将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 );
}
以下是您得到的: