5

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);
}
ouflak
  • 2,458
  • 10
  • 44
  • 49
seal
  • 1,122
  • 5
  • 19
  • 37
  • Laying out Components in Swing is hard. People are tempted to do setLayout(null); and then do a setBounds() for each component, but this can be difficult and is not recommended. Then you can try using the various LayoutManager classes provided by Swing, this can make layouts somewhat automatic, but it can be hard to figure out how to get it all to work. Nowadays, it helps that the Java API is open-source so you can look at the actual code for laying out Components, but Swing is complex and can be hard to understand even with the source-code. – Kaydell Sep 13 '13 at 18:46
  • What you may want to consider using is a GUI editor to layout your components with a GUI interface instead of writing your own code. Then, you can drag-and-drop your components into place. NetBeans has a GUI editor built-in and Eclipse has several different GUI editors whihch are plugins. (Just a thought.) I'm looking at them. – Kaydell Sep 13 '13 at 18:48
  • actually that was a laboratory assignment for basic GUI. so i wrote raw code. @Kaydell – seal Sep 20 '13 at 15:31
  • You set the dimensions of a `JTextArea` by specifying the number of rows and columns to display. One of the `JTextArea` constructors allows you to do this easily. – Gilbert Le Blanc Apr 27 '23 at 14:49

2 Answers2

9

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);
Ben Dale
  • 2,492
  • 1
  • 14
  • 14
2

PreferredSize is what it say what it is: a preferred size. The border layout determines the actual size (taking the preferred size into considerations).

See: http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html

Consider other layouts to get your desired size. E.G. flowLayout: http://docs.oracle.com/javase/tutorial/uiswing/layout/flow.html

Enigma
  • 1,699
  • 10
  • 14