I work with Swing for quite some time, but there's one thing that's bugging me all the time - when you dynamically show/hide some components, the container is not resized appropriately. That means that some components are cut off or hidden beyond the container edge. Maybe I'm just doing something wrong, can somebody help me?
The easiest example is here. I'll create a label that is hidden by default. When I dynamically show it, the frame/panel is not enlarged and therefore the label is not visible until the user manually resizes the frame/panel. Only after that you can see it.
(Usually I use the layout manager used when designing UIs in NetBeans, but I hope these default layout managers will demonstrate the same problem.)
import java.awt.event.*;
import javax.swing.*;
public class DynamicComponentDemo {
private static void createAndShowGUI() {
final JFrame frame = new JFrame("Dynamic Component Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
final JPanel panel = new JPanel();
frame.add(panel);
final JCheckBox checkbox = new JCheckBox("Show label");
final JLabel label = new JLabel("This is a label!");
checkbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setVisible(checkbox.isSelected());
}
});
label.setVisible(false);
panel.add(checkbox);
panel.add(label);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
What can I do to force the frame/panel to resize appropriately when some new component is shown? Moreover, can you point me to some documentation regarding these matters?
Thanks.