Abbes
Abbes

Reputation: 21

two textfield update each other

I try to convert data but without clicking on a button, When I enter the data in the 1st textfield nothing happens

JTextField textC = new JTextField() ;
  JTextField textF = new JTextField() ;
  labelC.setText("Celsius");
  labelF.setText("Fahrenheit");

ActionListener textFieldCListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
    String value = textC.getText();
    try {
        float valC = new Float(value);
        float valF = valC * 1.8f + 32;
        textF.setText(Float.toString(valF));
    } catch (Exception exp) {
        textF.setText("");
        textC.setText("");
    }
}};

Upvotes: 0

Views: 39

Answers (2)

SDD
SDD

Reputation: 21

Try: textC.addActionListener(textFieldCListener);

Upvotes: 1

Azodious
Azodious

Reputation: 13872

You should add ActionListener to your JTextField object.

textC.addActionListener(textFieldCListener);

See this: What addActionListener does?

Upvotes: 1

Related Questions