user1830252
user1830252

Reputation: 33

JComboBox does not play well with GroupLayout

I ran into a strange kind of behavior when putting JComboBox components inside a GroupLayout. I've reduced the code to the below minimal example, featuring exactly one JComboBox layed out by GroupLayout.

The observed behavior is as follows:

What I've found out already:

This is the sample code - comments are welcome:

import java.awt.BorderLayout;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JRootPane;

public class DummyUI_cbdiagnosis extends javax.swing.JPanel {
    private javax.swing.JComboBox cbCategory;

    public DummyUI_cbdiagnosis() {
        initComponents();
    }

    private void initComponents() {
        cbCategory = new JComboBox();
        cbCategory.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                "a", "b", "c" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addComponent(cbCategory,
                        javax.swing.GroupLayout.PREFERRED_SIZE,
                        javax.swing.GroupLayout.PREFERRED_SIZE,
                        javax.swing.GroupLayout.PREFERRED_SIZE)));
        layout.setVerticalGroup(layout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addComponent(cbCategory)
        ));
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JRootPane rootPane = frame.getRootPane();
        rootPane.setLayout(new BorderLayout());

        DummyUI_cbdiagnosis panel = new DummyUI_cbdiagnosis();
        rootPane.add(panel, BorderLayout.NORTH);

        frame.pack();
        frame.setVisible(true);
    }
}

Upvotes: 3

Views: 566

Answers (1)

Mordechai
Mordechai

Reputation: 16292

Never ever add components to the RootPane itself, rather add them to the contentPane.

frame.add(panel);

or

frame.setContentPane(panel);

A RootPane has control of where to put the:

  • Menu bar.
  • Content.
  • Glass pane.
  • And most important, lightweight popups (inc. JComboBox), dialogs, drag and drops, etc.

RootPane uses a special layout manager called RootLayout, and shouldn't be changed to BorderLayout.

Upvotes: 6

Related Questions