Java Swing How to - Attach action Event on JComboBox arrow JButton








Question

We would like to know how to attach action Event on JComboBox arrow JButton.

Answer

import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*w w  w .  j ava2 s . c o m*/
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main {
  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) {
    JComboBox<String> combo = new JComboBox<>(new String[]{ "One", "Two", "Three" });
    JButton arrowBtn = getButtonSubComponent(combo);
    if (arrowBtn != null) {
      arrowBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          System.out.println("arrow button pressed");
        }
      });
    }
    JFrame f = new JFrame();
    f.getContentPane().add(combo);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setVisible(true);
  }
}