![](/img/trans.png)
[英]Can I use BufferedReader and create an array inside actionListener class?
[英]Cannot use the button I created inside the ActionListener class
我正在創建一個簡單的窗口,它必須有一個文本字段和一個按鈕。
public class Find_Suspect_Window extends JFrame{
private JPanel panel=new JPanel();
private JTextField findName = new JTextField("Enter the name");
private JButton findButton = new JButton("Find");
public Find_Suspect_Window() {
panel.add(findName);
panel.add(findButton);
this.setContentPane(panel);
FindListener f = new FindListener();
mouse m = new mouse();
findName.addMouseListener(m);
findButton.addActionListener(f);
this.setVisible(true);
this.setSize(300, 100);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setTitle("Find Suspect");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
之后,我在實現 ActionListener 的同一個類文件中創建一個類,這樣我就可以讓按鈕做一些事情。
class FindListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == findButton) {
String n = findName.getText();
}
}
}
我在這里收到一個錯誤,提示 findButton 無法解析為變量,並且 findName 無法解析。 我知道它們不是同一個類的一部分,但我需要使用該按鈕和該字段來執行所有必要操作以使按鈕正常運行。
我錯過了什么? 有什么我必須改變或添加一些東西才能讓它工作的嗎?
如果您准確地描述了所有內容,那么應該沒有問題。 請參閱下面的示例:
class A extends JFrame {
private JButton button = new JButton ();
private int a;
{
button.addActionListener (new B ());
}
class B implements ActionListener {
@Override
public void actionPerformed (ActionEvent e) {
if (e.getSource () == button) {
System.out.println (a);
}
}
}
}
沒關系。 我在主類的邊界之外創建了這個類。 這就是它無法識別變量的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.