简体   繁体   English

Java Swing revalidate()和repaint()问题

[英]Java Swing revalidate() and repaint() problem

I have a small java desktop application that needs to be able to add and remove fields dynamically by clicking "+" and "-" buttons respectively. 我有一个小的java桌面应用程序,需要能够分别单击“+”和“ - ”按钮动态添加和删除字段。 I have gotten this to work by calling revalidate() and then repaint() on all the parent containers all the way up to the JFrame in the ActionListener. 我通过调用revalidate()然后在所有父容器上重绘()一直到ActionListener中的JFrame来实现这一点。

This seemed to have done the trick, but occasionally it doesn't work and the JPanels don't resize correctly. 这似乎已经成功,但偶尔它不起作用,JPanels没有正确调整大小。 This happens infrequently and seemingly at random and lead me to believe it might be a concurrency issue. 这种情况很少发生并且看似随意,让我相信这可能是一个并发问题。 I have tried launching the parent container from the event dispatch thread but this hasn't solved the problem. 我已经尝试从事件派发线程启动父容器,但这还没有解决问题。

Is this actually a concurrency issue or am I barking up the wrong tree? 这实际上是一个并发问题还是我在错误的树上咆哮? Anyone have any idea what is going on and how it can be solved? 任何人都知道发生了什么以及如何解决这个问题?

Much appreciated 非常感激

-SwingNoob -SwingNoob

that isn't answer to OP's question nice example , OP's problem is maybe about LayoutManager and something unknow in OP's code OP的问题不是很好的例子 ,OP的问题可能是关于LayoutManager和OP代码中未知的问题

1/ if you adds a new JComponent to the Container then you have to call 1 /如果你向Container添加一个新的JComponent,那么你必须调用

validate();
repaint(); //lay with LayoutManager required that 

2/ if removes and then adds a JComponents from/to the Container then you have to call 2 /如果删除然后从容器中添加JComponents然后你必须调用

revalidate();
repaint(); // lay with LayoutManager required that 

3/ looks like as revalidate covered validate too, 3 /看起来像重新验证覆盖验证,

Launching the container from the AWT/EDT thread is not enough. 从AWT / EDT线程启动容器是不够的。

You need to execute every layout change to the container on the AWT/EDT thread. 您需要在AWT / EDT线程上对容器执行每个布局更改。

So if you make sure your add and remove are done that way, revalidate() or repaint() should not be necessary. 因此,如果您确保以这种方式完成添加和删除,则不需要revalidate()或repaint()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM