Here is my code. The JScrollpanel shows up but now the scrollbar. I also can't use the scroll wheel if the text goes below the area.
JTextArea textArea = new JTextArea("Enter text here");
textArea.setPreferredSize(new Dimension(100,100));
textArea.setLineWrap(true);
textArea.setEditable(true);
textArea.setVisible(true);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//frame
this.setTitle("GUI Practice");
this.setLayout(new BorderLayout());
this.setResizable(true);
this.setSize(720,480);
this.setLocationRelativeTo ( null );
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(scroll, BorderLayout.SOUTH);
this.setVisible(true);
Never, never, NEVER do this:
textArea.setPreferredSize(new Dimension(100,100));
You are artificially constraining the size of the JTextArea, and you yourself are causing the JScrollPane to fail. Instead, set the JTextArea's column and row properties.
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;
@SuppressWarnings("serial")
public class GuiPracticePanel extends JPanel {
private static final int ROWS = 10;
private static final int COLS = 80;
private static final String INIT_TEXT = "Enter text here";
private JTextArea textArea = new JTextArea(INIT_TEXT, ROWS, COLS);
public GuiPracticePanel() {
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setLayout(new BorderLayout());
add(Box.createRigidArea(new Dimension(400, 300)));
add(scrollPane, BorderLayout.PAGE_END);
textArea.selectAll();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
GuiPracticePanel mainPanel = new GuiPracticePanel();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}