Solved

Dynamically adding a panel to a Swing GUI

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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Programmer's Notepad is, one of the best free text editing tools available, simply because the developers appear to have second-guessed every weird problem or issue a programmer is likely to run into. One of these problems is selecting and deleti…
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: …
This video teaches viewers about errors in exception handling.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

707 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now