我一直在尝试制作一个 JTextArea,我可以像在 Word 文档中一样编写它;当文本太宽时它会环绕,当文本太高时它会向下滚动)。
到目前为止,当包裹太宽时,包裹效果很好。但是,滚动条不起作用。它确实出现了,但它不会再出现,这意味着无论如何都无法查看 JTextArea 原始尺寸之外的任何内容。
有谁知道我做错了什么?代码如下所示;它是名为 panel 的 JPanel,稍后我将使用它,将其添加到另一个 JPanel,而另一个 JPanel 又添加到 JFrame。
JTextArea text = new JTextArea(rows, columns);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setPreferredSize(new Dimension(text.getWidth(), text.getHeight()));
JScrollPane scroll = new JScrollPane(text);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(scroll);
最佳答案
工作正常,当我删除 - text.setPreferredSize
import java.awt.Dimension;
import java.awt.HeadlessException;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
public class ScrollTest extends JFrame {
public ScrollTest() throws HeadlessException {
JTextArea text = new JTextArea(5, 20);
text.setLineWrap(true);
text.setWrapStyleWord(true);
// text.setPreferredSize(new Dimension(text.getWidth(), text.getHeight()));
JScrollPane scroll = new JScrollPane(text);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(scroll);
this.add(panel);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ScrollTest();
}
}
关于java - JTextArea 与 JPanel 内的 JScrollPane 不能很好地配合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48746977/