how-to

Window (swing) applications

How to dynamically add new component to window

When you want to add new component - for example javax.swing.JButton onto window, is important what type is used layout.

When you have on the window (panel..) for example java.awt.GridLayout, you can use for component adding this construction:

/* -- create new layout (or - you just have it)*/

this.setLayout( new GridLayout( 3, 3 ) );

/* -- create and add button */

JButton button = new JButton( "Added" );
this.add( button );

/* --project changes into window */

this.pack();

Free Layout

For free layout is the situation difficult. You must set location and size of the component + repaint owner.

/* -- create button */

JButton button = new JButton( "Added" );

/* -- set position and button size */

button.setLocation( 100, 100 );  
button.setSize( 100, 25 );

this.add( button );
    
/* --project changes into window */

this.revalidate();
this.repaint();