gpt4 book ai didi

java - JScrollPane 中的动态 JTextArea 最终位于滚动条下方

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

我有一个带有 JScrollPane 的 JFrame,其中包含 JTextArea。滚动 Pane 配置为从不显示水平滚动条,并根据需要显示垂直滚动条。随着文本区域中的文本增长,垂直滚动条最终会出现,隐藏部分文本区域。我希望滚动条出现时根据需要调整其内容的大小。

我发现的一个解决方法是始终显示垂直滚动条,但这看起来不太好,因为很少需要它。

在我的系统(Windows 10)上输入足够的文本后,下面的代码片段重现了该问题

import javax.swing.*;
import java.awt.*;
import static javax.swing.ScrollPaneConstants.*;

public class Test {
public static void main(String[] args) {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new JLabel("text"));
panel.add(new JLabel("text"));
panel.add(new JLabel("text"));

JTextArea textArea = new JTextArea();
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setText("This text fits");
panel.add(textArea);

JScrollPane scrollPane =
new JScrollPane(panel, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER);

JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollPane);

frame.pack();
frame.setVisible(true);
}
}

最佳答案

要解决该问题,请更改:

JTextArea textArea = new JTextArea();

致:

JTextArea textArea = new JTextArea(1,20);

通过向文本区域提供大小提示,滚动 Pane 能够在添加更多文本时更好地处理它。

关于java - JScrollPane 中的动态 JTextArea 最终位于滚动条下方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45730502/

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