Size of Text Area in java

seal picture seal · Sep 12, 2013 · Viewed 27.5k times · Source

I am writing a code for basic GUI. There i need a Text Area. But i can not make the Text Area in my desirable size. i use setPreferredSize method to set the dimension of the Text Area. But it did not work. I also tried setSize method but did not work also. Here is my written code.

 private void textArea() {
    setTitle("TextArea");
    setSize(700, 500);
    setLayout(new BorderLayout());


    JTextArea textArea = new JTextArea();

    textArea.setPreferredSize(new Dimension(100,100));
    System.out.println(textArea.getSize());

    textArea.setBackground(Color.GREEN);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(false);


    add(textArea,BorderLayout.CENTER);
}

Answer

Ben Dale picture Ben Dale · Sep 12, 2013

setPreferredSize won't always work, plus, it's strongly advised that you use the built in layout managers to deal with any sizing issues.

Try and set the columns and rows on the text area:

new JTextArea(5, 10);