Force immediate layout and paint in Swing

感情迁移 提交于 2019-11-28 04:04:14

问题


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 want to immediately re-draw everything - not in the sense of "please do this asap" like invalidate(), but synchronously and immediately. Any help? I cannot seem to find the right method of doing this, and all my reading about invalidate(), validate(), repaint(), doLayout(), etc is just confusing me more!


回答1:


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




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/4761374/force-immediate-layout-and-paint-in-swing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!