I’ve getInput method that takes string from text field on enter click. I’ve created while loop to wait until onClickListener returns true (pressed Enter). Here’s my code:
public String getInput(){
jTextField1.setEditable(true);
jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
temp=jTextField1KeyPressed(evt);
};
});
while(!(temp)){
}
temp=false;
jTextField1.setEditable(false);
String s= jTextField1.getText();
jTextField1.setText("");
return s;
}
private boolean jTextField1KeyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER)
return true;
else return false;
};
Now I have very strange problem: if I add System.out.println sentence in while loop, it works perfectly, if I remove it, while loop never exits. Where is problem?
Thanks in advance.
You would need some synchronization so that the changes to
tempare propagated to all required threads. But it’s a bad approach to start with –getInputwill waste a lot of CPU looping in thatwhilefor no good purpose.You could do it more cleanly. First, declare
tempto be ajava.lang.Object, and initialize it to a plain old Object:(or something like that.)
In getInput, instead of this:
put this:
And in the event handler:
This way, the thread running
getInputstays asleep waiting for something to happen rather than burning CPU cycles.There are also variants of
wait()that take a timeout value. You might be interested in using those too.