我制作了一个简单的形状程序,它在 JPanel
中为球制作动画。我的公共(public)类形状标记错误,指出形状不是抽象的(请参见下面的屏幕截图)
Shape is not abstract and does not override abstract method
actionPerformed(ActionEvent)
inActionListener
形状.java:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javafx.event.ActionEvent;
import javax.swing.*;
public class Shape extends JPanel implements ActionListener {
Timer t = new Timer(5, this);
double x = 0;
double y = 0;
double velX = 2;
double velY = 2;
public void painComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Ellipse2D circle = new Ellipse2D.Double(x, y, 40, 40);
g2.fill(circle);
t.start();
}
public void actionPerformed(ActionEvent e) {
if (x < 0 || x > 560) {
velX = -velX;
}
if(y < 0 || y > 360) {
velY = -velY;
}
x += velX;
y += velY;
repaint();
}
}
主要.java:
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
Shape s = new Shape();
JFrame f = new JFrame();
f.add(s);
f.setVisible(true);
f.setSize(600,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Moving Ball");
}
}
最佳答案
取而代之的是:
import javafx.event.ActionEvent;
你可能想要这个:
import java.awt.event.ActionEvent;
在 paintComponent()
和 actionPerformed()
的实现中,使用 @Override
,它“通知编译器该元素旨在覆盖父类(super class)中声明的元素。”然后,编译器可以帮助您识别拼写和类型错误。
public class Shape extends JPanel implements ActionListener {
…
@Override
public void paintComponent(Graphics g) {…}
@Override
public void actionPerformed(ActionEvent e) {…}
}
您可以覆盖 getPreferredSize()
以反射(reflect)您选择的几何形状。此外,请考虑重构数字常量。
@Override
public Dimension getPreferredSize() {
return new Dimension(560, 360);
}
关于java - Animate ball JPanel subclass is not abstract错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42568656/