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方法。
答案 0 :(得分:4)
JPanel
不听Action
,它是一个容器而不是一个控制器。因此,它没有addActionListener(actionListener)
函数。requestFocusInWindow()
以获得焦点。ActionListener
。使用内联匿名类或声明另一个实现ActionListener
KeyListener
。 查看官方教程页面:
答案 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;
}
}
});