Search code examples
javaswingjscrollpanejtextarea

Enable ScrollPane when components exceed inside a text area


Before anything else there might be some people who already asked this question. However, i am certain that I couldn't google it. Anyway, I have a scrollPane which has a viewPortView of textArea. My question is I would like to show my scrollpane when i insert numerous components inside my textArea. How am i supposed to do this? I have no idea and I'm not that expert with Javax Swing. Code goes like this:

textArea = new JTextArea();
scrollPane = new JScrollPane();
   textArea.setBounds(0,50,520,550);
   textArea.setBackground(Color.DARK_GRAY);
   scrollPane.setBounds(textArea.getBounds());
   scrollPane.setViewportView(textArea);

thanks for the help!


Solution

  • My question is I would like to show my scrollpane when i insert numerous components inside my textArea.

    A text area displays text, not components. The scrollbars will appear automatically when you actually add text to the text area.

    textArea.setBounds(0,50,520,550);
    

    Don't use setBounds. Swing was designed to be used with layout managers. In particular a JScrollPane will only work properly when you use layout managers.

    //textArea = new JTextArea();
    textArea = new JTextArea(5, 20);
    

    When you create a JtextArea use code like the above. This will allow the text area to determine its own preferred size. Then scrollbars will appear once you add more than 5 rows of text.

    Read the section from the Swing tutorial on How to Use Text Areas for more information and working examples. Keep a link to the tutorial handy for all Swing basics.