如何将空格键的actionListener实现为动作事件

时间:2013-06-04 20:12:05

标签: java swing keyboard actionlistener actionevent

我已将此设置为在计时器上不断更新,但我希望能够使用空格键暂停计时器。我试图实现一个actionListener,但我不知道应该将它应用到什么。我能找到的大多数例子都与按钮或文本框有关,而不是jpanel内的键盘按下。我已经将src打印到控制台,它似乎没有将我的空格键注册为事件...我已经尝试添加actionListener,但我没有得到关于语法的东西。任何帮助将不胜感激。

public class Arena extends JFrame {

private PaintPanel paintPanel;
public Arena() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setMinimumSize(new Dimension(1000, 720));
    paintPanel = new  PaintPanel();
    getContentPane().add(paintPanel, BorderLayout.CENTER);
    paintPanel.setBackground(Color.black);
    paintPanel.setFocusable(true);
          //paintPanel.addActionListener(this);
    pack();
    paintPanel.initGame();
}



class PaintPanel extends JPanel implements ActionListener {
    private List<Gladiator> gladiators;
    private Timer timer;
    private Ai AI;
    private Load loadObject;


    public void initGame() {

        timer = new Timer(500, this);
        timer.start();
        AI = new Ai(gladiators);
        loadObject = new Load();

    }       
    @Override
    public void actionPerformed(ActionEvent e) {
    Object src = e.getSource();
    System.out.println("*************   "+src);
//      if (src == spacebar) {


//      } else if (src = timer) {


        AI.runAI();     


        try {
        Thread.sleep(100);
        System.out.println("sleeping");
        } catch (InterruptedException d) {
        System.err.println("Caught : InterruptedException" + d.getMessage());
        }


        repaint();
//      }
    }

    public PaintPanel(){
        super();
        gladiators = new ArrayList<Gladiator>();            
        String[][] gladiatorInfo = new String[100][25];
        String[] gladiatorRaw = new String[100];
        String[][] parsedInfo = new String[250][100];
        Gladiator[] gladiator = new Gladiator[20];
        int[] matchInfo = new int[3];
        int numberofcontestants = 0;

        gladiatorRaw = loadObject.getGladiators(gladiatorRaw);
        parsedInfo = loadObject.parseStats(gladiatorRaw);   
        Venue venue = new Venue();
        matchInfo = loadObject.getMatchSettings(matchInfo);
        venue.populateVenue(matchInfo);
        gladiator = createGladiators(venue);

        for (int a = 0; a < venue.contestants; a++) {
        System.out.println("Populating Gladiator "+a);
        gladiator[a].populategladiators(parsedInfo,a);          
        gladiator[a].getEquipment();                
        gladiator[a].contestantNumber = a;
        gladiators.add(gladiator[a]);
        }


    }

    public Gladiator[] createGladiators(Venue venue) {
    int[][] initialPlacement = new int[20][2];
    Gladiator[] gladiator = new Gladiator[(venue.contestants)];
    initialPlacement = loadObject.loadInitialPlacement(venue.contestants);

    for (int a = 0; a < venue.contestants; a++) {
    System.out.println("Add gladiator "+a);
    gladiator[a] = new Gladiator(initialPlacement[a][0],initialPlacement[a][1]);
    System.out.println(initialPlacement[a][0]+","+initialPlacement[a][1]);

    }   
    return gladiator;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;

        try {       
        BufferedImage background = ImageIO.read(new File("background.png"));
        g.drawImage(background,0,0,this);
        } catch (IOException e) {
            System.err.println("Caught IOException: " + e.getMessage());
        }

        for (Gladiator s : gladiators){
            s.draw(g2); 
        }
    }
}
public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            Arena gamePanel = new Arena();
            gamePanel.setVisible(true);

        }
    });
}
}

此外,空格键是否有getEvent()键代码?似乎无法找到一个。感谢

1 个答案:

答案 0 :(得分:3)

您应该使用key bindings API

 InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
 ActionMap am = getActionMap();

 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "space");
 am.put("space", new AbstractAction() {
     public void actionPerformed(ActionEvent evt) {
         if (timer.isRunning()) {
             timer.stop();
         } else {
             timer.start();
         }
     }
 });

InputMap / ActionMap可以应用于从JComponent延伸的任何组件,但在您的情况下,我建议将其附加到PaintPane