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
| public class DemoCombo {
private static final String[] ITEMS = {"Abricot","Ananas","Banane","Citron","Fraise","Poire","Pomme"};
public static void main(String[] args) {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JComboBox<?> combo = createComboEditable();
JComboBox<?> combo = createComboNonEditable();
frame.getContentPane().add(combo);
JButton button = new JButton("Afficher sélection");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String saisie = (String) combo.getSelectedItem();
if ( saisie==null || saisie.isEmpty() ) {
JOptionPane.showMessageDialog(frame, "Saisie du fruit obligatoire");
}
else {
// la tu fais ton traitement...
JOptionPane.showMessageDialog(frame, "Vous avez saisi le fruit " + combo.getSelectedItem());
}
}
});
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static JComboBox<?> createComboEditable() {
JComboBox<String> combo = new JComboBox<>(ITEMS);
combo.setEditable(true);
combo.setSelectedItem("");
return combo;
}
private static JComboBox<?> createComboNonEditable() {
List<String> values = new ArrayList<>();
for(String item : ITEMS) {
values.add(item);
}
final JComboBox<String> combo = new JComboBox<>(values.toArray(new String[values.size()]));
combo.setRenderer(new DefaultListCellRenderer(){
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
String data = (String)value;
Component component = super.getListCellRendererComponent(list, data==null?"<Saisir une valeur>":data, index, isSelected, cellHasFocus);
return component;
}
});
combo.setSelectedItem(null);
return combo;
}
} |
Partager