So I have a button that when pressed needs to write the current mouse position out to a text box until the user presses shift, then it stops and leaves the most recent mouse position as the final text in the text box. Heres what I have done:
First a created the following class.
public class KeyListener extends KeyAdapter {
private boolean wasPressed = false;
private int keyCode;
public KeyListener(int keyCode) {
this.keyCode = keyCode;
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println("CALLED");
if(e.getKeyCode() == keyCode)
wasPressed = true;
}
public void setState(boolean state) {
wasPressed = state;
}
public boolean getState() {
return wasPressed;
}
}
Then in my "main" class I have the following code.
JButton track1 = new JButton("Track");
KeyListener kl = new KeyListener(KeyEvent.VK_SHIFT);
...
public DisplayFrame() {
this.addKeyListener(kl);
track1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event) {
kl.setState(false);
while(!kl.getState()) {
Point p = MouseInfo.getPointerInfo().getLocation();
topLeft.setText(p.getX() + "," + p.getY());
}
}
});
}
I then of course added the text box to a JPanel and it's displaying everything correctly, however, when I click the Track button nothing happens. I can tell that it is entering the loop, but no text is displayed in the textbox and pressing shift doesn't break the loop.