Hey guys,
I'm trying to make a digital version of this Simon says game, and I can't get the path entered from the player to save correctly.
Every color corresponds to a number, so Green = 0, Red = 1, Yellow = 2, and Yellow = 3.
The problem is that the playerPath is never resetting, so it will just add the current entered path to the path of last round, making it seem incorrect when compared to the original turnPath which is just a substring of the fullPath.
I attached all of the code below. Any help would be greatly appreciated.
import java.awt.Color;
import java.awt.event.*;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Simon implements ActionListener {
static JFrame f = new JFrame();
static JButton greenButton = new JButton("Green");
static JButton redButton = new JButton("Red");
static JButton yellowButton = new JButton("Yellow");
static JButton blueButton = new JButton("Blue");
static String playerPath = "";
static int turn = 1;
static int lostGame = 0;
static Random rand = new Random();
static String fullPath = "";
static String turnPath;
Simon() {
for (int i = 0; i < 100; i++) {
int maxIndex = 4;
int randomIndex = rand.nextInt(maxIndex);
fullPath = fullPath + randomIndex;
}
turnPath = fullPath.substring(0,turn);
prepareGUI();
buttonProperties();
}
public void prepareGUI() {
f.setSize(415,435);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void buttonProperties() {
greenButton.setBounds(0,0,200,200);
redButton.setBounds(200,0,200,200);
yellowButton.setBounds(0,200,200,200);
blueButton.setBounds(200,200,200,200);
greenButton.setBackground(Color.black);
redButton.setBackground(Color.black);
yellowButton.setBackground(Color.black);
blueButton.setBackground(Color.black);
greenButton.setOpaque(true);
redButton.setOpaque(true);
yellowButton.setOpaque(true);
blueButton.setOpaque(true);
greenButton.setForeground(Color.green);
redButton.setForeground(Color.red);
yellowButton.setForeground(Color.yellow);
blueButton.setForeground(Color.blue);
f.add(greenButton);
f.add(redButton);
f.add(yellowButton);
f.add(blueButton);
greenButton.addActionListener(this);
redButton.addActionListener(this);
yellowButton.addActionListener(this);
blueButton.addActionListener(this);
greenButton.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
greenButton.setBackground(Color.green);
}
#Override
public void mouseReleased(MouseEvent e) {
greenButton.setBackground(Color.black);
}
});
redButton.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
redButton.setBackground(Color.red);
}
#Override
public void mouseReleased(MouseEvent e) {
redButton.setBackground(Color.black);
}
});
yellowButton.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
yellowButton.setBackground(Color.yellow);
}
#Override
public void mouseReleased(MouseEvent e) {
yellowButton.setBackground(Color.black);
}
});
blueButton.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
blueButton.setBackground(Color.blue);
}
#Override
public void mouseReleased(MouseEvent e) {
blueButton.setBackground(Color.black);
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
//Recording user input
if (e.getActionCommand().matches("Green")) {
playerPath += "0";
}
else if (e.getActionCommand().matches("Red")) {
playerPath += "1";
}
else if (e.getActionCommand().matches("Yellow")) {
playerPath += "2";
}
else if (e.getActionCommand().matches("Blue")) {
playerPath += "3";
}
}
public static void main(String[] args) {
while (lostGame < 1) {
lightButtons();
try {
Thread.sleep(1000 + (1000*turn));
} catch (InterruptedException e) {
e.printStackTrace();
}
if (playerPath.equals(turnPath)) {
playerPath = "";
turn++;
}
else if (!(playerPath.equals(turnPath))) {
lostGame += 1;
System.out.println(playerPath);
System.out.println(turnPath);
System.out.println("GAME OVER" + '\n' + "Your Score: " + (turn-1));
}
}
}
public static void lightButtons() {
new Simon();
for (int i = 0; i < turnPath.length(); i++) { // iterates through string based on turn number
if (turnPath.charAt(i) == '0') {
greenButton.setBackground(Color.green); //* "Flashes" a color at appropriate box
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
greenButton.setBackground(Color.black); //*
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (turnPath.charAt(i) == '1') {
redButton.setBackground(Color.red); //*
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
redButton.setBackground(Color.black); //*
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (turnPath.charAt(i) == '2') {
yellowButton.setBackground(Color.yellow); //*
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
yellowButton.setBackground(Color.black); //*
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (turnPath.charAt(i) == '3') {
blueButton.setBackground(Color.blue); //*
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
blueButton.setBackground(Color.black); //*
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
} ```
You can reset a String variable by writing playerPath = "";
Related
The actionForward and actionBack functions are both throwing IndexOutofBounds exceptions and I cannot figure out why? I was tasked with making a very simple web browser with function back and forward buttons as well as a url address bar. When the ArrayList pageList has a size of 2 the buttons work as intended. However, once the pageList has a size of 3 or more they break.
class Proj03RunnerHtmlHandler extends JFrame implements HyperlinkListener{
JEditorPane html;
JButton backButton, forwardButton;
JTextField urlTextField;
ArrayList<String> pageList = new ArrayList<String>();
public Proj03RunnerHtmlHandler(String website) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Asg03");
pageList.add(website);
try{
if(website != null){
html = new JEditorPane(website);
html.setEditable(false);
html.addHyperlinkListener(this);
JPanel buttonPanel = new JPanel();
backButton = new JButton("Back");
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionBack();
}
});
buttonPanel.add(backButton);
urlTextField = new JTextField("http://www.somesite.com");
urlTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
showPage(new URL(urlTextField.getText()), true);
} catch(Exception ey){
ey.printStackTrace();
}
}
}
});
buttonPanel.add(urlTextField);
forwardButton = new JButton("Forward");
forwardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionForward();
}
});
buttonPanel.add(forwardButton);
JScrollPane scroller = new JScrollPane();
JViewport vp = scroller.getViewport();
vp.add(html);
this.getContentPane().add(buttonPanel, BorderLayout.NORTH);
this.getContentPane().add(scroller, BorderLayout.CENTER);
this.setSize(669,669);
this.setVisible(true);
}
} catch(Exception e){
e.printStackTrace();
}
}
public void hyperlinkUpdate(HyperlinkEvent e){
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED){
if (!(e instanceof HTMLFrameHyperlinkEvent)) {
try {
showPage(e.getURL(), true);
} catch(Exception ex){
ex.printStackTrace();
}
}
}
}
public void actionBack() {
try {
String currentUrl = html.getPage().toString();
int currentIndex = pageList.indexOf(currentUrl);
showPage(new URL(pageList.get(currentIndex - 1)), false);
} catch (Exception e){
e.printStackTrace();
}
}
public void actionForward() {
try {
String currentUrl = html.getPage().toString();
int currentIndex = pageList.indexOf(currentUrl);
showPage(new URL(pageList.get(currentIndex + 1)), false);
} catch (Exception e){
e.printStackTrace();
}
}
public void showPage(URL pageUrl, boolean addToList){
try {
URL currentUrl = html.getPage();
html.setPage(pageUrl);
if (addToList) {
int listSize = pageList.size();
if (listSize > 0) {
int pageIndex =
pageList.indexOf(currentUrl.toString());
if (pageIndex < listSize - 1) {
for (int i = listSize - 1; i > pageIndex; i--) {
pageList.remove(i);
}
}
}
pageList.add(pageUrl.toString());
}
urlTextField.setText(pageUrl.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (pageIndex < listSize - 1) {
for (int i = listSize - 1; i > pageIndex; i--) {
pageList.remove(i);
}
}
There's two obvious problems with this.
You should be removing only one page from the history.
If the page is at the end (pageIndex == listSize - 1), then you don't remove the page but do add a duplicate.
I am woring on simple example to use Wii Remote control on a Ev3 using Lejos 0.9.1-beta. I am using WiiRemoteJ and Bluecove 2.1.1-SNAPSHOT and the example works on my Mac, but I have the next error on my EV3:
Native Library bluecove_arm not available WR
I found a solution on the next link, but I don't know how to compile and create a new jar inside of the EV3.
Can you help me please?
This is my code
package test;
import wiiremotej.*;
import wiiremotej.event.*;
import com.intel.bluetooth.BlueCoveConfigProperties;
import lejos.hardware.lcd.LCD;
public class Wii extends WiiRemoteAdapter {
private WiiRemote remote;
private static boolean accelerometerSource = true;
private static int y = 0;
private static int lastY = 0;
public static void main(String args[]) {
System.setProperty(BlueCoveConfigProperties.PROPERTY_JSR_82_PSM_MINIMUM_OFF, "true");
WiiRemoteJ.setConsoleLoggingOff();
try {
LCD.drawString("Buscando WR", 0, 2);
WiiRemote remote = null;
while (remote == null) {
try {
remote = WiiRemoteJ.findRemote();
LCD.drawString("WR encontrado", 0, 2);
}
catch (Exception e) {
remote = null;
LCD.drawString("ERROR", 0, 2);
}
}
remote.addWiiRemoteListener(new Wii(remote));
remote.setAccelerometerEnabled(true);
remote.setSpeakerEnabled(false);
remote.setIRSensorEnabled(false, WRIREvent.BASIC);
remote.setLEDIlluminated(0, false);
remote.getButtonMaps().add(new ButtonMap(WRButtonEvent.HOME, ButtonMap.NUNCHUK, WRNunchukExtensionEvent.C,
new int[] { java.awt.event.KeyEvent.VK_CONTROL }, java.awt.event.InputEvent.BUTTON1_MASK, 0, -1));
final WiiRemote remoteF = remote;
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
remoteF.disconnect();
}
}));
} catch (Exception e) {
e.printStackTrace();
}
}
public Wii(WiiRemote remote) {
this.remote = remote;
}
public void accelerationInputReceived(WRAccelerationEvent evt) {
//Doblar derecha y izquierda
if(accelerometerSource){
lastY = y;
//300 es el centro
y = (int)(evt.getYAcceleration()/5*300)+300;
if( y < lastY - 2){
LCD.drawString("Izquierda", 3, 2);
}
else if( y > lastY + 2){
LCD.drawString("Derecha", 3, 2);
}
}
}
public void buttonInputReceived(WRButtonEvent evt) {
if (evt.isPressed(WRButtonEvent.ONE)){
LCD.drawString("Avanzar", 5, 2);
}
if (evt.isPressed(WRButtonEvent.TWO)){
LCD.drawString("Retroceder", 5, 2);
}
}
public void disconnected() {
System.out.println("Remote disconnected... Please Wii again.");
System.exit(0);
}
public void statusReported(WRStatusEvent evt) {
}
public void IRInputReceived(WRIREvent evt) {
}
public void extensionConnected(WiiRemoteExtension extension) {
System.out.println("Extension connected!");
try {
remote.setExtensionEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public void extensionPartiallyInserted() {
System.out.println("Extension partially inserted. Push it in more next time!");
}
public void extensionUnknown() {
System.out.println("Extension unknown. Did you try to plug in a toaster or something?");
}
public void extensionDisconnected(WiiRemoteExtension extension) {
System.out.println("Extension disconnected. Why'd you unplug it, eh?");
}
}
I've code like this:
public main() {
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(700, 500);
//tabbed pane
add(tb);
}
public JTextArea txtArea() {
JTextArea area = new JTextArea();
String st = String.valueOf(tab);
area.setName(st);
return area;
}
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new main();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source==mnew) {
tab++;
tb.add("Untitled-"+tab,new JPanel().add(txtArea()));
int s = tb.getSelectedIndex();
s = tb.getTabCount()-1;
tb.setSelectedIndex(s);
}
if(source==save) {
int s = tb.getSelectedIndex()+1;
}
Every click on the "New" menu item, code creates new tab with new panel and textarea (it's similar to a lot of text editors like notepad++).
After clicked "Save" in menu bar I want to get text from focused jtextarea.
Please help.
Add a document listener to the text area.
public JTextArea txtArea() {
JTextArea area = new JTextArea();
tstDocumentListener dcL = new tstDocumentListener();
area.getDocument().addDocumentListener(dcL);
String st = String.valueOf(tab);
area.setName(st);
return area;
}
tstDocumentListener
public class tstDocumentListener implements DocumentListener
{
public void changedUpdate(DocumentEvent e) {}
public void removeUpdate(DocumentEvent e)
{
String newString = "";
int lengthMe = e.getDocument().getLength();
try
{
newString = e.getDocument().getText(0,lengthMe);
System.out.println(newString);
}
catch(Exception exp)
{
System.out.println("Error");
}
}
public void insertUpdate(DocumentEvent e)
{
String newString = "";
int lengthMe = e.getDocument().getLength();
try
{
newString = e.getDocument().getText(0,lengthMe);
System.out.println(newString);
}
catch(Exception exp)
{
System.out.println("Error");
}
}
}
Edit
As for getting the text when you gain or lose focus on the text area
public JTextArea txtArea() {
JTextArea area = new JTextArea();
CustomFocusListener cFL = new CustomFocusListener();
area.addFocusListener(cFL);
String st = String.valueOf(tab);
area.setName(st);
return area;
}
CustomFocusListener
public class CustomFocusListener implements FocusListener
{
#Override
public void focusGained(FocusEvent e)
{
String parseMe = "";
JTextArea src;
try
{
src = (JTextArea)e.getSource();
parseMe = src.getText();
System.out.println(parseMe);
}
catch (ClassCastException ignored)
{
}
}
#Override
public void focusLost(FocusEvent e)
{
String parseMe = "";
JTextArea src;
try
{
src = (JTextArea)e.getSource();
parseMe = src.getText();
System.out.println(parseMe);
}
catch (ClassCastException ignored)
{
}
}
}
I just now trying to make a game where there are few borders on the map, which is being generated from a text document. The text document has 1s and 0s where ther is 1 it shows a wall. So how do I make it so the character stops infront of the wall
My Code:
MAIN CLASS:
public class JavaGame {
public static void main(String[] args) {
final Platno p = new Platno();
final JFrame okno = new JFrame("Test");
Mapa map = new Mapa();
okno.setResizable(false);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
okno.setSize(800, 600);
okno.setVisible(true);
map.nacti();
okno.add(p);
p.mapa = map;
okno.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int kod = e.getKeyCode();
if(kod == KeyEvent.VK_LEFT)
{
Platno.x -= 3;
p.repaint();
}
else if(kod == KeyEvent.VK_RIGHT)
{
Platno.x +=3;
p.repaint();
}
else if(kod == KeyEvent.VK_UP)
{
Platno.y -=3;
p.repaint();
}
else if(kod == KeyEvent.VK_DOWN)
{
Platno.y +=3;
p.repaint();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
/* Timer = new Timer(1, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
Platno.y -=3;
p.repaint();
}
}); */
}`
Map loader class:
public void nacti()
{
try (BufferedReader br = new BufferedReader(new FileReader("map1-1.txt")))
{
String radek;
int cisloRadku = 0;
while((radek = br.readLine()) != null)
{
for(int i = 0; i < radek.length(); i++)
{
char znak = radek.charAt(i);
int hodnota = Integer.parseInt(String.valueOf(znak));
pole[i][cisloRadku] = hodnota;
}
cisloRadku++;
}
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
}
public void vykresli(Graphics g)
{
try {
wall = ImageIO.read(ClassLoader.getSystemResource("Images/wall.gif"));
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
for(int i = 0; i < pole[0].length; i++)
{
for(int j = 0; j < pole.length; j++)
{
if(pole[j][i] == 1)
{
g.setColor(Color.RED);
// g.fillRect(j*40, i*40, 40, 40);
g.drawImage(wall, j*40, i*40, null);
}
}
}
}`
and the Hero class:
public class Hero {
public int poziceX;
public int poziceY;
public static boolean upB = false;
public static boolean downB = false;
public static boolean rightB = false;
public static boolean leftB = false;
BufferedImage up;
BufferedImage down;
BufferedImage right;
BufferedImage left;
public Hero()
{
try {
up = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Up.png"));
down = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Down.png"));
right = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Right.png"));
left = ImageIO.read(ClassLoader.getSystemResource("Images/Hero_Left.png"));
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
}
public void vykreslit(Graphics g)
{
if(upB == true)
{
g.drawImage(up, poziceX, poziceX, null);
}
else if(downB == true)
{
g.drawImage(down, poziceX, poziceX, null);
}
else if(leftB == true)
{
g.drawImage(left, poziceX, poziceX, null);
}
else if(rightB == true)
{
g.drawImage(right, poziceX, poziceX, null);
}
}`
Thanks for your help :)
You could calculate the 'future position' for a move, and test for collisions.
If a collision occur, dont'move, otherwise you're ok to move.
See if this logic can help you:
public boolean willCollide(int row, int col, Board map)
{
return map[row][col] == 1;
}
public void moveLeft(Hero hero, Board map)
{
//watch for index out of bounds!
int futureCol = hero.y - 1;
if (! willCollide(hero.row, futureCol)
hero.y = futureCol;
}
I am making an autocomplete application and the list of my words are coming from my database. I have a textfield and now I want to make a suggestion list that will appear below the field everytime I type something. Could you give me some hint or idea how to do it? Thanks in advance.
Much better if you use JCombobox but if you are using Jtextfield, I would rather suggest to you to use Jlist and put in JWindow since you are using textfield, thats what I've tried in my Dictionary application.
EDIT :
public class MainMenu extends JPanel
{
private final Connection connection;
private final Application application;
private JTextField word = new JTextField(10);
private final JButton translate = new JButton();
private final JComboBox translators = new JComboBox();
private final JButton search = new JButton();
private JList speechPartAndDefinitionWidget;
private final DefaultListModel speechPartAndDefinitionWidgetModel = new DefaultListModel();
private Translator translator;
private Suggestor suggestor;
private DefaultListModel translatedWidgetModel;
private JList translatedWidget;
private final DefaultListModel suggestionWidgetModel = new DefaultListModel();
private final JList suggestionWidget = new JList(suggestionWidgetModel);
private JavaWindow javaWindow = new JavaWindow(suggestionWidget);
public MainMenu(Application application, Connection connection)
{
word.getDocument().addDocumentListener(new DocumentListener()
{
public void insertUpdate(DocumentEvent e)
{
try
{
onWordUpdated(word.getText());
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
public void removeUpdate(DocumentEvent e)
{
try
{
onWordUpdated(word.getText());
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
public void changedUpdate(DocumentEvent e)
{
try
{
onWordUpdated(word.getText());
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
this.application = application;
this.connection = connection;
translators.setFocusable(false);
word.grabFocus();
word.requestFocus();
word.setFocusable(true);
search.setText("<html><b><u>S</u>earch</b></html>");
translate.setText("<html><b><u>T</u>ranslate</b></html>");
translators.addItem(new EnglishBisayaTranslator(connection));
setToolTipText("English-Bisaya");
translators.addItem(new BisayaEnglishTranslator(connection));
setToolTipText("Bisaya-English");
setLayout(new BorderLayout());
JPanel formX = new JPanel();
formX.setLayout(new BorderLayout());
JPanel header = new JPanel();
header.setLayout(new GridBagLayout());
header.add(translators);
header.add(word);
header.add(search);
header.add(translate);
translators.setBorder(BorderFactory.createEtchedBorder(1));
translators.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
word.setBorder(BorderFactory.createEtchedBorder());
word.setBorder(BorderFactory.createLineBorder(Color.gray, 1));
word.setFont(new Font("Garamond", Font.BOLD, 17));
suggestionWidget.setFont(new Font("Calibri", Font.BOLD, 17));
header.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 8));
formX.add(BorderLayout.PAGE_START, header);
formX.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 10));
add(header, BorderLayout.NORTH);
speechPartAndDefinitionWidget = new JList(speechPartAndDefinitionWidgetModel);
speechPartAndDefinitionWidget.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
speechPartAndDefinitionWidget.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent ev)
{
onDefinitionSelected(ev);
}
});
JPanel formBottom = new JPanel();
formBottom.setLayout(new GridBagLayout());
add(formBottom, BorderLayout.CENTER);
Component up = new JScrollPane(speechPartAndDefinitionWidget);
formBottom.setBorder(BorderFactory.createEmptyBorder(20, 10, 10, 10)); speechPartAndDefinitionWidget.setBorder(BorderFactory.createLineBorder(Color.black,1));
JPanel down = new JPanel();
down.setLayout(new BorderLayout());
down.setBorder(BorderFactory.createLineBorder(Color.black, 1));
down.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
down.add(translatedWidget = new JList(translatedWidgetModel = new DefaultListModel()));
add(down, BorderLayout.CENTER);
translatedWidget.setBorder(BorderFactory.createLineBorder(Color.black, 1));
translatedWidget.setFont(new Font("Calibri",Font.BOLD, 17));
speechPartAndDefinitionWidget.setFont(new Font("Calibri", Font.BOLD, 17));
add(BorderLayout.CENTER, new JSplitPane(JSplitPane.VERTICAL_SPLIT, up, down));
word.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
hideSuggestionWindowToBack();
}
else if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
int selectedIndex = suggestionWidget.getSelectedIndex();
if (selectedIndex == -1)
{
onSearchClick();
}
else
{
onSuggestionSelected(selectedIndex);
}
}
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
hideSuggestionWindowToBack();
onSearchClick();
}
}
});
translators.addActionListener(new
ActionListener()
{
public void actionPerformed
(ActionEvent e)
{
onTranslatorsClick();
}
}
);
word.addKeyListener(new
KeyAdapter()
{
public void keyPressed
(KeyEvent
e)
{
if (suggestionWidgetModel.isEmpty())
{
return;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
final Point location = word.getLocationOnScreen();
javaWindow.setLocation(location.x, location.y + word.getHeight());
showSuggestionWindowToBack();
int currentSelectedItemIndex = suggestionWidget.getSelectedIndex();
if (currentSelectedItemIndex == -1 || currentSelectedItemIndex == suggestionWidgetModel.size() - 1)
{
suggestionWidget.setSelectedIndex(0);
}
else if (currentSelectedItemIndex < suggestionWidgetModel.size() - 1)
{
suggestionWidget.setSelectedIndex(currentSelectedItemIndex + 1);
}
}
else if (e.getKeyCode() == KeyEvent.VK_UP)
{
int currentSelectedItemIndex = suggestionWidget.getSelectedIndex();
if (currentSelectedItemIndex == -1 || currentSelectedItemIndex == suggestionWidgetModel.size() + 1)
{
suggestionWidget.setSelectedIndex(0);
}
else if (currentSelectedItemIndex < suggestionWidgetModel.size() + 1)
{
suggestionWidget.setSelectedIndex(currentSelectedItemIndex - 1);
}
}
}
}
);
suggestionWidget.addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
int selectedIndex = suggestionWidget.getSelectedIndex();
if (e.getClickCount() == 2)
{
if (selectedIndex < -1)
{
onSearchClick();
}
else
{
onSuggestionSelected(selectedIndex);
hideSuggestionWindowToBack();
}
}
}
public void mouseReleased(MouseEvent e)
{
if (e.getClickCount() == 2)
{
{
hideSuggestionWindowToBack();
}
}
}
});
speechPartAndDefinitionWidget.addKeyListener(new
KeyAdapter()
{
#Override
public void keyPressed
(KeyEvent
e)
{
if (speechPartAndDefinitionWidgetModel.isEmpty())
{
return;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
int currentSelectedItemIndex = speechPartAndDefinitionWidget.getSelectedIndex();
if (currentSelectedItemIndex == -1 || currentSelectedItemIndex == speechPartAndDefinitionWidgetModel.size() - 1)
{
speechPartAndDefinitionWidget.setSelectedIndex(0);
}
else if (currentSelectedItemIndex < speechPartAndDefinitionWidgetModel.size() - 1)
{
speechPartAndDefinitionWidget.setSelectedIndex(currentSelectedItemIndex + 1);
onTranslate();
}
}
else if (e.getKeyCode() == KeyEvent.VK_UP)
{
int currentSelectedItemIndex = speechPartAndDefinitionWidget.getSelectedIndex();
if (currentSelectedItemIndex == -1 || currentSelectedItemIndex == speechPartAndDefinitionWidgetModel.size() + 1)
{
speechPartAndDefinitionWidget.setSelectedIndex(0);
}
else if (currentSelectedItemIndex < speechPartAndDefinitionWidgetModel.size() + 1)
{
speechPartAndDefinitionWidget.setSelectedIndex(currentSelectedItemIndex - 1);
}
}
}
}
);
speechPartAndDefinitionWidget.addMouseMotionListener(new MouseMotionAdapter()
{
#Override
public void mouseMoved(MouseEvent e)
{
final int x = e.getX();
final int y = e.getY();
final Rectangle cellBounds = speechPartAndDefinitionWidget.getCellBounds(0, speechPartAndDefinitionWidget.getModel().getSize() - 1);
if (cellBounds != null && cellBounds.contains(x, y))
{
speechPartAndDefinitionWidget.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
else
{
speechPartAndDefinitionWidget.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
}
);
speechPartAndDefinitionWidget.setCellRenderer(new
DefaultListCellRenderer()
{
#Override
public Component getListCellRendererComponent
(JList
list, Object
value, int index,
boolean isSelected,
boolean cellHasFocus)
{
final String speechPart = ((DefinitionUiModel) value).getPart().getFriendlyName();
final String definition = ((DefinitionUiModel) value).getDefinition().toString();
Color bg = null;
Color fg = null;
final JLabel renderer = new JLabel(
"<html><font color=red>" + speechPart + "</font>) => <font color=black>" + definition + "</font></html>");
if (renderer.isEnabled())
{
if (isSelected)
{
renderer.setText("<html><font color=gray>" + speechPart + "</font><font color=blue><u><b>" + definition + "</b></u></font></html>");
renderer.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
JList.DropLocation dropLocation = list.getDropLocation();
if (dropLocation != null
&& !dropLocation.isInsert()
&& dropLocation.getIndex() == index)
{
bg = DefaultLookup.getColor(this, ui, "List.dropCellBackground");
fg = DefaultLookup.getColor(this, ui, "List.dropCellForeground");
isSelected = true;
}
if (isSelected)
{
renderer.setBackground(bg == null ? list.getSelectionBackground() : bg);
renderer.setForeground(fg == null ? list.getSelectionForeground() : fg);
}
Border border = null;
if (cellHasFocus)
{
if (isSelected)
{
border = DefaultLookup.getBorder(this, ui, "List.focusSelectedCellHighlightBorder");
}
if (border == null)
{
border = DefaultLookup.getBorder(this, ui, "List.focusCellHighlightBorder");
}
}
else
{
}
}
return renderer;
}
}
);
translatedWidget.setForeground(Color.black);
translate.addActionListener(new
ActionListener()
{
public void actionPerformed
(ActionEvent
e)
{
onTranslate();
}
}
);
search.setToolTipText("find");
search.addActionListener(new
ActionListener()
{
public void actionPerformed
(ActionEvent
e)
{
onSearchClick();
}
}
);
translators.setSelectedIndex(0);
suggestionWidget.setBorder(BorderFactory.createLineBorder(Color.gray, 1));
onTranslatorsClick();
}
private void onSuggestionSelected(int selectedIndex)
{
String hold = (String) suggestionWidgetModel.getElementAt(selectedIndex);
word.setText(hold);
hideSuggestionWindowToBack();
suggestionWidgetModel.clear();
if (javaWindow == null)
{
javaWindow.dispose();
javaWindow = null;
}
}
public void onWordUpdated(final String toComplete) throws ClassNotFoundException, SQLException
{
new Thread(new Runnable()
{
public void run()
{
try
{
final List<Suggestion> suggestions = suggestor.getSuggestions(toComplete);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
speechPartAndDefinitionWidgetModel.clear();
translatedWidgetModel.clear();
suggestionWidgetModel.clear();
try
{
for (Suggestion suggestion : suggestions)
{
suggestionWidgetModel.addElement(suggestion.getCaption());
}
if (!suggestions.isEmpty())
{
suggestionWidget.setSelectedIndex(0);
if (javaWindow == null)
{
javaWindow = new JavaWindow(suggestionWidget);
}
else
{
final Point location = word.getLocationOnScreen();
javaWindow.setLocation(location.x, location.y + word.getHeight());
}
showSuggestionWindowToBack();
}
else
{
hideSuggestionWindowToBack();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
});
}
catch (SQLException e)
{
onSqlError(e);
}
}
}
, "onWordUpdated").
start();
}
private void onTranslate()
{
try
{
translatedWidgetModel.clear();
String lookupWord = word.getText();
if (lookupWord != null)
{
Collection<String> bisayaWords = this.translator.translateSimple(lookupWord);
for (String bisayaWord : bisayaWords)
{
translatedWidgetModel.addElement(bisayaWord.toUpperCase());
}
}
}
catch (SQLException ex)
{
onSqlError(ex);
}
}
private void onSqlError(SQLException ex)
{
JOptionPane.showMessageDialog(null, "SQL Error! :" + ex.getMessage());
}
private void onDefinitionSelected(ListSelectionEvent ev)
{
if (!ev.getValueIsAdjusting())
{
int selectedIndex = speechPartAndDefinitionWidget.getSelectedIndex();
if (selectedIndex != -1)
{
final DefinitionUiModel definitionUiModel = (DefinitionUiModel) speechPartAndDefinitionWidgetModel.get(selectedIndex);
translate(definitionUiModel.getDefinition());
}
}
}
private void translate(Definition definition)
{
try
{
translatedWidgetModel.clear();
Map<String, String> map = new HashMap<String, String>();
int definitionId = definition.getId();
String definitionName = definition.getValue();
int nameId = translator.getFromDictionary().getNameIdForDefinitionId(definitionId);
if (nameId > -1)
{
final Collection<String> translation = translator.translateSimple(nameId);
for (String transWord : translation)
{
map.put(transWord, definitionName);
for (Map.Entry<String, String> entry : map.entrySet())
{
String myValue = entry.getKey().toUpperCase() + " -- " + entry.getValue();
translatedWidgetModel.addElement(myValue);
}
}
}
}
catch (SQLException ex)
{
onSqlError(ex);
}
}
private void onSearchClick()
{
search.setEnabled(true);
hideSuggestionWindowToBack();
speechPartAndDefinitionWidgetModel.clear();
translatedWidgetModel.clear();
try
{
final String lookupWord = word.getText();
if (lookupWord != null)
{
final Dictionary fromDictionary = translator.getFromDictionary();
final WordDefinitions definitions = fromDictionary.getWordDefinitions(lookupWord);
final Iterator<Map.Entry<SpeechPart, List<Definition>>> items = definitions.iterator();
while (items.hasNext())
{
final Map.Entry<SpeechPart, List<Definition>> item = items.next();
for (Definition definition : item.getValue())
{
speechPartAndDefinitionWidgetModel.addElement(new DefinitionUiModel(item.getKey(), definition));
}
}
}
}
catch (SQLException ex)
{
onSqlError(ex);
}
}
private void onTranslatorsClick()
{
translator = (Translator) translators.getSelectedItem();
suggestor = new Suggestor(translator.getFromDictionary(), 10);
word.setEnabled(true);
application.setTitle(translator.toString());
translators.setToolTipText("tooltip : " + translator.toString());
speechPartAndDefinitionWidgetModel.clear();
}
private void hideSuggestionWindowToBack()
{
if (javaWindow == null)
{
return;
}
javaWindow.setVisible(false);
javaWindow.toBack();
}
private void showSuggestionWindowToBack()
{
if (javaWindow == null)
{
return;
}
javaWindow.setVisible(true);
javaWindow.toFront();
}
}
The algorithm (that I know of) behind the suggestions list is: Longest common substring problem. The problem is quite easy if you have stored the strings in the database in the form of a trie. Then the list of suggestions for the current prefix will be all those strings that start with the currently entered string. You will understand what I mean if you look at the Trie data structure.