我在JPanel中有一个JTextArea。我如何让JTextArea填充整个JPanel并在JPanel调整大小时调整大小并在输入太多文本时滚动?
答案 0 :(得分:19)
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
有关JScrollPane
的更多详细信息,请参阅http://download.oracle.com/javase/6/docs/api/javax/swing/JScrollPane.html或http://download.oracle.com/javase/tutorial/uiswing/components/scrollpane.html答案 1 :(得分:7)
将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);
这只是一个粗略的草图,但它应该说明如何做到这一点。