Java 无法使用我在ActionListener类中创建的按钮
我正在创建一个简单的窗口,它必须有一个文本字段和一个按钮Java 无法使用我在ActionListener类中创建的按钮,java,user-interface,actionlistener,Java,User Interface,Actionlistener,我正在创建一个简单的窗口,它必须有一个文本字段和一个按钮 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 Fi
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);
}
}
}
}
没关系。我在主类的边界之外创建了这个类。这就是为什么它不能识别变量。是的,这就是我这样做的原因。我记得去年做过类似的任务。但出于某种原因,我现在犯了这个错误。不知道出了什么问题。