Java Textarea ScrollPane

一曲冷凌霜 提交于 2019-12-20 07:16:16

问题


I have created a textarea, and i need a scrollbar applied to the textarea when necessary (when the text gets too long down and it cant be read anymore).

this is the code i have written, but for some reason, the scrollbar doesnt really come up?

    final JTextArea textArea = new JTextArea();
    textArea.setEditable(false);
    textArea.setBounds(10, 152, 456, 255);
    textArea.setBorder(border);
    textArea.setLineWrap(true);
    sbrText = new JScrollPane(textArea);
    sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    panel_1.add(textArea);

回答1:


see this

 import javax.swing.*;

    public class TestFrame extends JFrame

{
    JTextAreaWithScroll textArea;

    public TestFrame ()
    {
        super ("Test Frame");

        setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        setSize (300, 300);

        textArea = new JTextAreaWithScroll (JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        add (textArea.getScrollPane ());
    }

    public static void main (String[] args)
    {
        SwingUtilities.invokeLater (new Runnable()
        {
            public void run ()
            {
                TestFrame f = new TestFrame ();
                f.setVisible (true);
            }
        });
    }
}


class JTextAreaWithScroll extends JTextArea
{
    private JScrollPane scrollPane;

    public JTextAreaWithScroll (int vsbPolicy, int hsbPolicy)
    {
        scrollPane = new JScrollPane (this, vsbPolicy, hsbPolicy);
    }

    public JScrollPane getScrollPane ()
    {
        return scrollPane;
    }
}

from http://forum.html.it/forum/showthread/t-1035892.html




回答2:


  • You have to remove the code line that makes the JTextArea have absolute size on the screen due to using setBounds(). This makes it non-resizable, and JScrollPane works only if its content is resizable.

    // wrong
    textArea.setBounds(10, 152, 456, 255);
    
  • Please read JTextArea and JScrollPane tutorial; please run examples from both tutorials.




回答3:


You added the TextArea to a parent twice (scrollPane and panel). Change your last line to

panel_1.add(sbrText);



回答4:


Make sure that the preferredSize and the viewportSize are the same. The scrollpane will size itself with the preferred size of the textArea, and this can cause the scrollbars to disappear if the preferred size of the text area is large enough to display itself.

Again, please read the JTextArea and JScrollPane tutorials.

textArea.setPreferredSize(new Dimension(456, 255));
textArea.setPreferedScrollableViewportSize(new Dimension(456, 255));


来源:https://stackoverflow.com/questions/9624014/java-textarea-scrollpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!