简体   繁体   English

ActionListener和KeyListener根本不起作用

[英]ActionListener and KeyListener not working at all

package Objects;

import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;



public class PowerBar extends JPanel implements ActionListener, KeyListener {

private double x;
private final double y = 420;
private double xv = 0;
private final int width, height;
private boolean left = false, right = false;
private Timer t = new Timer(5, this);

public PowerBar(JPanel j) {
    width = j.getWidth();
    height = j.getHeight();
    x = 180;

    t.start();
    this.addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);

  }

  public void move() {

  }

  public void powerbarPosition() {

  }

  @Override
  public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    Rectangle2D rect = new Rectangle2D.Double(x, y, 100, 15);
    g2.setColor(Color.DARK_GRAY);
    g2.fill(rect);
  }

  @Override
  public void actionPerformed(ActionEvent ae) {
    x += xv;
    repaint();
  }

  @Override
  public void keyPressed(KeyEvent ev) {
    if (ev.getKeyCode() == KeyEvent.VK_LEFT) {
        left = !left;
        if (left == true) {
            xv = -2;
        } else if (ev.getKeyCode() == KeyEvent.VK_RIGHT) {
            right = !right;
            if (right == true) {
                xv = 2;
            }
        }
      }
    }

    @Override
    public void keyReleased(KeyEvent ev) {

    }

    @Override
    public void keyTyped(KeyEvent ke) {

    }

    }

Im kinda new to programming and this is my very first game to program. 我对编程有点陌生,这是我第一次编程。 Im trying to get the power bar to move with the left and right key but there is no response from these keys when pressed. 我试图用左键和右键移动电源条,但是按下这些键时没有响应。 The power bar is drawn in a separate class called DrawMain which uses the paintComponent method. 电源条在一个名为DrawMain的单独类中绘制,该类使用paintComponent方法。

  1. A JPanel doesn't listen to Action , it is a container rather than a controller. JPanel不监听Action ,它是一个容器而不是控制器。 Hence, it doesn't have a addActionListener(actionListener) function. 因此,它没有addActionListener(actionListener)函数。
  2. For listening to Key event- presse, release etc, the target component must have focus. 要收听按键事件,释放,释放等,目标组件必须具有焦点。 However, you can invoke requestFocusInWindow() on target component to gain focus if you wish to. 但是,您可以根据需要在目标组件上调用requestFocusInWindow()以获取焦点。
  3. It is preferable not to implement a listener to class which doesn't listen to such listener, in your context it is ActionListener . 最好不要对不监听此类的类实现一个监听器,在您的上下文中为ActionListener Make use of inline anonymous class or declare another class implementing the ActionListener 利用内联匿名类或声明另一个实现ActionListener
  4. As @AndrewThompson and other swing gigs of stackoverflow will suggest, It is preferable using Key binding using key input map and action input map to a component which is rather higher level implementation. 正如@AndrewThompson和stackoverflow的其他一些摇摆演出所建议的那样,最好将Key绑定(使用键输入映射和动作输入映射)使用到更高级别实现的组件。 Try avoiding make use of lower level AWT implementation KeyListener as much as possible. 尽量避免使用较低级别的AWT实现KeyListener

Check the official tutorial page: 检查官方教程页面:

  1. How to use Key Bingings 如何使用按键绑定
  2. How to Write a Key Listener 如何编写密钥侦听器
  3. How to Write an Action Listener 如何编写动作监听器

1) Your ActionListener doesn't attached to JPanel and components on it, because of that it doesn't work. 1)您的ActionListener未附加到JPanel及其上的组件,因为它不起作用。

2) Don't use KeyListener instead of use Key Bindings : 2)不要使用KeyListener而不是使用Key Bindings

getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0), "doSomething1");
getActionMap().put("doSomething1", new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
         left = !left;
         if (left == true) {
             xv = -2;
         }
    }
});

getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0), "doSomething2");
getActionMap().put("doSomething2", new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
           right = !right;
            if (right == true) {
                xv = 2;
            }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM