Java自动调整大小和滚动的JTextArea

13

我在一个 JPanel 中有一个 JTextArea。如何让 JTextArea 填充整个 JPanel,并在 JPanel 调整大小时调整大小,在输入太多文本时滚动显示?

2个回答

21
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());  //give your JPanel a BorderLayout

JTextArea text = new JTextArea(); 
JScrollPane scroll = new JScrollPane(text); //place the JTextArea in a scroll pane
panel.add(scroll, BorderLayout.CENTER); //add the JScrollPane to the panel
// CENTER will use up all available space

请参阅http://download.oracle.com/javase/6/docs/api/javax/swing/JScrollPane.htmlhttp://download.oracle.com/javase/tutorial/uiswing/components/scrollpane.html,了解有关JScrollPane更多的详细信息。


7

将JTextArea放置在JScrollPane内,并将其放入具有固定大小的JPanel中。例如,使用GridBagLayout的示例可能如下所示:

JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());

JScrollPane scrollpane = new JScrollPane();
GridBagConstraints cons = new GridBagContraints();
cons.weightx = 1.0;
cons.weighty = 1.0;
panel.add(scrollPane, cons);

JTextArea textArea = new JTextArea();
scrollPane.add(textArea);

这只是一个草图,但它应该说明如何做到。

差点没有点赞,因为使用GridBagLayout来实现如此简单的需求。 - Lawrence Dol
3
永远不要使用GridBagLayout!绝对不要! - Denis Tulskiy
5
由于对Swing中的其他布局管理器感到长期而完全的烦恼,我现在几乎专门使用GridBagLayout。这是我的个人经历的产物,而不是推荐。请使用适合您需求的任何布局管理器。在这种情况下,我认为权重的确切规范明确显示滚动面板吸收了所有大小的变化。但是,对于简单的布局来说,确实不值得使用复杂的布局管理器。 - Zoe
2
GridBagLayout没有任何问题。在我的经验中,它是灵活且易于使用的。如果您在布置组件时遇到性能问题,那么可以尝试其他布局管理器。 - Håvard Geithus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接