Search code examples
javaswingjscrollpanejtextarea

Scroll bars for JTextArea


I'm trying to create a scroll bar for my text area. However, the scroll bar isn't appearing. Can anyone give me any tips. This is the from the method which creates the panel where the scroll bar will be.

displayCD = new JPanel();
displayCD.setSize(new Dimension(500, 500));

jta = new JTextArea();
jta.setMaximumSize(new Dimension(500, 500));
scrollPane = new JScrollPane();
scrollPane.getViewport().add(jta);

displayCD.add(scrollPane);

Solution

  • see this example. JScrollPane.VERTICAL_SCROLLBAR_ALWAYS property.

    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    
    public class Main {
      public static void main(String[] argv) throws Exception {
        JTextArea textArea = new JTextArea();
        JScrollPane pane = new JScrollPane(textArea);
        pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    
      }
    }
    

    Reference: http://www.java2s.com/Code/JavaAPI/javax.swing/JScrollPaneVERTICALSCROLLBARALWAYS.htm