Java 在JComboBox箭头按钮上附加操作事件

Java 在JComboBox箭头按钮上附加操作事件,java,swing,jcombobox,look-and-feel,Java,Swing,Jcombobox,Look And Feel,我尝试将动作事件附加到JCombobox箭头按钮上 因此,我制作了一个自定义ComboBoxUI: public class CustomBasicComboBoxUI extends BasicComboBoxUI { public static CustomBasicComboBoxUI createUI(JComponent c) { return new CustomBasicComboBoxUI (); } @Override pro

我尝试将动作事件附加到JCombobox箭头按钮上

因此,我制作了一个自定义ComboBoxUI:

public class CustomBasicComboBoxUI extends BasicComboBoxUI {

    public static CustomBasicComboBoxUI createUI(JComponent c) {
        return new CustomBasicComboBoxUI ();
    }

    @Override
    protected JButton createArrowButton() {
        JButton button=super.createArrowButton();
        if(button!=null) {
            button.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    // arrow button clicked
                }
            });
        }
        return button;
    }
}
问题是combobox的外观不同,似乎是旧的外观。 为什么?我只向同一个箭头按钮添加了一个侦听器


谢谢。

可能是因为您希望JComboBox不是一个基本的ComboxUI,而是另一种外观,可能是一个MetalcomboxUI

您是否可以从现有JComboBox对象中提取JButton组件,而不是创建新的CustomBasicComboBoxUI对象?i、 e

import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class ComboBoxArrowListener {
   private static void createAndShowUI() {
      String[] data = {"One", "Two", "Three"};
      JComboBox combo = new JComboBox(data);
      JPanel panel = new JPanel();
      panel.add(combo);

      JButton arrowBtn = getButtonSubComponent(combo);
      if (arrowBtn != null) {
         arrowBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               System.out.println("arrow button pressed");
            }
         });
      }

      JFrame frame = new JFrame("ComboBoxArrowListener");
      frame.getContentPane().add(panel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   private static JButton getButtonSubComponent(Container container) {
      if (container instanceof JButton) {
         return (JButton) container;
      } else {
         Component[] components = container.getComponents();
         for (Component component : components) {
            if (component instanceof Container) {
               return getButtonSubComponent((Container)component);
            }
         }
      }
      return null;
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}