在BoxLayout中将JLabel与JScrollPane对齐

时间:2013-02-19 17:38:55

标签: java swing alignment jscrollpane boxlayout

我正在尝试将JLabel和JScrollPane(包含JTextArea)对齐到JPanel的左侧。当我将JTextArea直接放在面板中时,对齐是正确的。如果JTextArea位于滚动窗格中,则对齐方式不正确。

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);
    }
}

下面的第一张图片是滚动窗格,第二张图片没有它。如何正确对齐滚动窗格?

Unaligned dialog Aligned dialog

2 个答案:

答案 0 :(得分:2)

尝试使用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);
    }
}

答案 1 :(得分:1)

替换:

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

人:

JPanel labelPan = new JPanel(new FlowLayout(FlowLayout.LEFT);
labelPan.add(new JLabel("My Label"));
panel.add(labelPan);