我正在寫我的第一個GUI程序,它實際上做了一些事情,我遇到了動作監聽器的問題。完成後的程序將需要雙重輸入,並根據我還沒有添加的單選按鈕選擇從一個單元轉換爲另一個單元。現在的問題是Action偵聽器無法識別我的文本字段。gui help ... with a actionListener
我在單獨的面板中有一個輸入文本字段和一個輸出文本字段。我創建了一個動作監聽器,並將輸入文本字段添加到了監聽器。
ActionListener handler = new HandlerClass(); textField.addActionListener(handler); 然後我爲處理程序類創建了一個類定義,但是當我編寫動作預執行方法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
}
}
}
}
這是美妙的建議,但問題是「OP如何」引用文本字段;) – MadProgrammer
我不能讓你。怎麼意思? – subash
最基本的問題是,OP難以解決他們想要訪問的文本字段的引用......如果您嘗試編譯OP代碼,它不會,因爲'textField'和'output'是未知變量... – MadProgrammer