Attach action Event on JComboBox arrow JButton
I try to attach action Events on the JCombobox arrow JButton.
So I make 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 with this is that the look of combobox is different, seem to be an old look. Why? I only add a listener to the same arrow button...
Thank.
Perhaps the problem is due to your expecting a JComboBox isn't a BasicComboBoxUI but one of another look and feel, perhaps a MetalComboBoxUI.
Rather than create 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();
}
});
}
}
精彩评论