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 59 60 61 62
| public class DemoListCellRenderer {
public static void main(String[] args) {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyObjectWithId[] data = {
new MyObject(1, "Marie", "Directeur de projet"),
new MyObject(2, "Paul", "Chef de projet"),
new MyObject(3, "Caroline", "Développeur"),
new MyObject(4, "Marc", "Développeur"),
};
JComboBox<MyObjectWithId> combo = new JComboBox<>(data);
combo.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
if ( value instanceof MyObjectWithId) {
MyObjectWithId object = (MyObjectWithId) value;
setText(object.name+" ("+object.type+")");
}
return this;
}
});
combo.addActionListener(e-> afficheSelection(combo.getSelectedItem()));
frame.add(combo, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void afficheSelection(Object selectedItem) {
if ( selectedItem instanceof MyObjectWithId ) {
System.out.println("Object sélectionné : " + ((MyObjectWithId)selectedItem).id + "-" + ((MyObjectWithId)selectedItem).name);
}
}
public static class MyObjectWithId {
public final long id;
public final String name;
public final String type;
public MyObjectWithId(long id, String name, String type) {
this.id=id;
this.name=name;
this.type=type;
}
}
} |
Partager