0

Program not close but when i click my checkbox i get an exception like this; enter image description here

my class is here and it is extends from JPanel,my class is here and it is extends from JPanel,my class is here and it is extends from JPanel,my class is here and it is extends from 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;
}

}

and my clicklistener is here

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

Is there any idea for this exception?

enes
  • 95
  • 2
  • 9
  • Is `MyJTestPanel` a subclass of `JPanel`? Are you sure, that `getCenterPanel().getComponents()[i]` is a `MyJTestPanel` instance? – Meiko Rachimow Mar 24 '16 at 15:16
  • Do not post a picture of a stack trace. Copy the text of the stack trace, indent every line by four spaces, and paste it into your question. – VGR Mar 24 '16 at 15:17

1 Answers1

1

You are trying to cast the result of getCenterPanel().getComponents()[i] to a MyJTestPanel, and one of the Components you encounter is a JPanel.

If all the Components you encounter in that loop are a MyJTestPanel / extend MyJTestPanel then the cast would work, but at least one, the JPanel, does not meet this criteria and so the cast fails.

Paul MacGuiheen
  • 628
  • 5
  • 17
  • updated my code, yes my class extended JPanel. is there a problem about my editor(intellij)? – enes Mar 24 '16 at 15:27
  • there is another component in my centerPanel so i got this error. Thank you @Meiko for suggest. here is correct my code if (getCenterPanel().getComponents()[i] instanceof MyJTestPanel) – enes Mar 24 '16 at 15:34