我的 Java 代码中的 repaint()
方法有问题 . 我想在另一个 class
中调用它,但我可以't, something doesn' t工作 . 我在论坛上搜索过,但没有任何东西可以帮助我 .
我的 Main class
:
public class Main {
public static Main main;
public static JFrame f;
public Main(){
}
public static void main(String[] args) {
main = new Main();
f = new JFrame();
Ball b = new Ball();
f.getContentPane().setBackground(Color.GRAY);
f.add(b);
f.setSize(500, 500);
f.setLocationRelativeTo(null);
f.setTitle("Test");
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.addMouseMotionListener(b);
f.addKeyListener(new Key());
}
}
Ball class
我为移动形状创建了2DGraphics:
public class Ball extends JLabel implements MouseMotionListener{
public Ball(){
}
public static double x = 10;
public static double y = 10;
public static double width = 40;
public static double height = 40;
String nick;
boolean isEllipse = true;
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if(isEllipse){
Ellipse2D e2d = new Ellipse2D.Double(x, y, width, height);
g2d.setColor(Color.RED);
g2d.fill(e2d);
}
else{
Rectangle2D r2d = new Rectangle2D.Double(x, y, width, height);
g2d.setColor(Color.GREEN);
g2d.fill(r2d);
}
}
@Override
public void mouseDragged(MouseEvent e) {
isEllipse = false;
x = e.getX() - 30;
y = e.getY() - 40;
this.repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
x = e.getX() - 30;
y = e.getY() - 40;
isEllipse = true;
this.repaint();
}
}
并且 Key class
我把 KeyListener
用于按键移动形状:
public class Key extends Ball implements KeyListener {
public Key() {
}
@SuppressWarnings("static-access")
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W){
super.x += 10;
super.repaint();
System.out.println("x: " + super.x);
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
但是这段代码有问题: super 方法不适用于 Key class
. Ball class
中的所有内容都运行良好 . 问题出在哪儿?
1 回答
超级工作正常,但你对它的作用的解释是错误的 . 你的问题是你通过继承解决了问题 . 你需要在实际可视化和使用的Ball实例上调用
repaint()
,而不是在一个完全不同的类Key的实例上调用,它不适当地从Ball扩展 . 首先,使Key not 延伸Ball,将一个真正的Ball引用传递给Key,解决方案将从中掉落 .也许做这样的事情:
和
注意,我自己,我会使用Key Bindings,而不是KeyListener,因为那时我不需要键盘焦点 .
例如: