Question

I'm trying to align a JLabel and a JScrollPane (containing a JTextArea) to the left of a JPanel. When I put the JTextArea directly in the panel, the alignment is correct. The alignment is only incorrect if the JTextArea is in the scroll pane.

import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Main {

    public static void main(String[] args) {
        JDialog dialog = new JDialog();
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        panel.add(new JLabel("My Label"));
        // panel.add(new JTextArea(3, 15));
        panel.add(new JScrollPane(new JTextArea(3, 15)));
        dialog.add(panel);
        dialog.pack();
        dialog.setVisible(true);
    }
}

The first image below is with the scroll pane and the second image is without it. How can I align the scroll pane correctly?

Unaligned dialog Aligned dialog

Was it helpful?

Solution

Try to use alignmentX:

import java.awt.Component;

import javax.swing.*;

public class Main {

    public static void main(String[] args) {
        JDialog dialog = new JDialog();
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        JLabel label = new JLabel("My Label");
        label.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.add(label);

        JScrollPane pane = new JScrollPane(new JTextArea(3, 15));
        pane.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.add(pane);

        dialog.add(panel);
        dialog.pack();
        dialog.setVisible(true);
    }
}

OTHER TIPS

Replace:

panel.add(new JLabel("My Label"));

By:

JPanel labelPan = new JPanel(new FlowLayout(FlowLayout.LEFT);
labelPan.add(new JLabel("My Label"));
panel.add(labelPan);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top