简体   繁体   中英

Stop JTextArea from expanding

I'm trying to read information off of a data file and process it into a JTextArea for an about file for a term project that I'm making. The problem is that when I do scanner.nextLine() it's expanding the text area to fit the text and what I wanted was it to keep the size of the text area the same and if it runs out of space on the current line to start on the

    if(event.getSource() == forward)
    {
        text.setText(s.nextLine());
    }

The text area is setup like this:

     text = new JTextArea(11, 30); 

Basically what I want to know is if there's a method that text area offers (I looked) that relocates space to the next line if the current is full. I can most likely just edit the data file if there isn't a way to do it in the text area.

Place the JTextArea within a JScrollPane and add the scroll pane to your container instead

text = new JTextArea(11, 30);
JScrollPane scrollpane = new JScrollPane(text);
//...
add(scrollpane);

See How to use Scroll Panes for more details

This will prevent the scroll pane from growing in the current container.

Also check out JTextArea#setLineWrap and JTextArea#setWrapStyleWord which will effect how the component treats text that would exceed the viewable width.

See How to use Text Areas for more details

You can use JTextArea#setLineWrap(true) by default is set to false.

Sets the line-wrapping policy of the text area. If set to true the lines will be wrapped if they are too long to fit within the allocated width. If set to false, the lines will always be unwrapped. A PropertyChange event ("lineWrap") is fired when the policy is changed. By default this property is false.

Also see this method JTextArea#setWrapStyleWord(true)

Example a SSCCE:

   public class JTextAreaTest {

    public static void main(String args[]){

        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        frame.add(panel);
        JTextArea textArea = new JTextArea(11,30);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setText("Hi how are you? Im testing this textarea and im seeing if it's wrapping words");
        textArea.append("SASASASASDASDASDASDASDASDADSASDASDASDASDAS");
        JScrollPane scrollPane = new JScrollPane(textArea);
        panel.add(scrollPane);

        frame.pack();
        frame.setVisible(true);
    }

}

textArea示例

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM