gpt4 book ai didi

java - 在 JScrollPane 中获取 JPanel

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:44:24 25 4
gpt4 key购买 nike

我有一个 JScrollPane,我在 JScrollPane 中放了一个 JPanel。 JPanel 包含数量可变的 JLabel。

这是我“新建”它的方式:

JPanel dataPanel  = new JPanel();
//then do a for loop to put a few JLabels in dataPanel
JScrollPane scrollPane = new JScrollPane(dataPanel);

我想知道如何在另一个类中获得这些 JLabel?我尝试了以下代码,但无法使用 ClassCastException。在该类中,我成功获得了 JScrollPane,我将使用 scrollPane 来表示它。

//I only put a panel in the JScrollPane, so I used 0 in the getComponent() method
JPanel panel = scrollPane.getComponent(0);
for(int i = 0; i < panel.getComponentCount(); i++){
JLabel label = (JLabel)panel.getComponent(i);
}

其实在声明处:

JPanel panel = scrollPane.getComponent(0);

抛出 ClassCastException。

java.lang.ClassCastException: javax.swing.JViewport cannot be cast to javax.swing.JPanel

感谢您的帮助:)

最佳答案

JScrollPane#getViewport#getView

你将不得不 cast out 回到你的组件类型

更好的解决方案是在数组或 List

中维护一个 JLabel 列表

关于java - 在 JScrollPane 中获取 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30458717/

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