Dat*_*aki 5 java swing jscrollpane jtextarea miglayout
我和这个家伙有同样的困难:
与linewrap = true一起使用时,MigLayout JTextArea不会缩小
我使用了其中一个答案中描述的解决方案; 明确设置最小大小.如果将包含JTextArea的JPanel直接放在JFrame中,然后调整窗口大小,这可以正常工作.
但是,将包含JTextArea的面板放在JScrollPane中时,会再次出现同样的问题.这是为什么,以及如何解决这个问题?
干杯
编辑:一个例子
public class MiGTest2 extends JFrame{
public MiGTest2(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new MigLayout("fillx, debug", "[fill]"));
JTextArea textArea = new JTextArea();
textArea.setLineWrap(true);
panel.add(textArea, "wmin 10");
//panel.add(new JTextField());
JScrollPane scrollPane = new JScrollPane(panel);
//add(panel);
add(scrollPane);
pack();
}
public static void main(String[] args){
new MiGTest2().setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
如果取消注释//add(panel);,并注释add(scrollPane);,缩小窗口大小也会缩小JTextArea.也就是说,它不适用于JScrollPane.还要注意布局管理器在首次放大后缩小窗口大小时如何翻转并开始"摇动"其所有内容
当与JScrollPanes一起使用时,我遇到了与JTextAreas和包装类似的问题.
对我有用的解决方案是创建一个实现Scrollable接口的自定义面板,并覆盖getScrollableTracksViewportWidth()方法以返回true.此强制导致滚动窗格仅垂直滚动,并允许JTextArea中的换行按预期工作.
/**
* A panel that, when placed in a {@link JScrollPane}, only scrolls vertically and resizes horizontally as needed.
*/
public class OnlyVerticalScrollPanel extends JPanel implements Scrollable
{
public OnlyVerticalScrollPanel()
{
this(new GridLayout(0, 1));
}
public OnlyVerticalScrollPanel(LayoutManager lm)
{
super(lm);
}
public OnlyVerticalScrollPanel(Component comp)
{
this();
add(comp);
}
@Override
public Dimension getPreferredScrollableViewportSize()
{
return(getPreferredSize());
}
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation, int direction)
{
return(10);
}
@Override
public int getScrollableBlockIncrement(Rectangle visibleRect,
int orientation, int direction)
{
return(100);
}
@Override
public boolean getScrollableTracksViewportWidth()
{
return(true);
}
@Override
public boolean getScrollableTracksViewportHeight()
{
return(false);
}
}
Run Code Online (Sandbox Code Playgroud)
和MigTest2成为:
public class MiGTest2 extends JFrame
{
public MiGTest2()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new MigLayout("fillx, debug", "[fill]"));
JTextArea textArea = new JTextArea();
textArea.setLineWrap(true);
panel.add(textArea, "wmin 10");
//panel.add(new JTextField());
//Wrap panel with the OnlyVerticalScrollPane to prevent horizontal scrolling
JScrollPane scrollPane = new JScrollPane(new OnlyVerticalScrollPanel(panel));
//add(panel);
add(scrollPane);
pack();
}
public static void main(String[] args)
{
new MiGTest2().setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3919 次 |
| 最近记录: |