我一直在尝试制作一个JTextArea,可以像在Word文档中那样编写。当文字太宽时会回绕,当文字太高时会向下滚动)。
到目前为止,当包包太宽时效果很好。但是,滚动条不起作用。它的确显示了,但是再也无法显示了,这意味着无论如何都无法查看JTextArea原始尺寸之外的任何内容。
有人知道我在做什么错吗?代码是这样的:这是我稍后使用的以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();
}
}