Solved

Dynamically adding a panel to a Swing GUI

Posted on 2002-03-13
2
294 Views
Last Modified: 2013-11-23
Hi,

When I press a JButton I want to add a panel panel to my UI.  How would I implement this?

Thanks,

Matt
0
Comment
Question by:MatthewL
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 16

Accepted Solution

by:
Peter Kwan earned 200 total points
ID: 6861508
Here is an example:

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

public class TestFrame extends JFrame {
   public TestFrame() {
      addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          System.exit(1);
        }
      });

      JButton b = new JButton("Click me");
      b.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
           JPanel p = new JPanel();
           p.add(new JTextField(15));

           JButton button = (JButton)ae.getSource();
           Container c = button.getParent();
           c.add(p);
           pack();
        }
      });

      getContentPane().setLayout(new FlowLayout());
      getContentPane().add(b);
      pack();
      show();
   }

   public static void main(String[] args) {
       new TestFrame();      
   }
}
0
 
LVL 1

Author Comment

by:MatthewL
ID: 6862793
Hi pkwan.

Perfect!

Thanks,

Matt
0

Featured Post

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question