Force immediate layout and paint in Swing

后端 未结 3 934
北恋
北恋 2020-12-19 09:54

I cannot seem to force a layout in Swing. I have a JComponent added to a JLayeredPane and I set a border on the JComponent. Then, I wa

3条回答
  •  再見小時候
    2020-12-19 10:27

    The most reliable way to get Swing to update a display is to use SwingUtilities.invokeLater. In your case, it would look something like

    SwingUtilities.invokeLater(new Runnable {
                                 public void run() { 
                                    somecomponent.repaint();
                                 }
                               });
    

    I realize the 'invokelater' does not exactly sound like it does anything immediate, but in practice, events posted in this way tend execute pretty quickly compared to just calling e.g. somecomponent.repaint() directly. If you absolutely must make your control code wait for the GUI to update, then there is also invokeAndWait, but my experience is that this is rarely necessary.

    See also: document on event dispatch in Swing.

提交回复
热议问题