ActionListener不起作用

时间:2015-04-23 15:20:30

标签: java swing actionlistener keylistener

当我按下A'什么都不做我正在制作游戏,而且我没有看到任何错误的书面代码。

如果你有兴趣在2D简单生存游戏中放什么,请告诉你。

我没有收到任何错误。

$TitleTarg = array(
'1'=>$row_rsTargTitles['description1'],
'2'=>$row_rsTargTitles['description2'],
'3'=>$row_rsTargTitles['description3'],
'4'=>$row_rsTargTitles['description4'],
'5'=>$row_rsTargTitles['description5],

ad nauseum to 100
);

2 个答案:

答案 0 :(得分:4)

你没有JButton并且没有调用addActionListener(...),所以它不起作用是有意义的。解决方案:添加JButton并将ActionListener添加到该按钮。此外,您的问题表明ActionListener不起作用,但您的注释看起来在一个已失效的KeyListener中。这表明你真的想看看Swing教程。您可以在此处找到Swing教程和其他Swing资源的链接:Swing Info

其他评论:

1) 重

  

我没有收到任何错误。

缺少编译错误并不意味着没有逻辑错误(正如您所发现的那样)。

2) 永远不要在paintComponent方法中启动Timer。这种方法应仅用于绘画和绘画。

3)要响应A按键,请使用键绑定。上面链接的教程将向您展示如何使用它们。

例如:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.geom.Ellipse2D;
import javax.swing.*;

// public class Player extends JPanel implements ActionListener {
public class Player extends JPanel { // !! avoid having GUI's implement listener interfaces
   private static final int TIME_DELAY = 15; // avoid magic numbers
   private static final int PREF_W = 400;
   private static final int PREF_H = PREF_W;
   Timer time = new Timer(TIME_DELAY, new TimerListener());
   double x = 0;
   double velX = 2;
   double y = 0;
   double velY = 2;

   public Player() {
      // start timer here!
      time.start();

      setKeyBindings();
   }

   private void setKeyBindings() {
      // get action and input maps
      int condition = WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition);
      ActionMap actionMap = getActionMap();

