简体   繁体   中英

Java exception: java.lang.ClassCastException: javax.swing.Timer cannot be cast to javax.swing.JButton

I dont really understand this run time error:

java.lang.ClassCastException: javax.swing.Timer cannot be cast to javax.swing.JButton.

Here is my code:

timer = new Timer(DELAY, new ButtonListener());

private JButton[] buttons = new JButton[3];
buttons[0] = new JButton("Circle");
buttons[1] = new JButton("Start");
buttons[2] = new JButton("Stop");

for(JButton button : buttons){
  button.addActionListener(new ButtonListener());
  controlPanel.add(button);
}

public void actionPerformed(ActionEvent e){
 JButton button = (JButton) e.getSource();

 if(button.getText().equals("Start")){
    timer.start();
 }else 
  if(button.getText().equals("Stop")){
    timer.stop();
 }else
  if(button.getText().equals("Circle")){
    shapes[count] = new Circle();
    drawPanel.repaint();
    count++;
 }
}

Your problem in next line JButton button = (JButton) e.getSource(); in actionPerformed() method. Because you add ButtonListener to JButton and to Timer . You can use different listeners for them, or you can validate type of e.getSource(); in actionPerformed()

Swing Timers can also fire action events. You just need to do a class check in the code :

public void actionPerformed(ActionEvent e){


    if (e.getSource() instanceof (JButton)) {

        JButton button = (JButton) e.getSource();

        if(button.getText().equals("Start")){
            timer.start();
        }else
        if(button.getText().equals("Stop")){
            timer.stop();
        }else
        if(button.getText().equals("Circle")){
            shapes[count] = new Circle();
            drawPanel.repaint();
            count++;
        }


    }else (e.getSource() instanceof (Timer)) {
        //deal with timer
    }
}

In your actionPerformed method check if e.getSource() is an instance of JButton other wise don't process is

public void actionPerformed(ActionEvent e){
     if(e.getSource() instanceof JButton){
          // your button action logic
     }
}

Don't use same listener class for both JButtons and JTimer . Create a seperate Listener for your timer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM