1

I am an amateur in Java Swing and can't get my head around the following problem.

As soon as I add JScrollPane to the JTextArea, neither of components is visible in the GUI.

I know that I shouldn't add text area when I add its scroll (I commented that line out), but it doesn't help.

    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JTextArea textArea = new JTextArea();
    textArea.setBounds(213, 11, 186, 240);
// NOT CALLING       frame.getContentPane().add(textArea);
    scroll = new JScrollPane(textArea);
    scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

    frame.getContentPane().add(scroll);

It worked for me only when I used BorderLayout, but this is not the layout I would like to use.
My goal is to place several text area's in the frame.

What do I do to get text area displayed with scroll, say, with AbsoluteLayout (null)?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Vlad.Bachurin
  • 1,340
  • 1
  • 14
  • 22
  • 1
    Your use of `setBounds()` conflicts with the default `BorderLayout`. Please edit your question to include a [mcve]. – trashgod Feb 06 '16 at 01:18
  • 1
    [Why is it frowned upon to use a null layout in SWING?](http://stackoverflow.com/questions/6592468/why-is-it-frowned-upon-to-use-a-null-layout-in-swing) – MadProgrammer Feb 06 '16 at 02:39
  • 1
    Avoid using `null` layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify – MadProgrammer Feb 06 '16 at 02:39

1 Answers1

5

Your frame uses a null layout.

You add the scroll pane to the frame, but the size of the scroll pane is (0, 0) so there is nothing to paint.

Don't use a null layout.

Insteasd use a layout manager. The layout manager will then manage the size and location of each components so you don't have to. Don't try to reinvent the wheel, layout managers were created for a reason and there is absolutely no reason to attempt to use a null layout when using a JScrollPane/JTextArea.

textArea.setBounds(213, 11, 186, 240);

By the way that code will do nothing when you add the text area (or any component) to the scroll pane. Then scroll pane uses its own layout manager and will override those values.

JTextArea textArea = new JTextArea();

Don't use code like that to create the text area. Instead use something like:

JTextArea textArea = new JTextArea(5, 30);

Now the text area can determine its own preferred size and that information can be used by the layout managers.

camickr
  • 321,443
  • 19
  • 166
  • 288