I have made a window using JFrame and on my JPanel I have added 3 components: 2 JTextFields ("field1" and "field2") and inbetween them a JButton ("switch"). My goal is to switch the value of field1 to field2 and vice versa when the JButton is clicked. I thought this ActionListener which I have added to my JButton would achieve my goal:
public void actionPerformed(ActionEvent e) {
field2.setText(field1.getText());
field1.setText(field2.getText());
}
However, it changes the value of field2 into the value of field1 but not the other way around.
Any help would be appreciated.
You need a temporarily variable todo. If you do not use on, you set the text from field1 to field2 and then you get the wrong value.
public void actionPerformed(ActionEvent e) {
String tmp= field2.getText()
field2.setText(field1.getText());
field1.setText(tmp);
}