gpt4 book ai didi

java - 在 BoxLayout 中将 JLabel 与 JScrollPane 对齐

转载 作者:行者123 更新时间:2023-12-02 00:00:21 25 4
gpt4 key购买 nike

我正在尝试将 JLabel 和 JScrollPane(包含 JTextArea)与 JPanel 的左侧对齐。当我将 JTextArea 直接放入面板中时,对齐是正确的。仅当 JTextArea 位于滚动 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);
}
}

下面的第一张图片带有滚动 Pane ,第二张图片没有滚动 Pane 。如何正确对齐滚动 Pane ?

Unaligned dialog Aligned dialog

最佳答案

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

关于java - 在 BoxLayout 中将 JLabel 与 JScrollPane 对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14963909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com