在此处将 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 );
}
这就是你得到的: