gpt4 book ai didi

java - ActionListener 不工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:10:20 24 4
gpt4 key购买 nike

当我按“A”时,什么都不做。我正在制作游戏,我没有看到任何错误的编写代码。

如果您有关于在 2D 简单生存游戏中放入什么的建议,请告诉。

我没有收到任何错误。

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;

import javax.swing.*;


public class Player extends JPanel implements ActionListener{
Timer time = new Timer(5, this);
double x = 0; double velX = 2;
double y = 0; double velY = 2;

public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Ellipse2D circle = new Ellipse2D.Double(x,y,40,40);
g2.fill(circle);
time.start();
}

public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_A){
System.out.println("VK_A"); // When i press 'A' don't print this
velX = 1;
x = 1;
x += velX;
x += 1;
//velY = 0;
}
}



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

最佳答案

您没有 JButtons 并且调用了 addActionListener(...) 没有结果,所以它不起作用是有道理的。解决方案:添加一个 JButton 并将 ActionListener 添加到该按钮。此外,您的问题指出 ActionListener 不起作用,但您的评论看起来是在一个已失效的 KeyListener 中。这表明您确实想要查看 Swing 教程。您可以在此处找到 Swing 教程和其他 Swing 资源的链接:Swing Info .

其他评论:

1)再

I don't get any error.

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

2)切勿从 paintComponent 方法中启动 Timer。此方法应该仅用于绘画和绘画。

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

例如:

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 的枚举以及一个将四个 Direction 枚举值绑定(bind)到一个 boolean 值的 Map。 Key Bindings 将更改 Map 中的 boolean 值,仅此而已。例如,如果按下向上箭头,则与 Direction.UP 关联的 map boolean 值将为真。释放键后,与同一 Direction.UP 键关联的 Map 值将更改为 false。 Timer 的 ActionListener 将遍历四个 Direction 枚举,检查每个枚举的 Map 值,然后如果关联的 boolean 值为真,则按照 Direction 规定的方向移动 Sprite 。好处包括能够同时响应多个按键:

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

}

关于java - ActionListener 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29827779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com