Saadat
Saadat

Reputation: 47

swing: Aligning JPanels in a BoxLayout

I have a JPanel (panel), the layout of which is set to BoxLayout. I also have a custom class MapRow, which extends JPanel (and has a few components inside it in a simple FlowLayout), and I wish to add the instances of MapRow to panel in a simple, left-aligned, top-down fashion. Consider the following method:

public void drawMappingsPanel(JPanel panel) {
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));

        int s = /* aMethodCall() */;
        for (int i = 0; i < s; i++) {
            MapRow row = new MapRow();
            row.setAlignmentX(LEFT_ALIGNMENT);
            panel.add(row);
        }
    }

However, when I run the code, all MapRow panels are centrally aligned, like below:

enter image description here

How can I align the MapRow panels to the left? The setAlignmentX(LEFT_ALIGNMENT) method doesn't seem to work...

EDIT : I just replaced instances of MapRow with dummy JButtons, and they got left-aligned all fine. So components such as JButtons can be left aligned using setAlignmentX(), but JPanels cannot be?

Upvotes: 1

Views: 5090

Answers (1)

Guillaume Polet
Guillaume Polet

Reputation: 47627

You should use a LEFT-alignement for you FlowLayout in MapRow. Here is a small SSCCE illustrating that:

import java.awt.Color;
import java.awt.FlowLayout;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestJPanels {

    protected void initUI() {
        final JFrame frame = new JFrame(TestJPanels.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        for (int i = 0; i < 5; i++) {
            JLabel label = new JLabel("Label-" + i);
            label.setBorder(BorderFactory.createLineBorder(Color.GREEN));
            JPanel insidePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            insidePanel.add(label);
            insidePanel.setBorder(BorderFactory.createLineBorder(Color.RED));
            panel.add(insidePanel);
        }
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestJPanels().initUI();
            }
        });
    }
}

Upvotes: 1

Related Questions