I'm trying to use a JButton as an editor within a JComboBox. On Mac OS X this looks fine, but on Windows using the system look and feel, there is an ugly gap left between the JButton editor and the combo button itself:
This is the test code used to produce the dialog:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonEditorTest implements Runnable {
String[] items = {"One", "Two", "Three"};
ComboBoxModel model;
ButtonEditorTest() {
// our model, kept simple for the test
model = new DefaultComboBoxModel(items);
// create the UI on the EDT
SwingUtilities.invokeLater(this);
}
// creates UI on the event dispatch thread
@Override
public void run() {
JComboBox comboBox = new JComboBox(model);
comboBox.setEditable(true);
comboBox.setEditor(new ComboButtonEditor());
JFrame frame = new JFrame("JComboBox with JButton editor test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(comboBox, BorderLayout.NORTH);
frame.setSize(200, 100);
frame.setVisible(true);
}
public static void main(String[] args) throws Exception {
String lookAndFeelClassName = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(lookAndFeelClassName);
new ButtonEditorTest();
}
class ComboButtonEditor implements ComboBoxEditor {
private JButton button = new JButton();
private Object item;
@Override
public void addActionListener(ActionListener arg0) {
// not needed for UI test
}
@Override
public Component getEditorComponent() {
return button;
}
@Override
public Object getItem() {
return item;
}
@Override
public void removeActionListener(ActionListener arg0) {
// not needed for UI test
}
@Override
public void selectAll() {
// not needed for UI test
}
@Override
public void setItem(Object item) {
this.item = item;
button.setText(item.toString());
}
}
}