Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Using a button to add Swing component into JPanel at runtime doesn't work

843807May 5 2009 — edited May 6 2009
I am facing a weird issue while running my applet, I have a JPanel added into this applet with GridLayout and the JPanel is enclosed by a JScrollPane,

I've added some JButtons into this grid layout using jPanel.add(Component) method, all well, but adding the components works only inside the init() method, when I use the add method into my JButton actionListener handler (actionPerformed method) it doesn't show anything into this panel !!! although I can check the button is added using the method getComponentCount(), it returns the counter incremented.

In other words I have two buttons, one adds a component into that JPanel and other deletes it, when I press the add button, the component (button) don't appear into the JPanel, although if I execute the same code into the init()method it works well and I can see as many buttons as I want appearing into the grid...

Does this has anything to do with the applet life cycle? or is there any certain method call from the Component object? whats I am doing wrong?

appreciated your help
    public void init() {
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {

                public void run() {
                    initComponents();
                    setSize(600, 500);
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }

// this code works well, but if i moved it to the button even handler it deosn't !!
        JButton test1 = new JButton("test");
        JButton test2 = new JButton("test");
        this.jPanel1.add( test1 );
        this.jPanel1.add( test2 );
}
Thanks a lot

Regards
Mohammed Saleem
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 3 2009
Added on May 5 2009
2 comments
933 views