slex slex - 1 year ago 125
Java Question

java - How would I dynamically add swing component to gui on click?

What I am looking to do is a similar principle to adding attachments to emails, you can click a button and a new browse box would open increasing the number of separate attachments you can have.

I'm fairly new so if someone could point me towards an example?

Answer Source

Sample code to add Buttons on the fly dynamically.

panel.add(new JButton("Button"));

Full code:

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.awt.FlowLayout;
import java.awt.BorderLayout;

public class AddComponentOnJFrameAtRuntime extends JFrame implements ActionListener {

    JPanel panel;

    public AddComponentOnJFrameAtRuntime() {
        super("Add component on JFrame at runtime");
        setLayout(new BorderLayout());
        this.panel = new JPanel();
        this.panel.setLayout(new FlowLayout());
        add(panel, BorderLayout.CENTER);
        JButton button = new JButton("CLICK HERE");
        add(button, BorderLayout.SOUTH);
        setSize(500, 500);

    public void actionPerformed(ActionEvent evt) {
        this.panel.add(new JButton("Button"));

    public static void main(String[] args) {
        AddComponentOnJFrameAtRuntime acojfar = new AddComponentOnJFrameAtRuntime();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download