无法获得keypressed方法工作

时间:2017-06-10 02:40:47

标签: java jpanel keylistener

我只是尝试使用keypressed方法,并确保它在我继续之前工作,并使用我的程序执行更复杂的操作。目前,我只是试图让实现Keylistener的类在用户按下左箭头键时向JPanel添加图像。我已将相关代码放在下面。

public class Game implements KeyListener, ActionListener{

    private Window window;
    private JLabel enemySpaceshipLabel;
    private JPanel panel;


    public Game(){
        indexEnemySpaceship = (int)(Math.random()*7);
        try {
            enemySpaceshipLabel = new JLabel(new ImageIcon(ImageIO.read(this.getClass().getResource("spaceship (" + indexEnemySpaceship + ").png"))));
        } 
        catch (IOException e) {
            e.printStackTrace();
        } 
        window = new Window("Space Game")
        panel = window.getPanel();
        panel.addKeyListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent arg0)   
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_LEFT){
            panel.add(enemySpaceshipLabel);
            panel.repaint();
        }
    }

    @Override
    public void keyReleased(KeyEvent arg0) {        
    }

    @Override
    public void keyTyped(KeyEvent arg0) {
    }
}
public class Window extends JFrame{

    private JPanel panel;

    public Window(String title){
        SwingUtilities.isEventDispatchThread();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //this.setBackground(Color.BLACK);
        panel = new JPanel();
        this.add(panel);
        this.pack();
        this.setSize(500,500); //my edit
        panel.setBackground(Color.BLACK);
        this.setVisible(true);

    }

    public JPanel getPanel() {
        // TODO Auto-generated method stub
        return panel;
    }

}

0 个答案:

没有答案