javaswingjpaneljcomboboxcardlayout

JComboBox showing only if it has a single item


I have a JPanel with a CardLayout and a JComboBox inside it. They are dinamically filled with data taken from a JTable. If the JComboBox has a single item it shows just fine, but if I fill it with more than one it doesn't show.

JPanel intervalPanel = new JPanel;
CardLayout intervalLayout = new CardLayout();
intervalPanel.setLayout(intervalLayout);
JComboBox intervalComboBox = new JComboBox();
for (int i = 0; i < table.getRowCount(); i++) {
    String name = (String) table.getValueAt(i, 0);
    intervalComboBox.addItem(name);
    JPanel p = new JPanel();
    p.setName(name);
    p.add(intervalComboBox);
    p.add(new JLabel(name));
    intervalPanel.add(p, name);
}

Solution

  • A Swing component can only have a single parent.

    p.add(intervalComboBox);
    

    The above statement keeps removing the combo box from the previous panel and adds it to the current panel.

    but if I fill it with more than one it doesn't show.

    So the reason it doesn't show is because it is only visible on the last card, but you current see the first card.

    The better solution is to NOT add the combo box to the panel in the CardLayout. Instead your main panel should use a BorderLayout. Then the basic logic would be something like:

    JPanel main = new JPanel( new BorderLayout() );
    
    JComboBox comboBox = new JComboBox(...);
    main.add(comboBox, BorderLayout.PAGE_START);
    
    JPanel card = new JPanel( intervalLayout );
    main.add(card, BorderLayout.CENTER);
    
    frame.add( main );
    

    Then you just add child panels to the "card" panel as required.

    Read the section from the Swing tutorial on How to Use CardLayout for a complete working demo that uses the above design concept.