Declare | JComboBox people; |
Set the options to go in the combobox | String [] peopleStrings = {"Pascal", "Fermat", "Euler", "Turing", "Mandlebrot", "Wiles"}; |
Construct the combobox, pass it the array of options you made earlier. | JComboBox people = new JComboBox (peopleStrings); |
Pick which option you want to be the default | people.setSelectedIndex (3); |
Set the action listener and add to the applet | people.setActionCommand ("people"); people.addActionListener (this); add (people); |
In ActionPerformer: use e.getSource to find the source, use getSelectedItem() to figure out what the user choose |
if (e.getActionCommand ().equals ("people")) { //To draw the name that is in the peoples combo box JComboBox cb = (JComboBox) e.getSource (); people_s = (String) cb.getSelectedItem (); showStatus(people_s); } |
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.applet.Applet;
public class combobox extends Applet implements ActionListener { //Declare the widgets JComboBox people; String people_s;
public void init () { //Create the options for the box people_s = "Turing"; //the default option //the other options String [] peopleStrings = {"Pascal", "Fermat", "Euler", "Turing", "Mandlebrot", "Wiles"}; //Create the combo box for people JComboBox people = new JComboBox (peopleStrings); people.setSelectedIndex (3); people.setActionCommand ("people"); people.addActionListener (this); add (people); }
public void actionPerformed (ActionEvent e) { if (e.getActionCommand ().equals ("people")) { //To draw the name that is in the peoples combo box JComboBox cb = (JComboBox) e.getSource (); people_s = (String) cb.getSelectedItem (); showStatus(people_s); } } }