圈子不动?

时间:2014-03-18 11:57:03

标签: java

这段代码编译得很好但是当我按下右,上,上下键时圈子怎么不移动?

另外,为什么我需要底部的KeyPressed方法?它已经被称为? Eclipse希望我把它放在那里。

main.java(这是主要方法):

    import javax.swing.JFrame;

    public class main {

public static void main(String[] args) {
    Infout m = new Infout();
    JFrame frame = new JFrame();

    frame.setVisible(true);
    frame.setSize(300, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("Rectangle");
    m.repaint();
    frame.add(m);
}

    }

Infout.java文件:

    import javax.swing.*;

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.geom.Ellipse2D;

    public class Infout extends JPanel implements ActionListener, KeyListener{

Timer t = new Timer(5, this);
double x=0, y=0, velx=2, vely=2;

public Infout()
{
    t.start();
    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);
}


public void paintComponent(Graphics g)
{
        super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    Ellipse2D circle = new Ellipse2D.Double(x, y, 40, 40);
    g2.fill(circle);
}

public void actionPerformed(ActionEvent e)
{
    if (x < 0 || x > 260)
    {
        velx = -vely; 
    }
    if (y < 0 || y > 340)
    {
        velx = -vely;
    }

    x += velx;
    y += vely;
    repaint();
}

public void up()
{
    velx = -1.5;
    vely = 0;
}

public void down()
{
    velx = 0;
    vely = 1.5;
}

public void left()
{
    velx = -1.5;
    vely = 0;
}

public void right()
{
    velx = 1.5;
    vely = 0;
}

public void KeyPressed(KeyEvent e)
{
    int code = e.getKeyCode();
        if (code == KeyEvent.VK_UP);
            {up();}
        if (code == KeyEvent.VK_DOWN);
            {down();}
        if (code == KeyEvent.VK_LEFT);
            {left();}
        if (code == KeyEvent.VK_RIGHT);
            {right();}
}

public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyPressed(KeyEvent e) {}
    }

1 个答案:

答案 0 :(得分:0)

您的public void KeyPressed(KeyEvent e)不正确。 java区分大小写所以你应该在

中移动你的逻辑
public void keyPressed(KeyEvent e) {}

最后你必须调用repaint()。