在 Swing 中强制立即布局和绘制
我似乎无法在 Swing 中强制进行布局。我将 JComponent
添加到 JLayeredPane
中,并在 JComponent
上设置了边框。然后,我想立即重新绘制所有内容 - 不是像 invalidate()
那样“请尽快执行此操作”,而是同步且立即重新绘制。有什么帮助吗?我似乎找不到正确的方法来做到这一点,并且我所有关于 invalidate()、validate()、repaint()、doLayout() 等的阅读都让我更加困惑!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据 this (请参阅标题为“同步绘画”的部分) PaintImmediately() 方法应该可以工作。
According to this (see the section titled "Synchronous Painting") the paintImmediately() method should work.
让 Swing 更新显示的最可靠方法是使用
SwingUtilities.invokeLater
。在你的情况下,看起来就像我意识到“invokelater”听起来并不像它立即执行任何操作,但实际上,与仅调用例如
somecomponent.repaint( 相比,以这种方式发布的事件往往执行得相当快)直接
。如果你绝对必须让你的控制代码等待GUI更新,那么还有invokeAndWait
,但我的经验是这很少有必要。另请参阅:Swing 中的有关事件调度的文档 。
The most reliable way to get Swing to update a display is to use
SwingUtilities.invokeLater
. In your case, it would look something likeI 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 alsoinvokeAndWait
, but my experience is that this is rarely necessary.See also: document on event dispatch in Swing.
这是非常旧的,但我找到了一个简单的解决方案,我将用 JPasswordField 来展示它:
This is super old, but I found a simple solution, which I'll show with a JPasswordField: