Java Swing How to - Set the title of a JComboBox when nothing is selected








Question

We would like to know how to set the title of a JComboBox when nothing is selected.

Answer

import java.awt.BorderLayout;
import java.awt.Component;
/* w  ww . ja  v a2  s  .  c  o m*/
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

public class Main {
  public static final void main(String[] args) {
    JFrame frame = new JFrame();

    JPanel mainPanel = new JPanel();
    JPanel buttonsPanel = new JPanel();
    frame.add(mainPanel);
    frame.add(buttonsPanel, BorderLayout.SOUTH);

    String[] options = { "S", "G", "I","T" };

    JComboBox comboBox = new JComboBox(options);
    comboBox.setRenderer(new MyComboBoxRenderer("COUNTRY"));
    comboBox.setSelectedIndex(-1); 
    mainPanel.add(comboBox);

    JButton clearSelectionButton = new JButton("Clear selection");
    clearSelectionButton.addActionListener(e-> {
        comboBox.setSelectedIndex(-1);
    });
    buttonsPanel.add(clearSelectionButton);

    frame.pack();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}

class MyComboBoxRenderer extends JLabel implements ListCellRenderer {
  private String _title;

  public MyComboBoxRenderer(String title) {
    _title = title;
  }

  @Override
  public Component getListCellRendererComponent(JList list, Object value,
      int index, boolean isSelected, boolean hasFocus) {
    if (index == -1 && value == null)
      setText(_title);
    else
      setText(value.toString());
    return this;
  }
}