XHyper
XHyper

Reputation: 3

JLayeredPane not updating movement of JLabel

I have a for loop that changes the location of a JLabel in a JLayeredPane layout.

    c.setVisible(true);
    jLayeredPane.moveToFront(c);

    for (int i = 0; i < 1000; ++i) {
        c.setBounds(i, 500, 94, 136);
        System.out.println(c.getLocation());
        try {
            Thread.sleep(2);

        } catch (Exception e) {

        }
    }

This method is referencing to jLayeredPane, which is accessed from another class. It does indeed update the x value of the JLabel c, yet it does not show it on the screen.

What do I have to do to make it update in real time? I need this to run in order, not simultaneous to the next part of the program, thus I suppose multi-threading is disallowed.

Upvotes: 0

Views: 117

Answers (1)

camickr
camickr

Reputation: 324098

What do I have to do to make it update in real time?

Don't use Thread.sleep(). This will cause the Event Dispatch Thread (EDT) to sleep, which means the GUI can't repaint itself until the entire loop is finished executing.

For animation you need to use a Swing Timer

I need this to run in order, not simultaneous to the next part of the program

When the Timer fires the required number of times you then stop the Timer and invoke a method containing the rest of your code.

Also, you should not be hardcoding "1000" as the loop control. You have no idea what the resolution of the screen will be when code is executed on different screens. You can use the Toolkit class and the getScreenSize() methods to get the appropriate dimension to use based on your actual requirement.

Upvotes: 2

Related Questions