【问题标题】:Java JTextArea that auto-resizes and scrolls自动调整大小和滚动的 Java JTextArea
【发布时间】:2011-04-20 02:23:42
【问题描述】:

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

【问题讨论】:

    标签: java swing jpanel autoresize jtextarea


    【解决方案1】:
    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 的更多详细信息,请参阅 http://download.oracle.com/javase/6/docs/api/javax/swing/JScrollPane.htmlhttp://download.oracle.com/javase/tutorial/uiswing/components/scrollpane.html

    【讨论】:

      【解决方案2】:

      将 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 没有问题。至少在我的经验中,它灵活且易于使用。如果您在布局组件时遇到性能问题,请务必查看其他布局管理器。
      猜你喜欢
      • 2013-12-16
      • 2011-02-05
      • 2016-01-14
      • 2012-08-14
      • 2013-03-08
      • 2012-07-18
      • 2022-10-13
      • 1970-01-01
      • 2011-08-31
      相关资源
      最近更新 更多