Rafferty C
Rafferty C

Reputation: 11

Swing GUI with FlowLayout, won't display on JFrame more than last component added

I am trying to display 2 panels that I have created in separate files one at the top and one at the bottom of my GUI with a button group between them. However, the window is only displaying one panel or the button group at a time. The panels and button group are displaying properly but only the last one added to the frame is being displayed at any given execution.

Here is the current code without any layouts...

package UserGUI;

import javax.swing.*;
import java.awt.*;

public class RealFrame extends JFrame {
JButton Close = new JButton("Close");
JButton Proceed = new JButton("Proceed");
AuthorPanel header = new AuthorPanel();
FreeSpacePanel disk = new FreeSpacePanel();

public RealFrame() {
    super();       
    ButtonGroup Ops = new ButtonGroup();
    Ops.add(Close);
    Ops.add(Proceed);
    JPanel OPS = new JPanel();
    OPS.add(Close);
    OPS.add(Proceed);
    add(disk);
    add(OPS);
    add(header);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500,500);
    setVisible(true);
   }
}

Upvotes: 0

Views: 385

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347184

JFrame uses a BorderLayout by default, so when you do...

add(disk);
add(OPS);
add(header);

You're adding each component to the same location (the CENTRE position), but the BorderLayout will only layout the last one added.

Instead, you should use something more like...

add(disk, BorderLayout.NORTH);
add(OPS);
add(header, BorderLayout.SOUTH);

See How to Use Borders for more details

Upvotes: 2

camickr
camickr

Reputation: 324098

add(disk);
add(OPS);
add(header);

The default layout manager of the content pane of the JFrame is a BorderLayout. If you don't specify a constraint then the component is added to the BorderLayout.CENTER. Only one component can be added to the CENTER so the only the last component is displayed.

Try:

add(disk, BorderLayout.NORTH);
add(OPS, BorderLayout.CENTER);
add(header, BorderLayout.SOUTH);

to see the difference.

Or try another layout manager on the frame. See How to Use Layout Manager for more information.

Upvotes: 2

Related Questions