Wow! Can you show me more?

Prev      Next

Answer: Sure

This applet allows you to replace widgets on the fly - they do not have to be new ones, either.

   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.applet.*;

   public class E extends Applet implements ActionListener {
      JPanel p;
      JButton a[] = { new JButton("One"), new JButton("Two"),
                      new JButton("Three"), new JButton("Four") };
      JTextField b[] = { new JTextField("One"), new JTextField("Two"),
                         new JTextField("Three"), new JTextField("Four") };
      JComboBox c[] = { new JComboBox(), new JComboBox(),
                        new JComboBox(), new JComboBox() };
      JComboBox widget, wid_type;
      JButton doit;
      JTextField text;
 
      public void init () {
         c[0].addItem("One");
         c[1].addItem("Two");
         c[2].addItem("Three");
         c[3].addItem("Four");

         setLayout(new BorderLayout());
         // This is the panel we will meddle with
         p = new JPanel();
         p.setLayout(new GridLayout(1,4));
         for (int i=0 ; i < 4 ; i++) p.add(a[i]);
         add("North", p);

         // This is the control panel
         JPanel q = new JPanel();
         q.setLayout(new GridLayout(1,5));
         q.add(new JLabel("Pick a button: ",JLabel.RIGHT));
         q.add(widget = new JComboBox());
         widget.addItem("One");
         widget.addItem("Two");
         widget.addItem("Three");
         widget.addItem("Four");
         q.add(new JLabel("Widget Type: ", JLabel.RIGHT));
         q.add(wid_type = new JComboBox());
         wid_type.addItem("Button");
         wid_type.addItem("TextField");
         wid_type.addItem("ComboBox");
         q.add(doit = new JButton("Doit"));
         doit.addActionListener(this);
         add("South", q);
      } 

      public void actionPerformed (ActionEvent evt) {
         int i = widget.getSelectedIndex();
         p.remove(i);
         int widget_type = wid_type.getSelectedIndex();
         switch (widget_type) {
         case 0:  p.add(a[i],i);  break;
         case 1:  p.add(b[i],i);  break;
         case 2:  p.add(c[i],i);  break;
         }
         validate();
      }
   }