【问题标题】:Get JPanel in a JScrollPane在 JScrollPane 中获取 JPanel
【发布时间】:2015-05-26 12:33:11
【问题描述】:

我有一个 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

感谢您的帮助:)

【问题讨论】:

    标签: java swing jpanel jscrollpane jviewport


    【解决方案1】:

    JScrollPane#getViewport#getView

    你将不得不转换回你的组件类型

    更好的解决方案是在数组或List 中维护JLabels 的列表

    【讨论】:

      猜你喜欢
      • 2011-05-11
      • 1970-01-01
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      相关资源
      最近更新 更多