user274363
user274363

Reputation: 1

How to add new component to the panel at run time

I want to add JCombobox to the panel at run time, I don't have idea about this, so please if you have any idea about this suggest me.

Upvotes: 0

Views: 1628

Answers (1)

Klarth
Klarth

Reputation: 2045

I assume you want to add a combo box to a component that is already on screen. Just add the component to the appropriate Container and call the Container's validate method. Here is a little example for this:

import java.awt.Dimension;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Application {

    private static final String[] choices = { "One", "Two", "Three" };

    /**
     * @param args
     */
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        final JPanel content = new JPanel();
        content.setPreferredSize(new Dimension(50, 200));
        content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
        JButton addButton = new JButton(new AbstractAction("Add Combobox") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent arg0) {
                content.add(new JComboBox(choices));
                content.validate();
            }
        });

        frame.add(content);
        content.add(addButton);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Although I have used a frame only for this example, it should also work for a JPanel.

Upvotes: 1

Related Questions