1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| public final class Main {
private static class Foo {
final String value1;
final String value2;
public Foo(final String value1, final String value2) {
this.value1 = value1;
this.value2 = value2;
}
}
public static void main(final String... args) {
SwingUtilities.invokeLater(Main::start);
}
private static void start() {
final var values = new Foo[]{
new Foo("foo", "fii"),
new Foo("fuu", "faa"),
new Foo("fyy", "fee"),
new Foo("aaa", "bbb"),
new Foo("ccc", "ddd"),
new Foo("eee", "fff"),
new Foo("ggg", "hhh"),
new Foo("iii", "jjj"),
new Foo("kkk", "lll"),
new Foo("mmm", "nnn"),
new Foo("ooo", "ppp"),
new Foo("qqq", "rrr"),
new Foo("sss", "ttt"),
new Foo("uuu", "vvv"),
new Foo("www", "xxx"),
new Foo("yyy", "zzz"),
};
final var comboBox = new JComboBox<Foo>(values);
comboBox.setMaximumRowCount(5);
comboBox.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(final JList<?> list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
final var foo = (Foo)value;
String text = null;
if (foo != null) {
text = String.format("%s - %s", foo.value1, foo.value2);
}
setText(text);
return this;
}
});
final var frame = new JFrame("Test");
frame.setSize(500, 500);
frame.setLayout(new FlowLayout());
frame.getContentPane().add(comboBox);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
} |