Java JTextArea that auto-resizes and scrolls

倾然丶 夕夏残阳落幕 提交于 2019-12-23 07:01:24

问题


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?


回答1:


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.html or http://download.oracle.com/javase/tutorial/uiswing/components/scrollpane.html for more details on JScrollPane




回答2:


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:

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.



来源:https://stackoverflow.com/questions/3843493/java-jtextarea-that-auto-resizes-and-scrolls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!