stillStudent
stillStudent

Reputation: 449

Java Swing layout issue

I added child panel to parent panel by using method 'parent.addTab(child)' and added one JLabel in the child panel but setBounds method is not working in child panel. This JLabel is getting showed at one fix location. setBounds is working fine in parent panel. What to do?

Upvotes: 2

Views: 267

Answers (2)

Nate
Nate

Reputation: 16898

setBounds only work for containers that have their layout set to null. (Or for moving frames around on the desktop.)

JPanel's default layout manager is FlowLayout which lays out components in order horizontally, and dropping to a new row when the current is full (like text in a page).

Using a null layout and setBounds isn't a recommended way to lay out GUIs - it's very fragile - too much depends on the size of the container / frame and the size, resolution and font settings of the desktop can easily break the layout.

Read through the Using Layout Managers section of the Swing tutorial to figure out what layout managers can help you accomplish what you want.

Upvotes: 0

Adamski
Adamski

Reputation: 54705

You need to define an appropriate layout manager for your child panel. For example, if you chose to use BorderLayout you could arrange for the label to be shown in the center of the panel as follows:

JTabbedPane parent = new JTabbedPane();
JPanel child = new JPanel(new BorderLayout());

// Create label with centrally aligned text (default is left).
JLabel label = new JLabel("Hello, World", JLabel.CENTER_ALIGNMENT);

// Add label to center of the child panel.
child.add(label, BorderLayout.CENTER);

// Add child panel as a tab within parent JTabbedPane.
// The child panel will expand to fit the size of the tab.
parent.addTab("My Tab", child);

For more a flexible layout consider using GridBagLayout.

Upvotes: 2

Related Questions