2

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.