我的类在这里,它从 JPanel 扩展,我的类在这里,它从 JPanel 扩展,我的类在这里,它从 JPanel 扩展,我的类在这里,它从 JPanel 扩展
public class MyJTestPanel extends JPanel {
private JCheckBox cboxInfo;
private JLabel lblResult;
private JButton btnAgain;
public MyJTestPanel(String testName, String testContext){
setLayout(new MigLayout());
setMaximumSize(new Dimension(400, 30));
setName(testName);
cboxInfo = new JCheckBox(testContext);
add(cboxInfo, "gapright 10, height 30, width 250, cell 0 0");
lblResult = new JLabel();
lblResult = new JLabel();
lblResult.setBackground(Color.RED);
lblResult.setOpaque(true);
add(lblResult, "gapright 10, height 30, width 30, cell 1 0");
btnAgain = new JButton("Test again");
btnAgain.setVisible(false);
add(btnAgain,"height 30, width 80, cell 2 0");
}
public JCheckBox getCboxInfo() {
return cboxInfo;
}
public JLabel getLblResult() {
return lblResult;
}
public JButton getBtnAgain() {
return btnAgain;
}
}
我的点击监听器在这里
cboxSelectAll.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
boolean isChecked = ((JCheckBox) e.getItem()).isSelected();
for (int i = 0; i < getCenterPanel().getComponents().length; i++) {
((MyJTestPanel) getCenterPanel().getComponents()[i]).getCboxInfo().setSelected(isChecked);//exception is here...
}
}
});
对于这个异常有什么想法吗?
最佳答案
您正在尝试将 getCenterPanel().getComponents()[i] 的结果转换为 MyJTestPanel,并且您遇到的组件之一是 JPanel。
如果您在该循环中遇到的所有组件都是 MyJTestPanel/扩展 MyJTestPanel,则转换将起作用,但至少有一个(JPanel)不满足此条件,因此转换失败。
关于java - "AWT-EventQueue-0"类转换异常 : JPanel cannot be cast MyJTestPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36203542/