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
|
import java.awt.event.*;
import javax.swing.*;
public class MultipleComboBoxes {
private static final String[] DATA_A = {"plat 1", "plat 2", "plat 3", "plat 4"};
private static final String[] DATA_B = {"Cola", "Fanta", "Spirit", "Orange"};
private static final String[] DATA_C = {"Vodka", "Tikila", "XXX", "YYYY"};
private JPanel mainPanel = new JPanel();
// combo boxes declared as class level variables
private JComboBox comboA = new JComboBox(DATA_A);
private JComboBox comboB = new JComboBox(DATA_B);
private JComboBox comboC = new JComboBox(DATA_C);
public MultipleComboBoxes() {
JButton getSelectionBtn = new JButton("Get Selection");
getSelectionBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// in the button's action listener, use the references to both
// combo boxes to get the selected items
Object itemA = comboA.getSelectedItem();
Object itemB = comboB.getSelectedItem();
Object itemC = comboC.getSelectedItem();
String optionString = "comboA: " + itemA.toString() + "\n" +
"comboB: " + itemB.toString() + "\n" +
"comboC: " + itemC.toString();
JOptionPane.showMessageDialog(mainPanel, optionString);
}
});
mainPanel.add(comboA);
mainPanel.add(comboB);
mainPanel.add(comboC);
mainPanel.add(getSelectionBtn);
}
public JComponent getComponent() {
return mainPanel;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("MultipleComboBoxes");
frame.getContentPane().add(new MultipleComboBoxes().getComponent());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
} |
Partager