ActionListener和KeyListener根本不工作

时间:2013-12-01 08:31:53

标签: java swing jpanel keylistener paintcomponent

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

    }

    }

我对编程很新,这是我第一个编程的游戏。我试图让电源条与左右键一起移动,但按下时这些键没有响应。功率条在一个名为DrawMain的单独类中绘制,该类使用paintComponent方法。

2 个答案:

答案 0 :(得分:4)

  1. JPanel不听Action,它是一个容器而不是一个控制器。因此,它没有addActionListener(actionListener)函数。
  2. 要收听Key event-presse,release等,目标组件必须具有焦点。但是,如果您愿意,可以在目标组件上调用requestFocusInWindow()以获得焦点。
  3. 最好不要为不听这种监听器的类实现监听器,在你的上下文中它是ActionListener。使用内联匿名类或声明另一个实现ActionListener
  4. 的类
  5. 正如@AndrewThompson和stackoverflow的其他摇摆演出所暗示的那样,最好使用键绑定使用键输入映射和动作输入映射到更高级别实现的组件。尽量避免尽可能地使用较低级别的AWT实现KeyListener
  6. 查看官方教程页面:

    1. How to use Key Bingings
    2. How to Write a Key Listener
    3. How to Write an Action Listener

答案 1 :(得分:3)

1)您的ActionListener未附加到JPanel及其上的组件,因为它不起作用。

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