Java keylistener没有响应任何键?
我试图为一个玩家动作脚本编写一个简单的keyevent,它将响应“w”键。我希望最终能让它做一些像移动角色的事情,但现在我只是想让它做出反应。我对java比较陌生,所以如果可以,请详细说明。另外,请注意,播放器将不会是一个文本区域,当我实际得到这项工作,我只是不想显示图像和动画还没有。我已经包括了很多评论来解释我在每一行上试图做什么。希望有帮助!以下是我目前的代码:Java keylistener没有响应任何键?,java,swing,if-statement,listener,keyevent,Java,Swing,If Statement,Listener,Keyevent,我试图为一个玩家动作脚本编写一个简单的keyevent,它将响应“w”键。我希望最终能让它做一些像移动角色的事情,但现在我只是想让它做出反应。我对java比较陌生,所以如果可以,请详细说明。另外,请注意,播放器将不会是一个文本区域,当我实际得到这项工作,我只是不想显示图像和动画还没有。我已经包括了很多评论来解释我在每一行上试图做什么。希望有帮助!以下是我目前的代码: import javax.swing.*; //importing swing for gui stuff import java
import javax.swing.*; //importing swing for gui stuff
import java.awt.*; //importing awt for gui stuff
import java.awt.event.*; //importing awt event so i can add listeners
public class game { //creates the class
static String player = "Player"; //initializes the variable for text i will put in the text area
public static void main(String args[]) { //making a function (main) to run automatically and initialize the game
JFrame f = new JFrame("Javax Swing UI"); //create frame for GUI
GridLayout l = new GridLayout(2,4);
f.setSize(300,300); //set the size of the frame in pixels x,y
JTextArea t = new JTextArea(5,10); //create a text area to act as the player for the game (until i get an image working)
t.append(player);
t.setEditable(false); //make it so you cant edit the text area
f.add(t);
f.setLayout(l);
f.setVisible(true); //load the frame and all objects inside it
}
public static void movement(JTextArea t) { //creating a method for moving my "character"
t.addKeyListener(new KeyAdapter() { //adding key listener to my text area
public void keyPressed(KeyEvent e) { //creating the method to respond to my key listener
int key = e.getKeyCode(); //getting the key the user types
if (key == KeyEvent.VK_W) { //checking if the key is "w"
System.out.println("if key == w !!! working"); //prints that the if statement is working
}
}
});
}
}
没有错误,它编译良好,运行良好,但是keylistener没有响应“w”键。我假设它与关键代码或我的逻辑语句有关。稍后我会担心格式问题,但正如我所说,我只是想让keyevent正常工作。如果有更多java经验的人能帮上忙,那就太好了!(我正在使用Java8)
编辑[已解决]:我已开始使用击键来编写@DontKnowMuchButGetting Better的答案,我遇到了以下问题:
java:9: error: ';' expected
public void actionPerformed(ActionEvent e) {
java:9: error: ';' expected
public void actionPerformed(ActionEvent e) {
^
2 errors
引发错误的代码看起来有点像这样:
public class move extends AbstractAction {
public static void main(int right, int down) {
int right = right;
int down = down;
@Override
public void actionPerformed(ActionEvent e) {
x += right * 4;
y += down * 4;
repaint();
}
}
}
编辑:
解决了上次编辑问题,对其进行了一些处理,现在我发现以下错误:
game.java:39: error: cannot find symbol
String whenfocused = WHEN_IN_FOCUSED_WINDOW;
^
symbol: variable WHEN_IN_FOCUSED_WINDOW
location: class game
game.java:40: error: cannot find symbol
InputMap inputs = InputMap(whenfocused);
^
symbol: method InputMap(String)
location: class game
game.java:41: error: cannot find symbol
ActionMap actions = ActionMap();
^
symbol: method ActionMap()
location: class game
game.java:44: error: Action is abstract; cannot be instantiated
m = new Action();
^
game.java:46: error: incompatible types: game.move cannot be converted to Action
actions.put(key.toString(), m);
^
game.java:62: error: cannot find symbol
g.repaint();
^
symbol: method repaint()
location: variable g of type Graphics
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
6 errors
这是我的新代码:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import java.applet.Applet;
public class game { //creates the class
public static final int ph = 300;
public static final int pw = 300;
public final int w = 20;
public final int h = 20;
public int x = (pw - w) / 2;
public int y = (ph - h) / 2;
public void main(String args[]) { //making a function (main) to run automatically and initialize the game
JFrame f = new JFrame("Javax Swing UI"); //create frame for GUI
f.setSize(ph, pw); //set the size of the frame in pixels x,y
f.setBackground(Color.WHITE);
f.setVisible(true); //load the frame and all objects inside it
KeyStroke left = KeyStroke.getKeyStroke(KeyEvent.VK_A, 0);
KeyStroke down = KeyStroke.getKeyStroke(KeyEvent.VK_S, 0);
KeyStroke right = KeyStroke.getKeyStroke(KeyEvent.VK_D, 0);
KeyStroke up = KeyStroke.getKeyStroke(KeyEvent.VK_W, 0);
keyAdd(up, -1, 0);
keyAdd(down, 0, 1);
keyAdd(right, 1, 0);
keyAdd(left, -1, 0);
}
public void keyAdd(KeyStroke key, int right, int down) {
String whenfocused = WHEN_IN_FOCUSED_WINDOW;
InputMap inputs = InputMap(whenfocused);
ActionMap actions = ActionMap();
move m = new move(right, down);
m = new Action();
inputs.put(key, key.toString());
actions.put(key.toString(), m);
}
private class move {
private int down;
private int right;
public move(int right, int down) {
this.right = right;
this.down = down;
}
public void actionPerformed(ActionEvent e, int down, int right, Graphics g) {
x += right * 4;
y += down * 4;
g.repaint();
}
}
protected void paintComponent(Graphics g,int x,int y,int w,int h, Color color) {
g.setColor(color);
g.fillRect(x, y, w, h);
}
}
如果你想移动一个“球员”的基础上已经按下了一个键,然后根据我的评论,你原来的帖子,使用键绑定,而不是一个键侦听器。首先,即使绑定组件没有焦点,键绑定也可以工作,这可以由传递到JComponent#getInputMap(…)
方法的条件int控制。在下面的示例中,我传入JComponent.WHEN_In_FOCUSED_WINDOW
,这意味着如果组件位于具有焦点的窗口中,绑定将响应,即使实际的键盘焦点位于该窗口持有的另一个组件上
可以在此处找到密钥绑定教程:
下面是一个演示程序,它根据用户按箭头键移动一个小的红色矩形,即我的“精灵”:
请参阅代码注释以了解有关此代码的更多信息
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
@SuppressWarnings("serial")
public class MoveSomething extends JPanel {
private static final int PANEL_WIDTH = 800;
private static final int PANEL_HEIGHT = 600;
private static final Color SPRITE_COLOR = Color.RED;
private static final int SPRITE_W = 20;
public static final int DELTA = 4;
private int spriteX = (PANEL_WIDTH - SPRITE_W) / 2;
private int spriteY = (PANEL_HEIGHT - SPRITE_W) / 2;
public MoveSomething() {
setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
setBackground(Color.WHITE);
// keystrokes that the program will respond to
// you can use the "w" key as well, simply via KeyEvent.VK_W
KeyStroke upStroke = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
KeyStroke downStroke = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
KeyStroke leftStroke = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
KeyStroke rightStroke = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
// submit the key stroke for binding along with two int parameters
// the right parameter that tells us if the key stroke should move things right (+1) or left (-1)
// and the down parameter for moving sprite down (+1) or up (-1)
submitKeyBinding(upStroke, 0, -1);
submitKeyBinding(downStroke, 0, 1);
submitKeyBinding(leftStroke, -1, 0);
submitKeyBinding(rightStroke, 1, 0);
}
private void submitKeyBinding(KeyStroke keyStroke, int right, int down) {
// set key bindings:
int condition = WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = getInputMap(condition);
ActionMap actionMap = getActionMap();
inputMap.put(keyStroke, keyStroke.toString());
actionMap.put(keyStroke.toString(), new MoveAction(right, down));
}
// action used by the bindings to do the actual movement
private class MoveAction extends AbstractAction {
private int right;
private int down;
public MoveAction(int right, int down) {
this.right = right;
this.down = down;
}
@Override
public void actionPerformed(ActionEvent e) {
spriteX += right * DELTA;
spriteY += down * DELTA;
repaint(); // redraw the GUI
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(SPRITE_COLOR);
g.fillRect(spriteX, spriteY, SPRITE_W, SPRITE_W);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
MoveSomething mainPanel = new MoveSomething();
JFrame frame = new JFrame("MoveSomething");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
我看不出你在哪里调用方法movement()
。。。是的,只是我又变成了一个白痴。当我试图调用它时,它说定义一个返回类型。我对这件事不太了解。我怎样才能修好它?您的问题并更新代码,使其反映您遇到的问题。将KeyListener添加到JTextArea是一个非常糟糕的主意。如果要响应文本组件中的文本更改,如果需要分别侦听文档更新后或文档更新前的内容,则最好使用DocumentListener或DocumentFilter。如果您必须监听文本组件中的按键,那么最好使用键绑定。1)您不应该使用所有静态方法和变量。2) 应在将构件添加到配电盘之前设置布局。我建议您首先阅读Swing教程中关于Swing基础知识的部分。演示代码将向您展示如何更好地构造代码,以便您遵循Swing约定。谢谢!我来试试这个+1并接受!祝你有美好的一天!我不得不查找其中的一些内容,将其编码出来以便理解,然后在我的actionPerformed(ActionEvent e){}
void之后遇到了一个请求分号的错误。它说应该是在“帮助?”之后。皮索内德:不确定——在你的问题中把你的最新尝试作为一个答案。让我们看看它,包括抛出错误的代码,thanks@PythonNerd:您没有扩展JPanel,您几乎在静态main方法中执行所有操作,因此这当然不起作用。这是您遇到问题的基本Java,而不是GUI编码,是时候了解一下了。不要复制和粘贴我的代码,而是使用这些想法编写您自己的代码,而是重新开始并编写干净的代码,这些代码除了启动GUI所需的代码之外,什么都不需要。