简体   繁体   中英

How to get value from constantly changing variable

I'm creating some kind of menu (in swing), here's my code

public class JavaApplication5
{
    public static void main(String[] args) 
    {       
        NewJFrame frame = new NewJFrame();
        frame.setVisible(true);

        if(frame.getRunning() == true)
        {
           System.out.println("why it doesn't work");
        }
    }
}

And here is my menu class:

public class NewJFrame extends javax.swing.JFrame 
{
    public boolean isRunning = false;

    public void setRunning(boolean isRunning)
    {
        this.isRunning = isRunning;
    }

    public boolean getRunning()
    {
        return isRunning;
    }

    public NewJFrame() 
    {
        initComponents(); //this refers to auto-generated code by swing library
    }
    //some swing stuff...

    private void PlayActionPerformed(java.awt.event.ActionEvent evt) {                                     
        this.setRunning(true);
        System.out.println(getRunning());
    }
}

And the output is whenever i click on "Play" button: "true true true"

And here my question rises: Why in the output's console, the following line is not displayed "why it doesn't work" if I've changed that value from false to true (by pressing button)? How to call that constanly changing variable in the main function? Thanks in advance.

Your application does not block. It sets the JFrame to visible (ie displays the window) and then immediately checks whether frame.getRunning() == true . There's absolutely zero chance that you can hit the button before the condition is evaluated.

NewJFrame frame = new NewJFrame();
frame.setVisible(true);

// you're assuming the application waits here, but it does not

if(frame.getRunning() == true)
{
    System.out.println("why it doesn't work");
}

The way to solve this is either use a synchronization aid (maybe a CountDownLatch ) which will block your main thread or rethink the sequence of events that happen in your program. Perhaps you should register a listener / callback.

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