Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a Scrollable JTextArea (Java)

Tags:

java

swing

I am trying to add a scroll bar to a JTextArea. Would someone please tell me what I did wrong with the code below?

JFrame frame = new JFrame ("Test"); JTextArea textArea = new JTextArea ("Test");  JScrollPane scrollV = new JScrollPane (textArea); JScrollPane scrollH = new JScrollPane (textArea);  scrollV.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollH.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); frame.setVisible (true); 

Thank you in advance.

EDIT: I fixed the code with the Adel Boutros' advice below.

    //FRAME JFrame frame = new JFrame ("Test"); frame.setSize(500,500); frame.setResizable(false); //  //TEXT AREA JTextArea textArea = new JTextArea("TEST"); textArea.setSize(400,400);          textArea.setLineWrap(true);     textArea.setEditable(false);     textArea.setVisible(true);      JScrollPane scroll = new JScrollPane (textArea);     scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);           scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);      frame.add(scroll);     frame.setVisible(true);     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
like image 759
Nyx Avatar asked Jan 13 '12 10:01

Nyx


People also ask

How do I add a scroll pane in Java?

JPanel panel = new JPanel(); JScrollPane scrollPane = new JScrollPane( panel ); When you add buttons to the panel at run time the code should be: panel. add( button ); panel.

How do I add a scroll pane in JFrame?

fill = GridBagConstraints. BOTH; guiPanel. add(scrollPane, gbc); gbc.

What is scrollable in Java?

public interface Scrollable. An interface that provides information to a scrolling container like JScrollPane. A complex component that's likely to be used as a viewing a JScrollPane viewport (or other scrolling container) should implement this interface.

How do I add a Scrollbar in Netbeans?

In the Navigator, click on JPanel with the right mouse button --> Enclose In --> Scroll Pane.


1 Answers

It doesn't work because you didn't attach the ScrollPane to the JFrame.

Also, you don't need 2 JScrollPanes:

JFrame frame = new JFrame ("Test"); JTextArea textArea = new JTextArea ("Test");  JScrollPane scroll = new JScrollPane (textArea,     JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  frame.add(scroll); frame.setVisible (true); 
like image 56
Adel Boutros Avatar answered Sep 21 '22 22:09

Adel Boutros