Java:将滚动添加到文本区域
如何将滚动条添加到我的文本区域。 我试过这个代码,但它没有用。
middlePanel=new JPanel(); middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Display Area")); // create the middle panel components display = new JTextArea(16, 58); display.setEditable(false); // set textArea non-editable scroll = new JScrollPane(display); scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); //Add Textarea in to middle panel middlePanel.add(scroll); middlePanel.add(display);
谢谢
在这里将JTextArea添加到JScrollPane之后:
scroll = new JScrollPane(display);
您不需要像以下那样将其再次添加到其他容器中:
middlePanel.add(display);
只需删除最后一行代码,它就可以正常工作。 喜欢这个:
middlePanel=new JPanel(); middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Display Area")); // create the middle panel components display = new JTextArea(16, 58); display.setEditable(false); // set textArea non-editable scroll = new JScrollPane(display); scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); //Add Textarea in to middle panel middlePanel.add(scroll);
JScrollPane只是另一个容器,它在需要时将滚动条放在组件周围,并且还有自己的布局。 当你想把任何东西包装成一个滚动时你需要做的就是把它传递给JScrollPane构造函数:
new JScrollPane( myComponent )
或设置如下视图:
JScrollPane pane = new JScrollPane (); pane.getViewport ().setView ( myComponent );
额外:
这是完全有效的例子,因为你仍然没有让它工作:
public static void main ( String[] args ) { JPanel middlePanel = new JPanel (); middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) ); // create the middle panel components JTextArea display = new JTextArea ( 16, 58 ); display.setEditable ( false ); // set textArea non-editable JScrollPane scroll = new JScrollPane ( display ); scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS ); //Add Textarea in to middle panel middlePanel.add ( scroll ); // My code JFrame frame = new JFrame (); frame.add ( middlePanel ); frame.pack (); frame.setLocationRelativeTo ( null ); frame.setVisible ( true ); }
这是你得到的:
我天真的假设是滚动窗格的大小将自动确定…
实际上对我有用的唯一解决方案是明确地发布JScrollPane的边界 :
import javax.swing.*; public class MyFrame extends JFrame { public MyFrame() { setBounds(100, 100, 491, 310); getContentPane().setLayout(null); JTextArea textField = new JTextArea(); textField.setEditable(false); String str = ""; for (int i = 0; i < 50; ++i) str += "Some text\n"; textField.setText(str); JScrollPane scroll = new JScrollPane(textField); scroll.setBounds(10, 11, 455, 249); // <-- THIS getContentPane().add(scroll); setLocationRelativeTo ( null ); } }
也许它会帮助一些未来的访客:)
尝试将这两行添加到您的代码中。 我希望它能奏效。 它对我有用:)
display.setLineWrap(true); display.setWrapStyleWord(true);
输出图片如下所示