【问题标题】:Create not private object in constructor [duplicate]在构造函数中创建非私有对象[重复]
【发布时间】:2018-05-25 12:27:27
【问题描述】:

我在 java 中使用 swing 创建了一个表单,并且我有一个像这样的 Game 类:

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

现在我想在构造函数中创建 exit 事件,如下所示:

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

但我想创建一个这样的方法:

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

退出方法

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

}

但我无法在exitmethod 中访问btnExit

我试图将 btnExit 排除在构造函数之外,但是这样。app 无法正常工作。

【问题讨论】:

  • Member variable。查找它们并尝试调整您的代码。确保所有内容都在同一个类中
  • 你想使用字段,而不是局部变量!

标签: java swing variables methods scope


【解决方案1】:

您应该使您的 btnExit 成为 Game 类范围的一部分。类似的东西

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

【讨论】:

    猜你喜欢
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 2016-09-11
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多