Java Swing How to - Create new UI for JComboBox








Question

We would like to know how to create new UI for JComboBox.

Answer

import java.awt.Container;
import java.awt.FlowLayout;
/*from   ww  w  .j  a  v a2  s  .c  o m*/
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.UIManager;

public class Main extends JFrame {
  JComboBox<String> comboBox;

  Main() {
    String[] items = { "Item1", "Item2" };
    comboBox = new JComboBox<>(items);
    Container c = getContentPane();
    c.setLayout(new FlowLayout());
    c.add(comboBox);
    comboBox.setUI(new MyUI());
  }

  public JFrame getCurrentInstance() {
    return this;
  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.pack();
    frame.setVisible(true);
  }

}

class MyUI extends javax.swing.plaf.basic.BasicComboBoxUI {
  private ImageIcon infoIcon = (ImageIcon) UIManager
      .getIcon("OptionPane.informationIcon");
  private ImageIcon warnIcon = (ImageIcon) UIManager
      .getIcon("OptionPane.warningIcon");

  @Override
  protected JButton createArrowButton() {
    JButton btn = new JButton();
    btn.setIcon(infoIcon);
    btn.setRolloverIcon(warnIcon);
    return btn;
  }
}