简体   繁体   中英

Cannot use the button I created inside the ActionListener class

I am creating a simple window that has to have a text field and a button.

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


   }

}

After that I am creating a class inside the same class file that implements ActionListener so I can have the buttons do something.

class FindListener implements ActionListener{


   public void actionPerformed(ActionEvent e){

       if(e.getSource() == findButton) {

           String n = findName.getText();

       }

   }
}

I get an error here that says that findButton cannot be resolved to a variable and findName cannot be resolved. I get it that they are not part of the same class but I need to use that button and that field to do all the necessary to make the button function properly.

Did I miss something? Is there something I have to change or add something for it to work?

If you described everything exactly than no problems should be. See the example below:

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

    }

}

Never mind. I created the class outside of the boundaries of the main class. That is why it wasn't recognizing the variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM