Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用KeyListener移动矩形_Java_Swing_User Interface_Graphics_Keylistener - Fatal编程技术网

Java 使用KeyListener移动矩形

Java 使用KeyListener移动矩形,java,swing,user-interface,graphics,keylistener,Java,Swing,User Interface,Graphics,Keylistener,我正在尝试使用KeyListener移动一个矩形。我见过其他人使用相同的代码,但由于某种原因,我无法让它移动。现在,矩形确实出现了。我不确定我是否忘记了什么,如果我遗漏了什么。 这是我的密码: import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.awt.Graphics; public class roomwars extends JPanel implements ActionListene

我正在尝试使用KeyListener移动一个矩形。我见过其他人使用相同的代码,但由于某种原因,我无法让它移动。现在,矩形确实出现了。我不确定我是否忘记了什么,如果我遗漏了什么。 这是我的密码:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Graphics;
public class roomwars extends JPanel implements ActionListener, KeyListener {
    //public JPanel pane;
    public JFrame frame;
    public JButton start, help;
    public JTextField box;
    int x=0, y=0, velx =0, vely =0;
    Timer t = new Timer(5, this);
    public void run(){
        frame = new JFrame("ROOM WARS!");
        frame.setSize(700, 700);
        frame.setVisible(true);
        frame.add(this);
    }
    public void second (){
        t.start();
        addKeyListener(this);
        //setFocusalbe(true);
        //SETFocusTraversalKeyEnabled(false);
    }
    public void paintComponent(Graphics g) {
        Color mypurple = new Color(34, 0, 56);
        g.setColor(mypurple);
        g.fillRect(x, y, 30, 30);
        //g.setColor(Color.PINK);
        //g.fillRect(655,632,30,30);
    }

    public void actionPerformed(ActionEvent e){
        repaint();
        x+= velx;
        y+= vely;
    }

     public void keyPressed(KeyEvent e){
        int code = e.getKeyCode();
        if (code == KeyEvent.VK_UP){
            vely = -1;
            velx = 0;
        }
        else if (code == KeyEvent.VK_DOWN) {
            vely = 1;
            velx = 0;
        }
        else if (code == KeyEvent.VK_RIGHT) {
            velx = -1;
            vely = 0;
        }
        else if (code == KeyEvent.VK_LEFT) {
            velx = 1;
            vely = 0;
        }
    }
    public void keyTyped(KeyEvent e){}
    public void keyReleased(KeyEvent e) {}

    public static void main(String[] args) {
        new roomwars().run();
    }

}

请注意,在您的代码段中,未调用
second()
,因此未注册密钥侦听器。您的面板还需要可调焦,以便接收按键事件。您可能还想在方法中首先调用
super.paintComponent()

详情请参见此处:


除了不尊重油漆链(并调用
super.paintComponent
),您的主要问题是
KeyListener
的使用

短时间的搜索会很快告诉您,
KeyListener
因不响应而臭名昭著,因为它通常不可靠

最常见的解决方案是使用

下面是在当前代码库中实现键绑定的简单示例

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) throws IOException, InterruptedException {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new RoomWars());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class RoomWars extends JPanel implements ActionListener {
        //public JPanel pane;

        int x = 0, y = 0, velx = 0, vely = 0;
        Timer t = new Timer(5, this);

        public RoomWars() {
            t.start();

            InputMap im = getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "up.pressed");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "up.released");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "down.pressed");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "down.released");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "left.pressed");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true), "left.released");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "right.pressed");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), "right.released");

            am.put("up.pressed", new MoveAction(-1, 0));
            am.put("up.released", new MoveAction(0, 0));
            am.put("down.pressed", new MoveAction(1, 0));
            am.put("down.released", new MoveAction(0, 0));
            am.put("left.pressed", new MoveAction(0, -1));
            am.put("left.released", new MoveAction(0, 0));
            am.put("right.pressed", new MoveAction(0, 1));
            am.put("right.released", new MoveAction(0, 0));
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Color mypurple = new Color(34, 0, 56);
            g.setColor(mypurple);
            g.fillRect(x, y, 30, 30);
            //g.setColor(Color.PINK);
            //g.fillRect(655,632,30,30);
        }

        public class MoveAction extends AbstractAction {
            private int yDelta;
            private int xDelta;

            public MoveAction(int yDelta, int xDelta) {
                this.yDelta = yDelta;
                this.xDelta = xDelta;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                vely = yDelta;
                velx = xDelta;
            }
        }

        public void actionPerformed(ActionEvent e) {
            repaint();
            x += velx;
            y += vely;
        }

    }
}

“我见过其他人使用相同的代码”-然后是时候看看OP在Swing
计时器中调用
重新绘制
的其他地方了-因此从
键侦听器调用
重新绘制
是没有意义的-问题首先在于
KetListener
<代码>定时器t=新定时器(5,此)
正在注册
ActionListener
-总而言之,这是一个毫无意义的答案(抱歉,但它是)计时器未启动(第二个未调用)。祝贺您-您发现了“问题”-但它不会提供解决方案如果我听起来像narci,但是我非常不喜欢KeyListener谢谢你的帮助,但是我的老师希望我们使用KeyListener,相信我,我宁愿使用KeyListenerbindings@christianaceesay然后,您将不断遇到问题-KeyListener根本不可靠