Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Container resizing when dynamically showing/hiding components

809575Oct 31 2010 — edited Nov 14 2010
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.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 12 2010
Added on Oct 31 2010
19 comments
2,049 views