Skip to content

Instantly share code, notes, and snippets.

@klmr
Created October 11, 2011 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klmr/1279388 to your computer and use it in GitHub Desktop.
Save klmr/1279388 to your computer and use it in GitHub Desktop.
JComboBox with custom label
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.ListDataListener;
import javax.swing.plaf.basic.BasicComboBoxEditor;
public class Example extends JPanel {
static class ActiveComboItem {
private final Object item;
public ActiveComboItem(Object item) { this.item = item; }
@Override
public boolean equals(Object other) {
return item == null ? other == null : item.equals(other);
}
@Override
public String toString() { return String.format("Animal: %s", item); }
}
public Example() {
super(new BorderLayout());
final String[] animals = { "Cow", "Dolphin", "Pig", "Rat" };
JComboBox animalCombo = new JComboBox(animals);
animalCombo.setModel(new DefaultComboBoxModel(animals) {
private Object selected;
public void setSelectedItem(Object anItem) {
selected = anItem;
}
public Object getSelectedItem() {
return new ActiveComboItem(selected);
}
});
add(animalCombo, BorderLayout.PAGE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new Example();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() { createAndShowGUI(); }
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment