How to implement an actionListener for space bar a

2019-07-20 19:17发布

问题:

I have this set up to update pretty constantly on the timer, but I want to be able to pause the timer with the spacebar. I have attempted to implement an actionListener, but I am not sure what to apply it to. Most of the examples I can find relate to buttons or text boxes, not keyboard presses inside a jpanel. I have printed src to the console and it doesn't appear to be registering my spacebar as an event... I have tried adding the actionListener, but I am not getting something about the syntax. Any help would be appreciated.

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);

        }
    });
}
}

Also, is there a getEvent() key code for the spacebar? Can't seem to find one. Thanks

回答1:

You should use the 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();
         }
     }
 });

The InputMap/ActionMap can be applied to any component that extends from JComponent, but in your case, I'd suggest attaching it to your PaintPane