Search code examples
javauser-interfacescrolljscrollpanejtextpane

JTextPane Scrolling


I am aware of the fact that there have been similar questions asked about this topic, but after a few hours of research, I have come to no solution.

My question is why no scroll bar is showing on my JTextPane. Below is my code:

import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

import java.awt.BorderLayout;

import javax.swing.JTextPane;

public class OtherNotesWindow extends JFrame{

JTextPane page;
JPanel panel;


public OtherNotesWindow() {
    super("Other Notes Window");
    init();
    page.setFocusable(true);
    this.setSize(400,400);
    this.setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocation(400,400);
}

public void init(){
    panel = new JPanel();
    page = new JTextPane();
    JScrollPane scroll = new JScrollPane(page, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scroll.setViewportView(page);
    panel.add(scroll);
    this.add(page);
}
}

I don't know why no scroll bar, both vertical and horizontal, aren't showing up. Can anyone please tell me why?

Thanks in advance to anyone who replies. :)


Solution

  • Take a closer look at your code...

    // Create a  panel...
    panel = new JPanel();
    // Create a scroll pane
    page = new JTextPane();
    // Create a scroll pane with page as the view
    JScrollPane scroll = new JScrollPane(page, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    // A little redudent as you did this when you created the scoll pane, but what ever
    scroll.setViewportView(page);
    // Add the scroll pane to the panel
    panel.add(scroll);
    // Add the page to this...wait what??!
    this.add(page);
    

    This last line is you undoing, it is is removing page from the JScrollPane and simply adding to the JFrame...no scroll pane or anything...

    You need to change it to something like...

    this.add(panel);
    

    or

    this.add(scroll);
    

    Remember, JPanel by default uses a FlowLayout, which might not meet your requirements