0

I'm currently learning the javax.swing package. Created a JFrame that currently has a JMenuBar and a JTextArea. I've been trying to add a scrollbar to my application using JScrollPane but am having no luck. The scrollbar never appears with my code and I'm not sure what's the issue.

import java.awt.*;
import javax.swing.*;
class WordProcessor {
JFrame frame;
JMenuBar menu;
JTextArea textArea;
JScrollPane scrollPane;

public WordProcessor() {
    scrollPane = new JScrollPane(frame);


    //Create Frame for application
    frame = new JFrame("Word Processor");
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setBackground(Color.decode("#FFC0CB"));
    
    menuBar();
    textArea();
    scrollPane();

}

public void scrollPane() {
    scrollPane = new JScrollPane();
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    frame.add(scrollPane);
}

For clarification, I'm trying to add a scrollbar for the whole window — not the text area.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
dluisely
  • 71
  • 7
  • 1
    *"I'm trying to add a scrollbar for the whole window"* It makes sense for a table header to always appear at the very top of a `JScrollPane`. The same is true for a `JMenuBar`. The only other thing the frame contains is a `JTextArea` so it makes sense the scroll pane should apply to that. BTW: For better help sooner, [edit] to add a [mre]. My *guess* is that there is a problem in the `textArea()` method (but post a complete MRE). – Andrew Thompson Feb 14 '22 at 10:31
  • 1
    This GUI has further problems obvious even from the code provided: 1) `frame.setVisible(true);` should be last, it should be immediately after `frame.pack()`. 2) A call to `setBackground(Color.decode("#FFC0CB"))` will likely not change anything visually, as the entire content pane will be filled with opaque components. 3) `scrollPane = new JScrollPane(); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);` would better be `scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.VERTICAL_SCROLLBAR_NEVER);` – Andrew Thompson Feb 14 '22 at 10:36
  • 1
    Oracle has a helpful tutorial, [Creating a GUI With Swing](https://docs.oracle.com/javase/tutorial/uiswing/index.html). Skip the Learning Swing with the NetBeans IDE section. The [How to Use Scroll Panes](https://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html) section shows you how to use scroll panes. – Gilbert Le Blanc Feb 14 '22 at 10:39

0 Answers0