javaswinglayout-managerboxlayout

Nested BoxLayout with different axes


I'm having problems with creating nested panels with BoxLayout. I have a container with the layout set to BoxLayout (PAGE_AXIS), and in this container I want to generate panels (postedPanel) also with BoxLayout (PAGE_AXIS). And inside this panel, I have two panels with PAGE_AXIS and one with LINE_AXIS.

That panel with LINE_AXIS (postActions panel) seems to mess up the width and alignment of the panels with PAGE_AXIS. When I set the axis of postActions to PAGE_AXIS, the other panels are stretched to the full width of the container, but when it's LINE_AXIS, the other panels are compressed to half the width of the container. Any ideas how this can be fixed?

Here's the code:

public void generateFeed(JPanel container) {
    JPanel postedPanel = new JPanel();
    postedPanel.setBackground(Color.WHITE);
    postedPanel.setLayout(new BoxLayout(postedPanel, BoxLayout.PAGE_AXIS));

    // sample post

    JPanel postContent = new JPanel();
    postContent.setLayout(new BoxLayout(postContent, BoxLayout.PAGE_AXIS));
    postContent.setBackground(Color.WHITE);
    JLabel usernameLabel = new JLabel("Name");
    postContent.add(usernameLabel);

    JLabel dateLabel = new JLabel("Date posted");
    postContent.add(dateLabel);

    JLabel status = new JLabel("<html>Content Content Content ContentContent</html>");
    postContent.add(status);

    postedPanel.add(postContent);

    // like, comment panel

    JPanel postActions = new JPanel();
    postActions.setLayout(new BoxLayout(postActions, BoxLayout.LINE_AXIS));
    postActions.setBackground(Color.WHITE);

    JButton likeButton = new JButton("Like");
    postActions.add(likeButton);


    JLabel likesLabel = new JLabel("0 Likes");
    postActions.add(likesLabel);

    JButton commentButton = new JButton("Comment");
    postActions.add(commentButton);


    JLabel commentsLabel = new JLabel("0 Comments");
    postActions.add(commentsLabel);

    postedPanel.add(postActions);

    // sample comment

    JPanel addCommentPanel = new JPanel();
    addCommentPanel.setLayout(new BoxLayout(addCommentPanel, BoxLayout.PAGE_AXIS));
    addCommentPanel.setBackground(new Color(246,247,248));

    JLabel commentUser = new JLabel("Name");
    addCommentPanel.add(commentUser);

    JLabel commentText = new JLabel("<html>Comment Comment Comment Comment Comment Comment </html>");
    addCommentPanel.add(commentText);

    JLabel commentDateLabel = new JLabel("Date");
    addCommentPanel.add(commentDateLabel);

    postedPanel.add(addCommentPanel);


    container.add(postedPanel);

    pack();
}

And an image showing the result: http://pelennor.com/img/sample.png


Solution

  • Read the section from the Swing tutorial on Fixing Alignment Problems.

    I believe you need to make sure that all you components use the same setAlignmentX(...) values. I think by default a panel will use 0.5f and other components will use 0.0f.