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

Non*_*one 13 java swing jpanel jtextarea autoresize

我在JPanel中有一个JTextArea.我怎样才能让JTextArea填充整个JPanel并在JPanel调整大小时调整大小并在输入太多文本时滚动?

jle*_*s42 19

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
Run Code Online (Sandbox Code Playgroud)

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


Zoe*_*Zoe 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);
Run Code Online (Sandbox Code Playgroud)

这只是一个粗略的草图,但它应该说明如何做到这一点.

  • 通过对Swing中每个其他布局管理器的漫长而彻底的烦恼,我现在几乎只使用GridBagLayout.这是我个人历史的一件神器,而不是一个推荐.请使用适合您需要的布局管理器.在这种情况下,我认为权重的确切规范明确地表明滚动窗格吸收了所有大小的变化.但是,它实际上不值得使用复杂的布局管理器来实现简单的布局. (4认同)
  • 永远不要使用GridBagLayout!决不! (3认同)
  • GridBagLayout 没有任何问题。它灵活且易于使用,至少在我的经验中是如此。如果您在布局组件时遇到性能问题,那么当然要查看其他布局管理器。 (2认同)