Force immediate layout and paint in Swing

后端 未结 3 932
北恋
北恋 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:00

    According to this (see the section titled "Synchronous Painting") the paintImmediately() method should work.

    0 讨论(0)
  • 2020-12-19 10:19

    This is super old, but I found a simple solution, which I'll show with a JPasswordField:

    var pw = new JPasswordField();
    ...
    pw.paint(pw.getGraphics()); // paints immediately
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题