Java – pack, but don’t make it smaller
I have JFrame with gridbaglayout Users can resize this window In addition, he can perform some editing operations to change the window size I use pack (); Redraw (); Now after such action But in fact, I shouldn't make the window smaller after such an operation - just bigger The solution I found was
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 In addition to the ugly code, we set the size twice (one package at a time instead of directly) Are there any other solutions?
Solution
A simple solution is to use something like this:
frame.setMinimumSize(frame.getSize()); frame.pack(); frame.setMinimumSize(null);
I don't think this will allow pack () to make the window smaller and larger By resetting the minimum size to null after pack (), we prevent the user from adjusting its size later.
You should not need a repaint () at the end. The size change should trigger redrawing itself (of course, please ensure that all these operations occur in the event dispatch thread.)