自动调整大小和滚动的 Java JTextArea
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3843493/
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
Java JTextArea that auto-resizes and scrolls
提问by None
I have a JTextArea in a JPanel. How can I have the JTextArea fill the whole JPanel and resize when the JPanel resizes and scroll when too much text is typed in?
我在 JPanel 中有一个 JTextArea。当 JPanel 调整大小并在输入过多文本时滚动时,如何让 JTextArea 填充整个 JPanel 并调整大小?
采纳答案by jlewis42
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout()); //give your JPanel a BorderLayout
JTextArea text = new JTextArea();
JScrollPane scroll = new JScrollPane(text); //place the JTextArea in a scroll pane
panel.add(scroll, BorderLayout.CENTER); //add the JScrollPane to the panel
// CENTER will use up all available space
See http://download.oracle.com/javase/6/docs/api/javax/swing/JScrollPane.htmlor http://download.oracle.com/javase/tutorial/uiswing/components/scrollpane.htmlfor more details on JScrollPane
有关更多信息,请参阅http://download.oracle.com/javase/6/docs/api/javax/swing/JScrollPane.html或http://download.oracle.com/javase/tutorial/uiswing/components/scrollpane.htmlJScrollPane 上的详细信息
回答by Zoe
Place the JTextArea inside of a JScrollPane, and place that into the JPanel with with a layout that fixes the size. An example with a GridBagLayout, for instance could look like this:
将 JTextArea 放在 JScrollPane 内,然后将其放入 JPanel 并使用固定大小的布局。例如,带有 GridBagLayout 的示例可能如下所示:
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
JScrollPane scrollpane = new JScrollPane();
GridBagConstraints cons = new GridBagContraints();
cons.weightx = 1.0;
cons.weighty = 1.0;
panel.add(scrollPane, cons);
JTextArea textArea = new JTextArea();
scrollPane.add(textArea);
This is only a rough sketch, but it should illustrate how to do it.
这只是一个粗略的草图,但它应该说明如何去做。