Get Value of JTextField Changed

230 views Asked by At

I am making a small java Swing Applet that converts temperatures: TempConvert.java

Here is my code:

package swing;

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

/** Celcius to Fahrenheit Converter
 * @version 1.0
 * @author Oliver Ni
 */

public class TempConvert extends JApplet{
    JLabel result;
    JRadioButton ctof;
    JRadioButton ftoc;
    JTextField deg;
    JLabel degLab;
    JButton convert;

    public void convert() {
        if (ctof.isSelected() == true) {
            result.setText("<html><br>" + Integer.toString(Integer.parseInt(deg.getText()) * 9 / 5 + 32) + "<sup>o</sup> F</html>");
        } else if (ftoc.isSelected() == true) {
            result.setText("<html><br>" + Integer.toString((Integer.parseInt(deg.getText()) - 32) * 5 / 9) + "<sup>o</sup> C</html>");
        } else {
            result.setText("<html><br>Error.</html>");
        }
    }

    public void makeApplet() {
        setLayout(new FlowLayout());
        ctof = new JRadioButton("Celcius to Fahrenheit");
        ftoc = new JRadioButton("Fahrenheit to Celcius");
        convert = new JButton("Convert");
        result = new JLabel("");
        ButtonGroup group = new ButtonGroup();
        group.add(ctof);
        group.add(ftoc);

        deg = new JTextField(10);
        degLab = new JLabel("<html><sup>o</sup></html>");
        convert.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                convert();
            }
        });
        add(ctof);
        add(ftoc);
        add(deg);
        add(degLab);
        add(convert);
        add(result);
    }

    public void init() {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    makeApplet();
                }
            });
        } catch(Exception e) {
            System.out.println("Error loading because " + e);
        }
    }
}

I want to call the convert() function every time the text in the JTextField deg is changed. Is there any way I can do that?

Any help would be appreciated!

2

There are 2 answers

1
Dark Knight On BEST ANSWER

Need to add listener to textfield. Add following snippet and it should work.

deg.getDocument().addDocumentListener(new DocumentListener() {
    public void changedUpdate(DocumentEvent e) {
        convert();
    }
    public void removeUpdate(DocumentEvent e) {
        convert();
    }
    public void insertUpdate(DocumentEvent e) {
        convert();
    }
});
0
Scary Wombat On

Currently you have an ActionListener attached to your convert button. You need to implement the same ActionListener for the JTextField deg

Or you code try so that when you get an event for the textfield you post an event to the button using postActionEvent