Search code examples
javaswingjtextareaword-wrap

JTextArea issue


I'm having an issue with resizing of JTextArea in java.swing. The problem is that once the current line is finished (so for example if i keep pressing space) - it doesn't go to the second line - it just keeps on going. Same thing when i press enter - it stretches out the box vertically. How do I prevent this? I'm using GridBagLayout.

JTextArea MainText = new JTextArea();
MainText.setFont(new Font("Arial", Font.PLAIN, 16));
MainText.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets (10, 10, 10, 10);
c.gridx = 0;
c.gridy = 2;
c.weightx = 1.0;
c.weighty = 1.0;
c.gridwidth = 3;
c.gridheight = 1;
panel.add(MainText, c);

Solution

  • Set the lineWrap and wrapStyleWord properties of the JTextArea

    JTextArea MainText = new JTextArea();
    MainText.setLineWrap(true);
    MainText.setWrapStyleWord(true);
    

    Take a look at How to use Text Areas for more details

    You might also find having a read through Code Conventions for the Java Programming Language of some use

    Unless you really don't want to, I would also suggest adding the JTextArea into a JScrollPane instead of adding it directly to the conatiner

    panel.add(new JScrollPane(MainText), c);
    

    This will prevent the JTextArea from wanting to grow as more text is added to it (unless that's what you're going for)