gpt4 book ai didi

java - 关键听众由于某种原因不工作

转载 作者:行者123 更新时间:2023-11-30 09:15:25 25 4
gpt4 key购买 nike

我写了这段代码,当你启动它时,它应该向你显示一个图像,然后当你按向左或向右键时在其他两个图像之间切换,但由于某种原因它没有从键盘读取输入,我尝试使用 mouseListener 并且它起作用了,这是代码:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Implementary extends JFrame
{
private static final long serialVersionUID = 1L;
public Dimension d;
public static ImageIcon Im = new ImageIcon(Implementary.class.getResource("death.png"));
public static ImageIcon Imc = new ImageIcon(Implementary.class.getResource("right.png"));
public static ImageIcon I = new ImageIcon(Implementary.class.getResource("left.png"));
public static Image Img = Im.getImage();
public static int x = 10;
public static int y = 10;

public Implementary()
{
super("hue");
int x1 = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
int y1 = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
d = new Dimension(x1, y1 - 45);
this.setSize(d);
this.setLocationRelativeTo(null);
Panel p = new Panel();
p.addKeyListener(new KeyListener()
{
@Override
public void keyTyped(KeyEvent e)
{
keyPressed(e);
}

@Override
public void keyPressed(KeyEvent e)
{
int k = e.getKeyCode();
if (k == KeyEvent.VK_LEFT)
{
Img = I.getImage();
repaint();
System.out.println(3);
}
else
{
Img = Imc.getImage();
repaint();
System.out.println(2);
}
System.out.println(1);
}

@Override
public void keyReleased(KeyEvent e)
{
keyPressed(e);
}
});
this.add(p);
}

static class Panel extends JPanel
{
private static final long serialVersionUID = 1L;

public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.cyan);
g.drawImage(Img, x, y, null);
}
}
}

这是主类:

public class Yo
{
public static void main(String args[])
{
Implementary imp = new Implementary();
imp.setVisible(true);
}
}

最佳答案

将 KeyListener 添加到整个 JFrame 可以解决问题。由于无法选择/聚焦您的 JPanel,因此它不会接收击键。

改变

p.addKeyListener(new KeyListener()

this.addKeyListener(new KeyListener()

对我有用。

关于java - 关键听众由于某种原因不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19909958/

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