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
| import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ComboBoxDemo extends JPanel implements ActionListener {
static JFrame frame;
JTextField result;
public ComboBoxDemo() {
String[] comboValues = { "a", "b", "c", "d" };
JComboBox combo = new JComboBox(comboValues);
combo.addActionListener(this);
result = new JTextField("=>",50);
add(combo);
add(result);
} // constructor
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String newSelection = (String) cb.getSelectedItem();
result.setText(result.getText() + " " + newSelection);
}
public static void main(String[] args) {
JFrame frame = new JFrame("COMBO");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new ComboBoxDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
} |