Java Swing How to - Hide arrow button from JComboBox








Question

We would like to know how to hide arrow button from JComboBox.

Answer

//from   ww  w.j a  v  a2  s . c o m
import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicComboBoxUI;

public final class Main {
  public static void main(String[] args) {
    String[] items = {"A", "B", "C"};
    JComboBox<String> comboBox1 = new MyComboBox1<>(items);
    JPanel p = new JPanel();
    p.add(comboBox1);
    
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(p);
    f.setSize(320, 240);
    f.setVisible(true);
  }
}

class MyComboBox1<E> extends JComboBox<E> {
  public MyComboBox1(E[] list) {
    super(list);
  }
  @Override public void updateUI() {
    super.updateUI();
    UIManager.put("ComboBox.squareButton", Boolean.FALSE);
    setUI(new BasicComboBoxUI() {
      @Override protected JButton createArrowButton() {
        JButton b = new JButton();
        b.setBorder(BorderFactory.createEmptyBorder());
        b.setVisible(false);
        return b;
      }
    });
    setBorder(BorderFactory.createLineBorder(Color.GRAY));
  }
}