Can you add buttons to a panel on the fly?

Prev      Next

Answer: Yes

The following is an example (originally I thought this did not work but Shriram Narayanaswamy pointed out that the applet needs be to resized to see the effect - he also suggested adding a resize line to do this automatically - instead I added validate() - I also show how to remove all the components of the JPanel - for more information see the API on the course webpage, look for methods of the Container class).

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

   public class C extends Applet implements ActionListener {
      int i=0;
      JPanel p;
      JButton a[] = { new JButton("One"), new JButton("Two"),
		      new JButton("Three"), new JButton("Four") };
 
      public void init () {
         p = new JPanel();
         p.setLayout(new GridLayout(1,4));
         p.add(a[i++]);
         add("Center",p);
         for (int i=0 ; i < 4 ; i++) a[i].addActionListener(this);
      }

      public void actionPerformed (ActionEvent evt) {
         if (i == 4) {
            i=0;
            p.removeAll();
         }			
         p.add(a[i++]);
         validate();
      }
   }