在 Swing 中强制立即布局和绘制

发布于 2024-10-13 10:04:00 字数 297 浏览 1 评论 0原文

我似乎无法在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不语却知心 2024-10-20 10:04:00

根据 this (请参阅标题为“同步绘画”的部分) PaintImmediately() 方法应该可以工作。

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

此刻的回忆 2024-10-20 10:04:00

让 Swing 更新显示的最可靠方法是使用 SwingUtilities.invokeLater。在你的情况下,看起来就像

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

我意识到“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 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.

揪着可爱 2024-10-20 10:04:00

这是非常旧的,但我找到了一个简单的解决方案,我将用 JPasswordField 来展示它:

var pw = new JPasswordField();
...
pw.paint(pw.getGraphics()); // paints immediately

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文