Question

I have read about that when programming Java Swing, we should put these components into Java Event Queue, because Java Swing thread is not-thread safe.

But, when I use Event Queue, I don't know how to update component properties (for example : set text for label or change something..). Here is my code :

public class SwingExample {

    private JLabel lblLabel;    
    SwingExample(){
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        lblLabel = new JLabel("Hello, world!", JLabel.CENTER);
        frame.getContentPane().add(lblLabel); // adds to CENTER
        frame.setSize(200, 150);
        frame.setVisible(true);

    }

    public void setLabel(){
        lblLabel.setText("Bye Bye !!!");
    }



    public static void main(String[] args) throws Exception
    {
        SwingExample example = null;
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                example = new SwingExample(); // ERROR : Cannot refer to non-final variable inside an inner class defined in different method
            }
        });

        // sometime in the futures, i want to update label, so i will call this method...
        example.setLabel();
    }

}

I know, if I write SwingExample example = new SwingExample(); the error won't appear again, but if i use that, I cannot process example.setLabel later.

Please tell me about this error and how to fix this.

Thanks :)

Was it helpful?

Solution

By having your SwingExample instance as a field, you can reference it inside the inner classes without it being final.

public class SwingExample {

    private JLabel lblLabel;    
    private static SwingExample instance;    

    SwingExample() {
        // code omitted
    }

    public void setLabel() {
        lblLabel.setText("Bye Bye !!!");
    }

    public static void main(String[] args) throws Exception {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                instance = new SwingExample();
            }
        });

        // ...

        EventQueue.invokeLater(new Runnable() {
            public void run() {
              instance.setLabel();
            }
        });
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top