2013-11-03 23 views
1

我使用Gridlayout將4個元素放在一行中。首先我有一個JPanel,一切正常。對於線數變大而我必須能夠向下滾動的情況,我稍微改了一下。現在我有我的JPanel,其上添加了一個JScrollPane。我使用了相同的代碼,現在我只是將元素添加到Jscrollpane的視口中,但現在我得到此異常Get java.lang.ClassCastException: layout of JScrollPane must be a ScrollPaneLayout: at javax.swing.JScrollPane.setLayout(Unknown Source),我不知道爲什麼。爲什麼不應該是Gridlayout的Jscrollpane未知?Java:無法將Gridlayout應用於Jscrollpane。獲取獲取java.lang.ClassCastException

下面是代碼:

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-loop,問題必須在setLayout()-方法中的某處。

在此先感謝,感謝每一個幫助。

回答

8

scrollPane.setLayout(new GridLayout(0,4)); //導致錯誤的行

您無法更改滾動窗格的佈局管理器。

JScrollPane中,有它自己的自定義佈局管理器,因爲它需要管理水平/垂直滾動以及行/列表頭等等。

相反,你添加使用網格佈局面板:

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

我認爲這是'JScrollPane'中的一個bug ... setLayout應該被保護...'public void setLayout(LayoutManager layout)'' –