JTextArea word wrap resizing

我是研究僧i 提交于 2019-12-10 13:16:34

问题


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.

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.

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


回答1:


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...

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();
    }

}


来源:https://stackoverflow.com/questions/12021860/jtextarea-word-wrap-resizing

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