MigLayout JTextArea is not shrinking when used with linewrap=true

萝らか妹 提交于 2019-12-17 19:39:05

问题


If I use a JTextArea with MigLayout like this:

MigLayout thisLayout = new MigLayout("", "[][grow]", "[]20[]");
   this.setLayout(thisLayout);
   {
jLabel1 = new JLabel();
this.add(jLabel1, "cell 0 0");
jLabel1.setText("jLabel1");
  }
  {
 jTextArea1 = new JTextArea();
this.add(jTextArea1, "cell 0 1 2 1,growx");
jTextArea1.setText("jTextArea1");
jTextArea1.setLineWrap(false);
   } 

then the JTextArea grows and shrinks perfectly when resizing the window. When I set the linewrap to true the JTextArea is not shrinking when I make the window smaller again. I would very much appreciate any help. Thanks

Marcel


回答1:


This is because JTextArea's automatically have their minimum width set anytime they resize. Details are available on the MigLayout forum. To roughly summarize, create a panel that contains the JTextArea and gives you further control over the resize behavior. Here's an excerpt from the above forum post:

static class MyPanel extends JPanel implements Scrollable
{
  MyPanel(LayoutManager layout)
  {
     super(layout);
  }

  public Dimension getPreferredScrollableViewportSize()
  {
     return getPreferredSize();
  }

  public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
  {
     return 0;
  }

  public boolean getScrollableTracksViewportHeight()
  {
     return false;
  }

  public boolean getScrollableTracksViewportWidth()
  {
     return true;
  }

  public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
  {
     return 0;
  }
}

Then, wherever you would use the JTextArea, use the panel containing the text area:

MigLayout thisLayout = new MigLayout("", "[][grow]", "[]20[]");
this.setLayout(thisLayout);
{
    jLabel1 = new JLabel();
    this.add(jLabel1, "cell 0 0");
    jLabel1.setText("jLabel1");
}
{
    JPanel textAreaPanel = new MyPanel(new MigLayout("wrap", "[grow,fill]", "[]"));
    jTextArea1 = new JTextArea();
    textAreaPanel.add(jTextArea1);
    this.add(textAreaPanel, "cell 0 1 2 1,grow,wmin 10");
    jTextArea1.setText("jTextArea1");
    jTextArea1.setLineWrap(false);
} 



回答2:


I just discovered that this can simply be resolved by changing the line

this.add(jTextArea1, "cell 0 1 2 1,growx");

to

this.add(jTextArea1, "cell 0 1 2 1,growx, wmin 10");

and no extra panels are needed. Setting an explicit minimum size is what does the trick.

Explanation: see the note under the section on padding in the MiGLayout whitepaper:

http://www.migcalendar.com/miglayout/whitepaper.html



来源:https://stackoverflow.com/questions/2475787/miglayout-jtextarea-is-not-shrinking-when-used-with-linewrap-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!