Java:无法将Gridlayout应用于Jscrollpane。 获取java.lang.ClassCastException

我使用Gridlayout将4个元素放在一行中。 首先,我有一个JPanel,一切正常。 对于行数变大而我必须能够向下滚动的情况,我改变了一点。 现在我的JPanel上添加了一个JScrollPane 。 我使用了相同的代码,现在我只是将元素添加到Jscrollpane的视口中,但现在我得到了这个exceptionGet java.lang.ClassCastException: layout of JScrollPane must be a ScrollPaneLayout: at javax.swing.JScrollPane.setLayout(Unknown Source)我不确切知道为什么。 为什么不应该为Jscrollpane不知道Jscrollpane

这是代码:

  public objectDetails() { setTitle("LLI_MC_Solver"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); contentPane = new JPanel(); contentPane.setLayout(new GridLayout()); setBounds(100, 100, 510, 401); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setVisible(true); contentPane.setPreferredSize(new Dimension(500, 390)); JScrollPane scrollPane = new JScrollPane(); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setViewportBorder(new LineBorder(new Color(0, 0, 0), 2)); scrollPane.setBounds(10, 10, 474, 342); scrollPane.setLayout(new GridLayout(0,4)); //Line which causes the error scrollPane.setPreferredSize(new Dimension(465, 330)); contentPane.add(scrollPane); JPanel view = (JPanel)scrollPane.getViewport().getView(); for(Values v : colDetails) { JLabel lblC = new JLabel(); lblC.setText(k); view.add(lblC); view.validate(); JLabel lblN = new JLabel(); lblN.setText(v.getName()); view.add(lblN); view.validate(); JLabel lblT = new JLabel(); lblT.setText(v.getType()); view.add(lblT); view.validate(); JTextField valueBox = new JTextField(); valueBox.setText(v.getValue()); view.add(valueBox); view.validate(); } } 

我根据编译器标记了引起问题的行。 我不明白为什么,与JPanel相同的代码工作得很好。 添加元素的for循环我发布用于完成目的,问题必须在setLayout() Method中的某处。

在此先感谢,感谢每一位帮助。

scrollPane.setLayout(new GridLayout(0,4)); //导致错误的行

您无法更改滚动窗格的布局管理器。

JScrollPane有自己的自定义布局管理器,因为它需要管理水平/垂直滚动条以及行/列标题等。

而是添加一个使用GridLayout的面板:

 JPanel panel = new JPanel( new GridLayout(0, 4) ); panel.add( component1 ); panel.add( component2 ); panel.add( component3 ); panel.add( component4 ); JScrollPane = new JScrollPane( panel );