Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JTextField KeyListener 1 key stroke behind

808423Mar 13 2011 — edited Mar 13 2011
I have a program with a JTextField where the user inputs a variable. when it receives user input (any input) I want it to update things that rely on that variable such as labels and things like that. however when I type it lags behind in the key strokes. say I type in "keys". when I type the first letter nothing appears to update. when I finish typing the updated texts will say "key". below is some code representing the problem. Type in the first box and you can see what I mean.

is there a way to make fix this to make it real time or is there a better way to do this?
public class Gui extends JFrame {
	JTextField field1;
	JTextField field2;
	public Gui(){
		this.setLayout(new FlowLayout());
		field1 = new JTextField(5);
		field2 = new JTextField(5);		
		field1.addKeyListener(new Adapter());
		this.add(field1);
		this.add(field2);
	}
	
	public class Adapter extends KeyAdapter{
		public void keyPressed(KeyEvent e){
			field2.setText(field1.getText());
		}
	}
	
	public static void main(String[] args) {
		Gui gui = new Gui();
		gui.pack();
		gui.setVisible(true);
		gui.setLocationRelativeTo(null);
		gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 10 2011
Added on Mar 13 2011
1 comment
221 views