Java Interface Programming (8) ------ combo box (drop-down list)
This article is my learning notes, welcome to reprint, but please note the Source: http://blog.csdn.net/jesson20121020
Similar to the function of a group of single-choice buttons, a combo (drop-down list) forces users to select only one possible element from a group. However, this method is more compact, in addition, it is easier to change the content in the drop-down list without confusing users.
In the following example, the JComboBox combo box already has some elements at the beginning. When a button is pressed, a new element is added to the combo box.
Public class ComboBoxes extends JFrame {private String [] weekDays = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat ", "Sun"}; private JTextField t = new JTextField (15); private JComboBox c = new JComboBox (); private JButton B = new JButton ("Add items "); private int count = 0; public ComboBoxes () {// TODO Auto-generated constructor stubsetLayout (new FlowLayout (); setSize (200,175); setVisible (true ); for (int I = 0; I <3; I ++) c. addItem (weekDays [count ++]); t. setEditable (false); B. addActionListener (new ActionListener () {@ Overridepublic void actionreceivmed (ActionEvent e) {// TODO Auto-generated method stubif (count <weekDays. length) {c. addItem (weekDays [count ++]) ;}}); c. addActionListener (new ActionListener () {@ Overridepublic void actionreceivmed (ActionEvent e) {// TODO Auto-generated method stubt. setText ("you have selected" + c. getSelectedItem () ;}}); c. setEditable (true); add (t); add (c); add (B);}/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stubnew ComboBoxes ();}}
The effect is as follows:
When you click the option in the combo box, the selected result is displayed in JTextField.