Ahmed Ahmed - 2 months ago 12
Java Question

JScrollPane on a TextArea

Okay, I've read almost all the threads about this topic in this website, but they all look confusing to me to be honest and none of them works with my code.
I've created a simple TextArea

JTextArea ttt=new JTextArea("");
ttt.setSize(500, 300);
ttt.setLocation(10, 100);
ttt.setEditable(false);


then created the Scrollpane with this line and added it to the TextArea

JScrollPane sp=new JScrollPane(ttt,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);


And added it to my JFrame afterwards

myForm.add(sp);


As I read on most of the threads, this code should be working, but it's not. The TextArea was shown on the frame before I try to add the ScrollPane, but now the whole TextArea isn't even showing. Thank you.

Edit; here's my main for example, isn't working

public class Test2 {

public static void main(String[] args) {
JFrame myForm=new JFrame("Connect-4");
myForm.setLayout(new GridLayout(4,2)); // assign layout
myForm.setSize(new Dimension(500,400)); // size

JTextArea ttt = new JTextArea (3,3 );
ttt.setEditable(false);
//ttt.setSize(500, 300);
//ttt.setLocation(10, 100);
JScrollPane sp=new JScrollPane(ttt,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
myForm.add(sp);

myForm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myForm.setLayout(null);
myForm.setVisible(true);

}
}


Edit 2; 2 Jlabel, 2 textfield, button and a textarea
image

Edit 3;

public class Test2 {

public static void main(String[] args) {
JButton button=new JButton("Add");
//button.setSize(100, 50);
//button.setLocation(450, 40);


JTextField tf1=new JTextField();
tf1.setSize(150, 30);
tf1.setLocation(70, 52);


JLabel l1=new JLabel("Name");
//l1.setSize(51, 50);
//l1.setLocation(10, 40);
l1.setFont(new Font("", Font.PLAIN, 20));


JTextField tf2=new JTextField();
tf2.setSize(150, 30);
tf2.setLocation(285, 52);

JLabel l2=new JLabel("Phone");
l2.setSize(55, 50);
l2.setLocation(225, 40);
l2.setFont(new Font("", Font.PLAIN, 20));

//////
JTextArea ttt=new JTextArea("");
ttt.setSize(500, 300);
ttt.setLocation(10, 100);

JPanel panel1=new JPanel(new FlowLayout());
panel1.add(l1);
panel1.add(tf1);
panel1.add(l2);
panel1.add(tf2);
panel1.add(button);


JPanel panel2=new JPanel();
panel2.add(new JButton("FSFSD"));
panel2.add(new JButton("RIGHT"));

JPanel all=new JPanel(new BorderLayout());
all.add(panel1, BorderLayout.NORTH);
all.add(ttt, BorderLayout.CENTER);

JFrame frame=new JFrame();
frame.setContentPane(all);
//frame.add(all);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);
frame.setVisible(true);


}
}

Answer

You are setting a layout with

myForm.setLayout(new GridLayout(4,2));

and then removing it with

myForm.setLayout(null);

Remove this line and you will see your text area.

You might also want to call myFrame.pack() before displaying the frame.