简体   繁体   English

JScrollPane中JTextArea上的滚动条不起作用

[英]Scrollbars on JTextArea in a JScrollPane do not work

I'm having trouble getting a JTextArea to scroll. 我无法让JTextArea滚动。 I'm not sure how you can mess up a JScrollPane but I seem to have and I just can't see it. 我不知道你怎么会弄乱JScrollPane,但我似乎有,我只是看不到它。 It's all part of a larger project but the code below is how I'm creating a JTextArea and adding it to a JScrollPane. 这是一个更大项目的所有部分,但下面的代码是我如何创建一个JTextArea并将其添加到JScrollPane。 When you type beyond the edge of the text area the scrollbar doesn't appear. 当您在文本区域的边缘外键入时,不会出现滚动条。 Setting the vertical scrollbar to always on gives a scrollbar that doesn't do anything. 将垂直滚动条设置为始终打开会生成一个不执行任何操作的滚动条。

import javax.swing.*;
import java.awt.*;

public class TextAreaTest extends JFrame{

    public TextAreaTest() {
     super("Text Area Scroller");

     Container c = getContentPane();

     JTextArea textarea = new JTextArea();
     textarea.setPreferredSize(new Dimension(300, 50));
     textarea.setLineWrap(true);
     textarea.setText("xx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\n");

     JScrollPane scroller = new JScrollPane(textarea);

     c.add(scroller, BorderLayout.CENTER);
     pack();
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String args[]){
     TextAreaTest instance = new TextAreaTest();
     instance.setVisible(true);
    }
}

I've tried setting the text area text, or rows and columns, in the constructor, neither of which worked. 我已经尝试在构造函数中设置文本区域文本或行和列,两者都不起作用。 It's doing my head in. Any ideas? 它正在努力。任何想法?

设置滚动窗格的首选大小而不是文本区域。

The others are right about the size. 其他人的规模是正确的。 As an aside, consider starting on the Event Dispatch Thread ( EDT ): 另外,请考虑从Event Dispatch Thread( EDT )开始:

public static void main(String args[]) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            new TextAreaTest().setVisible(true);
        }
    });
}

Use this code 使用此代码

import javax.swing.*;
public class ScrollingTextArea 
{
JFrame f;
JTextArea ta;
JScrollPane scrolltxt;

public ScrollingTextArea() 
{
    // TODO Auto-generated constructor stub

    f=new JFrame();
    f.setLayout(null);
    f.setVisible(true);
    f.setSize(500,500);
    ta=new JTextArea();
    ta.setBounds(5,5,100,200);

    scrolltxt=new JScrollPane(ta);
    scrolltxt.setBounds(3,3,400,400);

    f.add(scrolltxt);

}

public static void main(String[] args)
{
    new ScrollingTextArea();
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM