Search code examples
javaswingjpaneljscrollpanejtextarea

How to immediately show scroll bar in the JScrollPane


I added JScrollPane to my JPanel but I wanted to make scroll bar visible at the start of the program not only when the text is going out of the screen is that possible?

jpMiddle = new JPanel();
    JTextArea ta = new JTextArea(20,43);
    JScrollPane sp = new JScrollPane(ta); 

    jpMiddle.add(sp);

Solution

  • JScrollPane sp = new JScrollPane(ta, 
                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, 
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    

    That's for the scrollbars to be active always, you can substitute the ALWAYS for AS_NEEDED to ensure they appear only when the contents of ths scrollpane overflows.

    The API exists for one reason, though...