JTextArea自动换行大小 [英] JTextArea word wrap resizing

查看:181
本文介绍了JTextArea自动换行大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在JPanel(BoxLayout)上具有JTextArea.我也有Box填充器,可以填充JPanel的其余部分.我需要我的JTextArea以单行高度开始(我可以管理它),并在需要时进行扩展和缩小.

So, I have JTextArea on a JPanel (BoxLayout). I also have Box filler that fills the rest of the JPanel. I need my JTextArea to start of with single-line-height (I can manage that), and to expand and reduce when that is needed.

启用了自动换行,添加/删除新行时,我只需要它来调整它的高度.

Word wrap is enabled, I just need it to adjust it's height when new line is added/removed.

我尝试使用documentListener和getLineCount(),但无法识别自动换行符.

I tried with documentListener and getLineCount(), but it doesn't recognize wordwrap-newlines.

如果可能的话,我希望避免弄乱字体.

I'd like to avoid messing with the fonts if it's possible.

而且,没有乱七八糟的东西.始终显示JTextArea至关重要.

And, NO SCROLL PANES. It's essential that JTextArea is displayed fully at all times.

推荐答案

JTextArea具有相当特殊的副作用,在适当的条件下,它可以自行发展.当我试图设置一个简单的两行文本编辑器(每行限制字符长度,最多两行)时,偶然发现了这个问题.

JTextArea has a rather particular side effect, in the right conditions, it can grow of it's own accord. I stumbled across this by accident when I was trying to set up a simple two line text editor (restricted characters length per line, with a max of two lines)...

基本上,只要有了合适的布局管理器,这个组件就可以独立发展-确实有道理,但让我感到惊讶...

Basically, given the right layout manager, this component can grow of it's own accord - it actually makes sense, but took me by surprise...

此外,如果您对此感兴趣,则可能需要使用ComponentListener来监视组件何时更改尺寸.

Now in addition, you may want to use a ComponentListener to monitor when the component changes size, if that's what you're interested...

public class TestTextArea extends JFrame {

    public TestTextArea() {

        setLayout(new GridBagLayout());

        JTextArea textArea = new JTextArea();
        textArea.setColumns(10);
        textArea.setRows(1);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        add(textArea);

        setSize(200, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);

        textArea.addComponentListener(new ComponentAdapter() {

            @Override
            public void componentResized(ComponentEvent ce) {

                System.out.println("I've changed size");

            }

        });

    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new TestTextArea();
    }

}

这篇关于JTextArea自动换行大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