概要

ArrowButtonを隠して、JComboBoxの表示をJLabel風にします。

サンプルコード

Object[] items = {"JComboBox 11111:", "JComboBox 222:", "JComboBox 33:"};
UIManager.put("ComboBox.squareButton", Boolean.FALSE);
JComboBox comboBox = new JComboBox(items);
comboBox.setUI(new BasicComboBoxUI() {
  @Override protected JButton createArrowButton() {
    JButton button = new JButton(); //super.createArrowButton();
    button.setBorder(BorderFactory.createEmptyBorder());
    button.setVisible(false);
    return button;
  }
});
comboBox.setOpaque(true);
comboBox.setBackground(p.getBackground());
comboBox.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2));
comboBox.setFocusable(false);

UIManager.put("ComboBox.squareButton", Boolean.TRUE);
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、以下のようにしてJComboBoxの矢印ボタンを非表示に設定しています。

  • UIManager.put("ComboBox.squareButton", Boolean.FALSE)を設定してJComboBoxの高さと同じ幅ではなくArrowButtonの幅をそのまま使用するように変更
  • BasicComboBoxUI#createArrowButtonをオーバーライドしてArrowButtonの代わりに幅と高さが0setVisible(false)JButtonを作成
  • JComboBoxの背景色を親のJPanelと同じ色に変更
  • JComboBoxがフォーカスを取得不可になるよう設定

参考リンク

コメント