Can I restart some Swing component updates so that all replications run at once?

I have a bunch of buttons in my JToolBar, and I have determined that some of them will be disabled or enabled depending on the state of my application. When I update several buttons at once, I find that they are not all repainted at the same time. I want to make sure that when I set several buttons to turn off / on, they all change state at the same time.

Below is a small test demonstrating the problem. (To use the button icon, you need the a.png file in the current directory.) When you run it, a toolbar with 10 buttons is displayed. Pressing the "Enter" key on the terminal will disable the state of all buttons. On my machine, at least every time I do this, the buttons are repainted in a seemingly random order, and not all at once.

It seems that double buffering might solve the problem, although the first thing I tried (installing double buffering on JToolBar) did not seem to affect anything.

Thanks,

Cameron

import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.*;

public class Test {
    public static void main(String[] args) throws IOException {
        final JButton[] bs = new JButton[10];
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new JFrame("test");
                JToolBar t = new JToolBar();
                f.getContentPane().add(t);
                for (int i = 0; i < bs.length; i++) {
                    bs[i] = new JButton(new ImageIcon("a.png"));
                    t.add(bs[i]);
                }
                f.pack();
                f.setVisible(true);
            }
        });
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            r.readLine();
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    for (JButton b : bs) {
                        b.setEnabled(!b.isEnabled());
                    }
                }
            });
        }
    }
}
+5
source share
3 answers

, , . , , ? ?

(, ), , .

+2

, JDK6 XP.

. / , , .

, ? , .

+1

@camickr JDK6 Windows 7. EventQueue.invokeLater(), , , , EventQueue. invokeLater(). EDT (.. setEnabled() ActionListener ), .

@iny That's right, it just looks bad. I really thought that since all state changes occur during one EventQueue Runnable, the whole picture will occur immediately after its completion, but I think not. Your suggestion about calling repaint () on JToolBar really combined the whole picture for buttons, thanks! (As soon as my unregistered account (which, it seems to me, does not return) and my newly registered account are merged, I will accept your answer.)

0
source

All Articles