954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

JPanel BoxLayout nested JPanel alignment issue

I am having a problem with left alignment after adding a second JPanel. Both JPanels are using the BoxLayout with the first set to Y_AXIS and the second set to X_AXIS. If you comment out the add(twoPanel) it results in the desired left alignment. I don't understand why the alignment changes after adding the second JPanel. Thanks in advance.

import javax.swing.*;

public class BoxManager extends JApplet{
	JButton one, two, three;
	
	public void init() {
		one = new JButton("one");
		two = new JButton("two");
		three = new JButton("three");
		
		setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
		add(new JLabel("This is the contentPane."));
		JPanel twoPanel = new JPanel();
		twoPanel.setLayout(new BoxLayout(twoPanel, BoxLayout.X_AXIS));
		twoPanel.add(new JLabel("Second Panel"));
		twoPanel.add(new JTextField("Text Field"));
		add(twoPanel); // comment this line out
		
		add(one);
		add(two);
		add(three);
	}
}
RagingRiver
Newbie Poster
2 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

Try

twoPanel.setLayout(new BoxLayout(twoPanel, BoxLayout.PAGE_AXIS));

edit: Hmm, scratch that, it doesn't preserve the horizontal ordering that you wanted for the second panel.

Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

I solved it out by adding the following before adding the twoPanel.

twoPanel.setAlignmentX(LEFT_ALIGNMENT);

RagingRiver
Newbie Poster
2 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

Edit: oops cross-posted, I guess you found the same thing :)
Try this

public void init() {
		one = new JButton("one");
		two = new JButton("two");
		three = new JButton("three");

		setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
		add(new JLabel("This is the contentPane."));
		JPanel twoPanel = new JPanel();
                twoPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
		twoPanel.setLayout(new BoxLayout(twoPanel, BoxLayout.LINE_AXIS));
		twoPanel.add(new JLabel("Second Panel"));
		twoPanel.add(new JTextField("Text Field"));
		add(twoPanel); // comment this line out

                one.setAlignmentX(Component.LEFT_ALIGNMENT);
                two.setAlignmentX(Component.LEFT_ALIGNMENT);
                three.setAlignmentX(Component.LEFT_ALIGNMENT);
		add(one);
		add(two);
		add(three);
	}
Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: