Making a JButton that switches text from 2 JTextFields on click with mouse

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.

Upvotes: 1

Views: 91

Answers (2)

Xabster
Xabster

Reputation: 3720

You need a temporary variable to store it in.

Right now field2 is first set to whatever is in field1, and then you set field1 to what you just set field2 to. You must save the content temporarily before you overwrite it:

String temp = field2.getText();
field2.setText(field1.getText());  
field1.setText(temp);

Upvotes: 2

Jens
Jens

Reputation: 69470

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);  
    }  

Upvotes: 3

Related Questions