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

自动调整大小和滚动的Java JTextArea,java,swing,jpanel,autoresize,jtextarea,Java,Swing,Jpanel,Autoresize,Jtextarea,我在JPanel中有一个JTextArea。如何让JTextArea填充整个JPanel,并在JPanel调整大小时调整大小,以及在输入太多文本时滚动 JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); //give your JPanel a BorderLayout JTextArea text = new JTextArea(); JScrollPane scroll = new JScrollPane(

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

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

有关JScrollPane的更多详细信息,请参见或将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可以满足如此简单的需求。永远不要使用GridBagLayout!从未!经过与Swing中其他所有布局管理器的长期和彻底的麻烦,我现在几乎只使用GridBagLayout。那是我个人历史的产物,而不是建议。请务必使用符合您需要的布局管理器。在这种情况下,我认为权重的确切规格明确显示滚动窗格吸收了所有大小的变化。但是,对于一个简单的布局,使用复杂的布局管理器显然是不值得的。GridBagLayout并没有什么问题。至少以我的经验来看,它灵活且易于使用。如果在布局组件时遇到性能问题,那么一定要查看其他布局管理器。