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中。
在此先感谢,感谢您的帮助。
相关文章:
1. javascript - vue-cli中 用proxyTable实现了跨域,用get访问没有问题,但通过 post传数据就出现了问题2. java - 微信小程序中 无缘无故的提示(图片的加载失败)3. [python2]local variable referenced before assignment问题4. python - TypeError: tryMsgcode() takes exactly 2 arguments (0 given)5. javascript - 像这种内联Js绑定方式,如何定位到js代码?6. python - 一个程序中的切片问题7. flexbox - css3[flex-shrink]属性在子项有 padding/box-sizing 属性时,是如何计算子项宽度的?8. css - 手机app中rem的基准值计算错误9. java - 哪位大神做过考勤打卡定位功能?请大神指点10. module - python模块from import语句相对导入,加不加点号有什么区别?

网公网安备