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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<Ville> villes = new Vector<Ville>();
villes.add(new Ville("Paris", "FR"));
villes.add(new Ville("Lyon", "FR"));
villes.add(new Ville("Marseille", "FR"));
villes.add(new Ville("Madrid", "ES"));
villes.add(new Ville("Barcelone", "ES"));
villes.add(new Ville("Valencia", "ES"));
final JComboBox combo = new JComboBox(villes);
combo.setRenderer(new Ville());
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(((Ville)combo.getSelectedItem()).getNom());
}
});
frame.add(combo);
frame.pack();
frame.setVisible(true);
}
}
class Ville implements ListCellRenderer {
private String nom;
private String pays;
public Ville(){};
public Ville(String nom, String pays) {
this.nom = nom;
this.pays = pays;
}
public String getNom(){
return nom;
}
public String getPays(){
return pays;
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JPanel pan = new JPanel(new BorderLayout());
Ville ville = (Ville)value;
JLabel nom = new JLabel(ville.getNom());
JLabel pays = new JLabel(ville.getPays());
nom.setOpaque(true);
if(ville.getPays().equals("FR"))nom.setBackground(Color.BLUE);
else if(ville.getPays().equals("ES"))nom.setBackground(Color.RED);
pan.add(nom, BorderLayout.CENTER);
pan.add(pays, BorderLayout.EAST);
return pan;
}
} |
Partager