Search code examples
javaswingjtextareaword-wrap

JTextArea word wrap resizing


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.


Solution

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

    I'm so smallLook at me grow

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