0

我已经创建了一个 textarea,并且我需要在必要时将滚动条应用于 textarea(当文本太长并且无法再阅读时)。

这是我写的代码,但由于某种原因,滚动条并没有真正出现?

    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);
4

4 回答 4

1

看到这个

 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;
    }
}

来自 http://forum.html.it/forum/showthread/t-1035892.html

于 2012-03-08T20:09:01.787 回答
1
  • 您必须删除JTextArea由于使用setBounds(). 这使其不可调整大小,并且JScrollPane仅在其内容可调整大小时才有效。

    // wrong
    textArea.setBounds(10, 152, 456, 255);
    
  • 请阅读JTextAreaJScrollPane教程;请运行两个教程中的示例。

于 2012-03-08T20:04:11.007 回答
0

您将 TextArea 添加到父级两次(scrollPane 和面板)。将最后一行更改为

panel_1.add(sbrText);
于 2012-03-08T20:07:45.323 回答
0

确保 thepreferredSizeviewportSizethe 相同。滚动窗格将根据 的首选大小自行调整大小,textArea如果文本区域的首选大小足以显示自身,这可能会导致滚动条消失。

同样,请阅读JTextAreaJScrollPane教程。

textArea.setPreferredSize(new Dimension(456, 255));
textArea.setPreferedScrollableViewportSize(new Dimension(456, 255));
于 2016-11-15T16:24:51.280 回答