Solved

Dynamically adding a panel to a Swing GUI

Posted on 2002-03-13
2
290 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
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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
splitOdd10 challenge 5 105
custom annotations 9 38
maven module vs maven project 3 22
How do I remove an object from a 3 23
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…
Here is a helpful source code for C++ Builder programmers that allows you to manage and manipulate HTML content from C++ code, while also handling HTML events like onclick, onmouseover, ... Some objects defined and used in this source include: …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.

776 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