gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:05:32 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com