Can a reference to a Button be obtained from a Panel?

Prev      Next

Answer: Yes

I originally thought this could not be done but in reinvestigating the question of adding buttons on the fly I realized that this type of control comes from the Container class. I recommend looking at the methods of that class for many more interesting things that can be done to components on the fly. The following code shows how to find and delete buttons on the fly from a JPanel.

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

   public class D extends Applet implements ActionListener {
      JPanel p;
      JButton a[] = { new JButton("One"), new JButton("Two"),
                      new JButton("Three"), new JButton("Four") };
      JTextField text;
 
      public void init () {
         p = new JPanel();
         p.setLayout(new GridLayout(1,4));
         for (int i=0 ; i < 4 ; i++) {
            p.add(a[i]);
            a[i].addActionListener(this);
         }
         add(p);
         JPanel q = new JPanel();
         q.setLayout(new GridLayout(1,2));
         q.add(new JLabel("Removing: ",JLabel.RIGHT));
         q.add(text = new JTextField(""));
         add(q);
      }

      public void actionPerformed (ActionEvent evt) {
         JButton button = (JButton)evt.getSource();
         text.setText(button.getText());		
         p.remove(button);
         validate();
         /*** Alternatively, and more revealing, use this:			
         Component comp[] = p.getComponents();
         int ncomp = p.getComponentCount();
         for (int i=0 ; i < ncomp ; i++) {
            if (evt.getSource() == comp[i]) {
               text.setText(((JButton)comp[i]).getText());
               p.remove(i);
               validate();
            }
         }
         ***/
      }
   }