java JScrollPane 中 JTextArea 上的滚动条不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2687023/
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
Scrollbars on JTextArea in a JScrollPane do not work
提问by Robert
I'm having trouble getting a JTextArea to scroll. I'm not sure how you can mess up a JScrollPane but I seem to have and I just can't see it. 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. 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.
我无法让 JTextArea 滚动。我不确定您如何弄乱 JScrollPane,但我似乎有,但我看不到它。它是更大项目的一部分,但下面的代码是我如何创建 JTextArea 并将其添加到 JScrollPane。当您键入超出文本区域的边缘时,不会出现滚动条。将垂直滚动条设置为始终打开会提供一个不执行任何操作的滚动条。
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?
我试过在构造函数中设置文本区域文本或行和列,但都不起作用。这让我很头疼。有什么想法吗?
回答by ColinD
Set the preferred size of the scroll pane rather than the text area.
设置滚动窗格而不是文本区域的首选大小。
回答by trashgod
回答by Sachindra N. Pandey
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();
}
}
}

