Java Swing How to - Hide and show JCombobox








Question

We would like to know how to hide and show JCombobox.

Answer

import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
/*  w w  w.j av a2  s .  c o  m*/
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame result = new JFrame();
    JComboBox<String> combobox = new JComboBox<>(new String[] { "foo", "bar",
        "aaa", "Hello World" });
    result.add(combobox, BorderLayout.CENTER);

    JCheckBox toggleVisibility = new JCheckBox("Toggle visibility");
    toggleVisibility.setSelected(combobox.isVisible());
    toggleVisibility.addItemListener(e -> {
      combobox.setVisible(e.getStateChange() == ItemEvent.SELECTED);
    });
    result.add(toggleVisibility, BorderLayout.SOUTH);

    result.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    result.pack();
    result.setVisible(true);

  }
}