4

All,

I have a form type view I'm creating in Java. Based on the contents of a combobox, I need to switch some aspects of the form. I am using a cardlayout to do this, and it works fine.

The problem is that cardlayouts use the maximum of all preferred sizes of the components added to them to determine their own preferred size. This means that when I've chosen an option that has fewer fields, there is blank space due to the preferred size of the cardlayout on the switcher component.

I've tried to manually change the preferred size of the cardlayout panel each time the selection changes, but this has no effect - the panel is always the maximum that fits all the components.

combo.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            Dimension preferredSize = null;
            switch (combo.getSelectedIndex()) {
                case 0:
                    preferredSize = panel0.getPreferredSize();
                    break;
                case 1:
                    preferredSize = panel1.getPreferredSize();
                    break;
                case 2:
                    preferredSize = panel2.getPreferredSize();
                    break;
                default:
                    assert false;
            }
            patternOptions.setPreferredSize(preferredSize);
            c.show(patternOptions, TYPE[combo.getSelectedIndex()]);
        }
    });

In a nutshell I'd like for the UI to dynamically grow when an option is chosen that needs more space, and shrink when it needs less space, just like the iTunes smartlist UI:

alt text alt text

(I realize that this is a slightly different issue, but it's illustrative of what I want - that panel holding the constraint fields is growing based on the number of rows. I need my layout to grow based on the number of options, based on the combobox selection)

I82Much
  • 26,901
  • 13
  • 88
  • 119

2 Answers2

2

You could subclass CardLayout and override the preferredLayoutSize method so that it only considers the current card.

To make sure the frame grows and shrinks you may need to call pack after setting the size of the content. Not sure if that will work in all cases (it may not shrink) but it's worth a shot.

Cameron Skinner
  • 51,692
  • 2
  • 65
  • 86
1

Sounds like you should be using an JDialog for each form.

Or don't bother using a CardLayout and manually remove/replace each panel and then pack() the dialog.

camickr
  • 321,443
  • 19
  • 166
  • 288