JDialog fails to pack(), only sometimes

2019-07-22 20:33发布

问题:

I have written a nifty thing in Java with a GUI that includes a JDialog that starts out rather small and then uses pack() to accommodate things the progam later puts in it. All of this is going on before the JDialog renders.

Then, to my surprise, about 80% of the time, when I run it, the window fails to resize. It seems to be entirely random, as it's theoretically doing exactly the same thing every time. Why on Earth would it do something different with the same code on the same machine five seconds later?

This problem, by the way, popped up when I enabled the native Windows look-and-feel for this GUI.

回答1:

In my experience, when the GUI does random funny stuff like this, it might be a symptom of not doing all your GUI calls on the Event Dispatch Thread.

Make sure all your GUI calls from non-GUI threads are wrapped in SwingUtilities.invokeLater or invokeAndWait.

A quick google search turned up what seems to be a nifty way to check that your application conforms to the EDT-rules: http://thejavacodemonkey.blogspot.com/2007/08/using-aspectj-to-detect-violations-of.html