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
| // appeler le fichier Exemple048_Swing_JComboBox.java
// Nicolas_75, 6 septembre 2006
// http://www.developpez.net/forums/showthread.php?t=206292
// tutoriel JComboBox : http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Exemple048_Swing_JComboBox extends JFrame {
public Exemple048_Swing_JComboBox() {
// initialisation de la JFrame
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// initialisation de la 2nde JCombobox,
// nécessaire pour l'ActionListener ci-dessous
final JComboBox box2 = new JComboBox();
// final ci-dessus pour permettre l'accès depuis le listener interne
// première JComboBox
String[] values1 = {"Elem1", "Elem2", "Elem3", "Elem4", "Elem5"} ;
final JComboBox box1 = new JComboBox(values1);
// final ci-dessus pour permettre l'accès depuis le listener interne
box1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String selectedItem = (String) box1.getSelectedItem();
// ajoutons l'item sélectionné à gauche dans le JComboBox de droite
// mais uniquement si ce dernier ne le contient pas déjà
ComboBoxModel model = box2.getModel();
boolean alreadyInBox2 = false;
int i=0;
while ((!alreadyInBox2) && (i<model.getSize())) {
if ((String) model.getElementAt(i) == selectedItem) alreadyInBox2 = true;
i++;
}
if (!alreadyInBox2) box2.addItem(selectedItem);
}
});
box1.setPreferredSize(new Dimension(100,40));
this.add(box1,BorderLayout.WEST);
// inclusion de la JComboBox dans la JFrame
box2.setPreferredSize(new Dimension(100,40));
this.add(box2,BorderLayout.EAST);
// affichage de la JFrame :
this.pack();
}
public static void main(String[] args) {
Exemple048_Swing_JComboBox myFrame = new Exemple048_Swing_JComboBox();
myFrame.setVisible(true);
}
} |
Partager