actionPerformed不起作用

时间:2016-07-14 14:53:11

标签: java action

actionPerformed不起作用,但是KeyListener正在工作,当我按下按钮时我得到了输出。我不明白为什么void actionPerformed不起作用。它曾经为我工作过一次。 ################################################## ############################

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

public class Window implements ActionListener, KeyListener{

public static Window window;
public static DrawWindow drawWindow;

public Point player;
public Point wall;

public boolean isMovingUp = false, isMovingDown = false, isMovingLeft = false, isMovingRight = false;

public static void main(String[] args) {
    window = new Window();
}

public Window() {
    JFrame frame = new JFrame();
    frame.setSize(500, 500);
    frame.setTitle("Test");
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.add(drawWindow = new DrawWindow());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.addKeyListener(this);

    game();
}
public void game() {
    player = new Point(0,0);
    System.out.println("player is created");  //working

}


@Override
public void actionPerformed(ActionEvent arg0) {

    drawWindow.repaint();

    if(isMovingUp == true) {
        player.y += 1;
        System.out.println("Moving");   //Not working
    }
}

@Override
public void keyPressed(KeyEvent g) {
    int key = g.getKeyCode();
    if(key == KeyEvent.VK_UP) {
        isMovingUp = true;
        System.out.println("arrow up is pressed, isMovingUp = true");  //Working

    }
}

@Override
public void keyReleased(KeyEvent g) {

}

@Override
public void keyTyped(KeyEvent arg0) {

}

}

1 个答案:

答案 0 :(得分:2)

您忘了将您的组件(例如<a href="#"> <b>get a free quote </b></a>)设置为动作侦听器,通过以下习语:

this

有关详细信息,请参阅documentation