Search code examples
javaswinglayout-managernull-layout-manager

JTextArea disappears when add JScrollPane


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)?


Solution

  • 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.