Attach Event to JComboBox arrow JButton

I am trying to attach actions to events on JCombobox arrow JButton.

So, I create a custom 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; } } 

The problem is that the look of the combobox is different, it seems the old look. What for? I add only the listener to the same arrow button ...

Thanks.

+4
source share
1 answer

Perhaps the problem is because you expect JComboBox to be not BasicComboBoxUI, but one from a different look, possibly MetalComboBoxUI.

Instead of creating a new CustomBasicComboBoxUI object, could you extract the JButton component from an existing JComboBox object? 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(); } }); } } 
+4
source

Source: https://habr.com/ru/post/1340523/


All Articles