我正在编写第一个实际执行某些操作的GUI程序,但我遇到了动作侦听器的问题。完成后的程序将进行双输入,并根据我尚未添加的一些单选按钮选项从一个单元转换到另一个单元。现在的问题是Action侦听器无法识别我的文本字段。
我在单独的面板中有输入文本字段和输出文本字段。我创建了一个动作监听器,并将输入文本字段添加到监听器。
ActionListener handler = new HandlerClass(); textField.addActionListener(处理程序); 然后我为处理程序类创建了一个类定义,但是当我编写动作时,预先形成的方法textField和输出无法由程序解析。谁能看到我做错了什么?
public class conversionDisplay extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel northPanel;
private JPanel southPanel;
private JPanel eastPanel;
private JPanel westPanel;
public conversionDisplay() {
super("Temperature Conversion");
northPanel = new JPanel(); //create northPanel
northPanel.setLayout(new GridLayout(1,2,5,5));
northPanel.add(new JPanel());
JPanel northLabelPanel = new JPanel(new BorderLayout()) ;
northLabelPanel.add(new JLabel("Input"), BorderLayout.EAST);
northPanel.add(northLabelPanel);
JTextField textField =new JTextField(10);
northPanel.add(textField);
northPanel.add(new JPanel());
southPanel = new JPanel(); //create southPanel
southPanel.setLayout(new GridLayout(1,2));
southPanel.add(new JPanel());
JPanel southLabelPanel = new JPanel(new BorderLayout());
southLabelPanel.add(new JLabel("Output "), BorderLayout.EAST);
southPanel.add(southLabelPanel);
JTextField output;
southPanel.add(output = new JTextField( 10));
output.setEditable(false);
southPanel.add(new JPanel());
add(northPanel,BorderLayout.NORTH); //add north panel
add(southPanel,BorderLayout.SOUTH); //add north panel
ActionListener handler = new HandlerClass();
textField.addActionListener(handler);
setSize(350, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent e) {
double input = textField.getText();
if (input != 0)
{
output.setText(input); //Perform conversion
}
}
}
}
答案 0 :(得分:2)
您必须将String解析为Double值
public void actionPerformed(ActionEvent e) {
double input = Double.parseDouble(textField.getText());
if (input != 0)
{
output.setText(input+""); //Perform conversion
}
}
并将JTextField output,textField
声明为Globel。
答案 1 :(得分:2)
您的textField JTextField是在构造函数内声明的,因此只能在该块中显示(同样是构造函数)。您需要将其设为类的实例字段。
即,
public class Foo {
private Bar bar = new Bar(); // this field is visible throughout the object
public Foo() {
Baz baz = new Baz(); // this is only visible within this constructor
}
因此,就像上面的bar变量可见而构造函数中声明的baz变量不可见时,您需要移动构造函数的JTextField变量声明 out 。
答案 2 :(得分:0)
public class conversionDisplay extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel northPanel;
private JPanel southPanel;
private JPanel eastPanel;
private JPanel westPanel;
JTextField output = new JTextField(10);
public conversionDisplay() {
super("Temperature Conversion");