java 如何在java中将滚动条添加到textarea

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33931061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:18:19  来源:igfitidea点击:

how to add scrollbar to textarea in java

javaswingtextareascrollbar

提问by Christian

the jscrollpane that I am adding doesnt appearin my textarea

我添加的 jscrollpane 没有出现在我的 textarea 中

textArea = new JTextArea();
 scroll = new JScrollPane(textArea);
          scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

         this.add(textArea);
         this.add(scroll);

          this.setSize(1000, 600);
       this.setLayout(new BorderLayout());


        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

回答by camickr

textArea = new JTextArea();
scroll = new JScrollPane(textArea);
//this.add(textArea); // get rid of this
this.add(scroll);

You create the scrollpane with the text area, but then the next statement removes the text area from the scrollpane because a component can only have a single parent.

您使用文本区域创建滚动窗格,但随后的下一条语句从滚动窗格中删除文本区域,因为组件只能有一个父级。

Get rid of that statement and just add the scrollpane to the frame.

摆脱该语句,只需将滚动窗格添加到框架中。

Then scrollbars will appear automatically as you add data to the text area.

当您向文本区域添加数据时,滚动条将自动出现。

Also you should create the text area using something like:

您还应该使用以下内容创建文本区域:

textArea = new JTextArea(5, 20);

to give a suggestion on how big to make the text area.

给出关于使文本区域有多大的建议。

I did what you said but still nothing happens

我做了你说的但仍然没有任何反应

Another problem is that you need to set the layout manager BEFORE you start adding components to the frame (or panel).

另一个问题是您需要在开始向框架(或面板)添加组件之前设置布局管理器。

回答by Gayan Rajapakse

Remove this.add(textArea);and add scroll.setSize( 100, 100 );will also work for you.

删除this.add(textArea);和添加scroll.setSize( 100, 100 );也适用于您。