简体   繁体   中英

add action listener to static context

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

i get an error on the last line that says 'controlledball.this cannot be referenced from a static context'

when i try the following technique instead of calling the stop() method i just change the values i need to change:

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

i get the error non-static field 'x' cannot be referenced from a static context...

the question is, from the main method how can i change the values of x and y which are declared in another method?

There are may ways you can solve this problem. A good suggestion is to probably create a custom ActionListener that holds a reference to the Object you want to change. For example, you could have:

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

Then you can just instantiate and use that class as an ActionListener :

stop.addActionListener(new MyListener(ball2)); 

This should help you organize your code and keep it clean and maintainable.

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