      // get keystroke
      KeyStroke aKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_A, 0);

      // bind keystroke with an action
      inputMap.put(aKeyStroke, aKeyStroke.toString());
      actionMap.put(aKeyStroke.toString(), new A_Action());
   }

   @Override
   //!! public void paintComponent(Graphics g) {
   protected void paintComponent(Graphics g) {  // should be protected not public
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      Ellipse2D circle = new Ellipse2D.Double(x, y, 40, 40);
      g2.fill(circle);
   }

   @Override //!! make bigger
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private class A_Action extends AbstractAction {
      @Override
      public void actionPerformed(ActionEvent e) {
         System.out.println("A key pressed");
         x++;
         y++;
         repaint();
      }
   }

   public void actionPerformed(ActionEvent e) {
      // x += velX;
      // y += velY;
      // x = x + velX;
      // y = y + velY;
      repaint();
   }

   private class TimerListener implements ActionListener {
      @Override
      public void actionPerformed(ActionEvent e) {
         // TODO: move x and y
         repaint();
      }
   }

   private static void createAndShowGui() {
      Player mainPanel = new Player();

      JFrame frame = new JFrame("Player");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

这是一个更完整的例子,它可以在Timer的ActionListener中完成所有移动。它使用名为Direction的枚举以及将四个方向枚举值绑定到布尔值的Map。 Key Bindings将改变Map中的布尔值,即它。例如,如果按下向上箭头,则与Direction.UP关联的Map的布尔值将为true。释放该键后,与相同Direction.UP键关联的Map值将更改为false。 Timer的ActionListener将迭代四个方向枚举,检查每个枚举的Map值,然后如果关联的布尔值为true,则按方向规定的方向移动精灵。好处包括能够同时响应多个按键:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.geom.Ellipse2D;
import java.util.EnumMap;
import java.util.Map;
import javax.swing.*;

@SuppressWarnings("serial")
public class MoveCircle extends JPanel { 
   private static final int TIME_DELAY = 15; // avoid magic numbers
   private static final int PREF_W = 600;
   private static final int PREF_H = PREF_W;
   Timer time = new Timer(TIME_DELAY, new TimerListener());

   // key presses and releases will change the boolean values held in this Map
   // When an arrow key is pressed, the direction-corresponding boolean is set true
   // and likewise when the arrow key is released the direction corresponding boolean is false
   private Map<Direction, Boolean> dirMap = new EnumMap<>(Direction.class);
   private double x = 0;
   private double velX = 2;
   private double y = 0;
   private double velY = 2;

   public MoveCircle() {
      setKeyBindings();
      time.start();      
   }

   private void setKeyBindings() {
      int condition = WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition);
      ActionMap actionMap = getActionMap();

      // iterate through all the Direction enums
      for (Direction direction : Direction.values()) {
         // set all values to false
         dirMap.put(direction, false);

         // create two key strokes, one for pressed and one for released
         int keyValue = direction.getKeyValue();
         KeyStroke pressedKey = KeyStroke.getKeyStroke(keyValue, 0, false);
         KeyStroke releasedKey = KeyStroke.getKeyStroke(keyValue, 0, true);

         // create two Actions, one for pressed, one for released
         Action pressedAction = new KeyAction(direction, true);
         Action releasedAction = new KeyAction(direction, false);

         // add keystroke to inputMap and use keystroke's toString as binding link
         inputMap.put(pressedKey, pressedKey.toString());
         inputMap.put(releasedKey, releasedKey.toString());

         // link binding links to our actions
         actionMap.put(pressedKey.toString(), pressedAction);
         actionMap.put(releasedKey.toString(), releasedAction);
      }
   }

   @Override
   protected void paintComponent(Graphics g) {  
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;

      // draw smooth circles
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      Ellipse2D circle = new Ellipse2D.Double(x, y, 40, 40);
      g2.fill(circle);
   }

   @Override 
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private class KeyAction extends AbstractAction {
      private Direction direction;
      private boolean pressed;

      public KeyAction(Direction direction, boolean pressed) {
         this.direction = direction;
         this.pressed = pressed;               
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         dirMap.put(direction, pressed); // key press simply changes the map, that's it.
      }
   }

   private class TimerListener implements ActionListener {
      @Override
      public void actionPerformed(ActionEvent e) {
         // if JPanel no longer displayed, stop the Timer
         if (!MoveCircle.this.isDisplayable()) {
            ((Timer) e.getSource()).stop();
         }
         // here's the key: iterate through the Direction enum
         for (Direction direction : Direction.values()) {
            // get corresponding boolean from dirMap
            // and if true, change location of x and y
            if (dirMap.get(direction)) {
               x += velX * direction.getDeltaX();
               y += velY * direction.getDeltaY();
            }
         }
         repaint();
      }
   }

   private static void createAndShowGui() {
      MoveCircle mainPanel = new MoveCircle();

      JFrame frame = new JFrame("Move Circle");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

enum Direction {
   UP("Up", KeyEvent.VK_UP, 0, -1),
   DOWN("Down", KeyEvent.VK_DOWN, 0, 1),
   LEFT("Left", KeyEvent.VK_LEFT, -1, 0),
   RIGHT("Right", KeyEvent.VK_RIGHT, 1, 0);

   private String text; 
   private int keyValue; // KeyEvent.VK_?
   private int deltaX; 
   private int deltaY;

   Direction(String text, int keyValue, int deltaX, int deltaY) {
      this.text = text;
      this.keyValue = keyValue;
      this.deltaX = deltaX;
      this.deltaY = deltaY;
   }

   public String getText() {
      return text;
   }

   public int getKeyValue() {
      return keyValue;
   }

   @Override
   public String toString() {
      return text;
   }

   public int getDeltaX() {
      return deltaX;
   }

   public int getDeltaY() {
      return deltaY;
   }

}

答案 1 :(得分:0)

public class Player extends JPanel implements ActionListener, KeyListener{

您还应该实现keylistener来监听按键。 ActionListener处理按钮单击。