Java异常: java. lang.ClassCastException : javax. swing.Timer无法转换为javax.swing.JButton

标签 java swing classcastexception

我不太明白这个运行时错误:

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

这是我的代码:

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++;
 }
}

最佳答案

您的问题在 actionPerformed() 方法中的下一行 JButton button = (JButton) e.getSource(); 中。因为您将 ButtonListener 添加到 JButtonTimer 中。您可以为它们使用不同的监听器,也可以在 actionPerformed() 中验证 e.getSource(); 的类型

关于Java异常: java. lang.ClassCastException : javax. swing.Timer无法转换为javax.swing.JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25747473/

相关文章:

java - jax-rs客户端下载文件

Java - 更改每个类的 JTable 渲染器

java - 在 JPanel 中创建 JTable 并添加行

java - Android - 使用 R.id.resource 时出现 ClassCastException

java - Applet : visually bugs out only in browser, 并从 Swing 抛出异常

以封装、多态和继承为特色的 Java 示例?

java - 灰熊/ Jersey : Request injected into ContainerRequestFilter is null

java - 是否可以调用绝对函数在 TYPE_FORWARD_ONLY 结果集中向前移动行?

java - 类的组合

java - Java中从Object类型转换为Integer类型时出现ClassCastException