您的位置:首頁技術文章
文章詳情頁

Java:無法將Gridlayout應用于Jscrollpane。獲取獲取java.lang.ClassCastException

瀏覽:73日期:2024-05-05 08:39:35
如何解決Java:無法將Gridlayout應用于Jscrollpane。獲取獲取java.lang.ClassCastException?

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 );解決方法

我使用Gridlayout在一行中放置4個元素。首先,我有一個JPanel,一切正常。對于行數變大并且必須向下滾動的情況,我做了一些更改。現在我添加JPanel了一個JScrollPane。我使用了相同的代碼,現在我只是將元素添加到的視口中Jscrollpane,但是現在卻遇到了這個異常Getjava.lang.ClassCastException: layout of JScrollPane must be aScrollPaneLayout: at javax.swing.JScrollPane.setLayout(UnknownSource),我也不知道為什么。為什么不應該不知道Gridlayout的原因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)); 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),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中。

在此先感謝,感謝您的幫助。

標簽: java
相關文章:
国产综合久久一区二区三区