I have JFrame with GridBagLayout. User can resize this window. Also, he can perform some editing actions that change window size. I use pack(); repaint(); now after such actions. But, actually I shouldn’t make window smaller after such operations – only bigger. What I found as solution is
Dimension oldSize = getSize();
pack();
Dimension newSize = window.getSize();
setSize(
(int) Math.max(newSize.getWidth(), oldSize.getWidth()),
(int) Math.max(newSize.getHeight(), oldSize.getHeight()));
repaint();
But I don’t like this solution at all. Beside ugly code, we set size twice (once by pack and than directly). Is there any other solutions?
A simple solution would be to use something like this:
This will not allow
pack()to make the window smaller, only bigger, I think.By resetting the minimum size to
nullafter thepack()we avoid preventing the user on resizing it smaller afterwards.You should not need a
repaint()at the end, the size changing should trigger a repaint by itself. (Of course, make sure that all these actions happen in the event dispatch thread.)