2

我做了这段代码,当你启动它时,它应该向你显示一个图像,然后当你按下左键或右键时在其他两个图像之间更改它,但由于某种原因它没有从键盘读取输入,我试过了使用 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);
    }
}
4

1 回答 1

2

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

改变

p.addKeyListener(new KeyListener()

this.addKeyListener(new KeyListener()

为我工作。

于 2013-11-11T15:40:23.283 回答