简体   繁体   中英

Can I Use get and set on ActionListener? Why don't work?

See below:

/ this is my main /

package br.com.general;

public class Main {

    public static void main(String[] args) {

        Wind w = new Wind();
        w.start();

        while(true){
            //System.out.printf("%b\n", w.button());
            if(w.button()){
                System.out.printf("xx %b\n", w.button());
            }
        }

    }

}

/ this is my JFrame Window with one button /

package br.com.general;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Wind extends JFrame{

    private static final long serialVersionUID = 1L;
    Act a = new Act();

    public Wind() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JButton B = new JButton("on");

        getContentPane().setLayout(null);  

        B.setBounds(10, 10, 50, 30);
        B.addActionListener(a);

        add(B);
        setSize(100, 100);
    }

    public void start() {
        setVisible(true);
    }
    public boolean button(){
        return(a.button());
    }
    public void buttonOk(){
        a.zero();
    }
}

/*and in the end this is my ActionListener for my button */

package br.com.general;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Act implements ActionListener {
    boolean s;
    public void actionPerformed(ActionEvent ae) {
        s = true;

    }
    public boolean button(){
        return(s);
    }
    public void zero(){
        s = false;
    }
}

if you run, you can see that don't works, but if, in the main, you remove the "//" and enable the line "System.out.printf("%b\\n", w.button());" it starts functioning.... WHY? Somebody can help me?

This is a very good question! In an ideal world your code would run without issues, no matter if the first System.out.println(…) is commented out or not.

The problem is that Java optimizes your code and does not always retrieve the current value of your s flag in the Act class.

To circumvent this (in this case wrong) optimization, you can use the volatile modifier: volatile boolean s; . This requires the JVM to always retrieve the actual value from memory and prevents caching it, see Atomic Access in The Java Tutorials .

It looks you have hard infinite loop that consumes all the resources. You probably should insert small delay (ex, 10-100ms) into the loop. This can be done using Thread.wait() method. In your case delay is produced by System.out.printf(), since console output is quite slow.

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