0

I created a form with swing in java and i have a Game class like this :

public class Game extends JFrame {
     public Game() {
          JPanel contentPane = new JPanel();
          JDesktopPane desktopPane = new JDesktopPane();
          JButton btnExit = new JButton("Exit");
    }
}

Now i want to create exit event in constructor like this:

 btnExit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });

But i want to create a method like this :

btnExit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            exitmethod();
        }
    });

exitmethod :

private void exitmethod() {
     if (btnExit.getText().equals("1")){
         system.exit(0);
     }

}

But i can't access btnExit in exitmethod.

I tried to put btnExit out of constructor but it this way.app didn't work correct.

1 Answers1

0

Your should make your btnExit to be the part of Game class scope. Something like

public class Game extends JFrame {
    private JButton btnExit;
    public Game() {
        JPanel contentPane = new JPanel();
        JDesktopPane desktopPane = new JDesktopPane();
        this.btnExit = new JButton("Exit");
    }
}
jahra
  • 1,173
  • 1
  • 16
  • 41