gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:02:31 25 4
gpt4 key购买 nike

我使用 Gridlayout 在一行中放置 4 个元素。首先,我有一个 JPanel,一切正常。对于行数变大并且我必须能够向下滚动的情况,我对其进行了一些更改。现在我的 JPanel 上添加了一个 JScrollPane。我使用了相同的代码,现在我只是将元素添加到 Jscrollpane 的视口(viewport)中,但是现在我得到了这个异常 Get java.lang.ClassCastException: layout of JScrollPane must be a ScrollPaneLayout:在 javax.swing.JScrollPane.setLayout(Unknown Source) 我不知道为什么。为什么 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, 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)); //Line which causes the error

您不能更改滚动 Pane 的布局管理器。

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 );

关于Java:无法将 Gridlayout 应用于 Jscrollpane。获取 获取 java.lang.ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19756784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com