I saw a few questions like this question, but I couldn't get this solved. I cannot get a JScrollPane
visible on JTextArea
. Can anyone please point out where I have done my mistake? Thanks.
package experiement;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Experiment extends JFrame{
public Experiment(){
JTextArea tarea=new JTextArea();
tarea.setBounds(100,100,200,200);
JScrollPane pan= new JScrollPane();
pan.setPreferredSize(new Dimension(100,100));
pan=new JScrollPane(tarea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
add(pan);
add(tarea);
setLayout(null);
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[]aegs){
Experiment e=new Experiment();
}
}
When you use
JTextArea
component withJSrcollPane
component you should set size and position to the last component and not to the first one, and when you add the created elements to theJFrame
you should only addJScrollPane
component because it is considered as container to theJTextArea
component, try this code:Problems with your code:
setBounds()
might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.Instead:
For example say you wanted a JTextArea inside of a JScrollPane within the center of your GUI, with buttons on top and a JTextField and a submit button below, say a typical chat window type application, you could make the overall layout a BorderLayout, add a GridLayout-using JPanel with buttons to the top, a BoxLayout using JPanel with the JTextField and submit button to the bottom, and the JScrollPane holding the JTextArea to the center. It could look like this:
and the code could look like this:
EDIT
Rather than guess what works and what doesn't, let's experiment and create a GUI that holds two JTextAreas, one where the columns and rows property is set and held by the colRowTextArea variable, and another where the preferred size of the JTextArea is set, and call its variable the prefSizeTextArea.
We'll create a method,
setUpTextArea(...)
where we place the JTextArea into a JScrollPane, place this into a JPanel, and have a button that adds lots of text into the JTextArea, and see what happens with the behavior of the JTextArea when text is added.Here's the code and push the buttons and see for yourself which one scrolls: