【问题标题】:add action listener to static context将动作侦听器添加到静态上下文
【发布时间】:2019-02-01 10:18:01
【问题描述】:
 public static void main(String[] args) {
        ControlledBall ball2 = new ControlledBall(12,2);
        JFrame window = new JFrame("Controlled Ball");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        window.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        JButton stop = new JButton("Stop");
        stop.setSize(4,400);
        stop.setVisible(true);
        stop.setText("Stop");
        stop.addActionListener(new Action());

我在最后一行显示“受控球。无法从静态上下文引用”

当我尝试以下技术而不是调用 stop() 方法时,我只是更改我需要更改的值:

stop.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                x= 0;
                y = 0;
           }
        });

我得到错误 non-static field 'x' cannot be referenced from a static context...

问题是,如何从主方法更改在另一个方法中声明的 x 和 y 的值?

【问题讨论】:

    标签: java button listener action


    【解决方案1】:

    您可以通过多种方式解决此问题。一个好的建议是创建一个自定义的ActionListener,其中包含对您要更改的对象的引用。例如,您可以:

    class StopListener implements ActionListener {
    
        private ControlledBall ball;
    
        public StopListener(ControlledBall ball) {
            this.ball = ball;
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            ball.stop(); // sets x and y to zero
        }
    }
    

    然后您可以实例化该类并将其用作ActionListener

    stop.addActionListener(new MyListener(ball2)); 
    

    这应该可以帮助您组织代码并使其保持整洁和可维护。

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      相关资源
      最近更新 更多