20-CS-694 Advanced Programming Techniques Spring 2012
Widgets

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

     Previous      Next      Applet Source      All lectures

JComboBox Test

Choose a planet - your planet is written into the JTextField.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;

public class ComboApplet extends Applet implements ItemListener {
   JComboBox cb;
   JTextField text;
   
   public void init () {
      setLayout(new GridLayout(2,1,10,10));
      Panel p1 = new Panel();
      p1.setLayout(new BorderLayout());
      p1.add("North", new JLabel("Selected Planet"));
      p1.add("Center", text = new JTextField(20));
      text.setEditable(false);
      add(p1);

      p1 = new Panel();
      p1.setLayout(new BorderLayout());
      p1.add("North", new JLabel("Choose a Planet"));
      cb = new JComboBox();
      cb.addItemListener(this);
      cb.addItem("Mercury");      
      cb.addItem("Venus");      
      cb.addItem("Earth");      
      cb.addItem("Mars");            
      cb.addItem("Jupiter");
      cb.addItem("Saturn");      
      cb.addItem("Uranus");            
      cb.addItem("Neptune");                  
      cb.addItem("Pluto");                        
      p1.add("Center", cb);
      add(p1);
   }

   // Allows "Close" to actually close the window frame
   public void itemStateChanged (ItemEvent evt) {
      if (evt.getSource() == cb) text.setText((String)cb.getSelectedItem());
   }
}