获取JTextField的值

时间:2013-12-25 02:32:31

标签: java swing jtextfield temperature valuechangelistener

我正在制作一个转换温度的小型Swing小程序:TempConvert.java

这是我的代码:

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

每次convert() JTextField中的文字发生变化时,我都想调用deg函数。我有什么方法可以做到吗?

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

需要将监听器添加到textfield。添加以下代码段,它应该可以。

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

答案 1 :(得分:1)

目前,您的转换按钮附加了一个ActionListener。您需要为JTextField deg

实现相同的ActionListener

或者您尝试编码,以便在获得文本字段的事件时,使用postActionEvent

将事件发布到按钮
相关问题