Search code examples
javaswingjscrollpanejtextarea

JScrollPane not scrolling in JTextArea and is staying disabled


I am trying to make a simple text editor using JTextArea, but when I type more text so that it goes off the screen, the JScrollPane is still not enabled and not letting me to scroll. I've looked for hours for answers on the internet but nothing seemed to help me. Here is my code:

import mods.JFrame.JFrameMods;
import javax.swing.*;

public class NimbleIDE {
    
    JFrame frame;
    JTextArea main;
    JScrollPane scroll = new JScrollPane(main);
    
    NimbleIDE() {
        frame = new JFrame();
        main = new JTextArea();
        frame.add(main);
        
        //Frame setting up
        initialiseBlankJFrame(frame, "NimbleIDE");
        frame.add(scroll);
        
        //Text setting up
        main.setSize(JFrameMods.getScreenWidth() - 14, JFrameMods.getScreenHeight()); //JFrameMods is a custom class I made previously
        main.setWrapStyleWord(true);
        main.setLineWrap(true);
        main.setEditable(true);
        
        //Scroll setting up
        scroll.setBounds(JFrameMods.getScreenWidth() - 14, 0, 16, JFrameMods.getScreenHeight() - 23);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        
    }
    
    initialiseBlankJFrame(JFrame frame, String title) {
        frame.setVisible(true);
        frame.setExtendedState(MAXIMIZED_BOTH);
        frame.setLayout(null);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(Color.white);
        frame.setTitle(title);
    }
    
}

Solution

  • This:

    JTextArea main;
    JScrollPane scroll = new JScrollPane(main);
    

    effectively means this:

    JScrollPane scroll = new JScrollPane(null);
    

    You're passing a null object to the JScrollPane.


    You can fix your problem by passing an actual JTextArea object to your scroll pane. Also note that the scroll pane is the only component that you explicity have to add to your JFrame. Something like this:

    public class NimbleIDE {
        JFrame frame;
        JTextArea main;
        JScrollPane scroll;
        
        NimbleIDE() {
            frame = new JFrame();
            main = new JTextArea();
            scroll = new JScrollPane(main);
    
            //Frame setting up
            initialiseBlankJFrame(frame, "NimbleIDE");
            frame.add(scroll);
    
            // ...
        }
        // ...
    }
    

    You may also want to take a look at the following Java Trails: