本文介绍了使用键盘在Java中以一定角度移动圆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个应用程序,可以根据按下键盘上的哪个按钮成功地向左,向右,向上或向下移动球(椭圆).但是,我很难使球成一定角度移动.我试图通过说如果用户按住2个方向键,则球将沿对角线进入.例如,如果他们单击向左键和向上键,则我希望球向西北方向移动.如果你们中有人知道导致问题的原因,我将非常感谢您的帮助!

So I have an application that successfully moves a ball (ellipse) left, right, up, or down depending on which button of the keypad is being pressed. However, I'm having trouble getting the ball to move at an angle. I'm trying to do this by saying that if the user holds 2 direction keys, the ball will go in diagonally. For example, If they click the left key and the up key, I want the ball to move in an NorthWest direction. If any of you see what is causing the problem, I'd really appreciate the help!

引擎

Engine

class KeyClickListener implements KeyListener
        {
        public void keyPressed(KeyEvent e)
        {
            if (e.getKeyCode() == KeyEvent.VK_DOWN )
                {
                    component.moveCircle(1);
                }
            else if (e.getKeyCode() == KeyEvent.VK_UP)
                {
                    component.moveCircle(2);
                }
            else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
                {
                    component.moveCircle(3);
                }
            else if (e.getKeyCode() == KeyEvent.VK_LEFT)
                {
                    component.moveCircle(5);
                }
            //this is my attempt at telling whether or not the user was holding two keys
            else if (e.getKeyCode() == KeyEvent.VK_LEFT && e.getKeyCode() == KeyEvent.VK_UP)
                {
                    component.moveCircle(5);
                }
        }
        public void keyReleased(KeyEvent e){}
        public void keyTyped(KeyEvent e){}
    }

CircleComponent

 public void moveCircle(int w)
 {
    dir = w;
    if (dir == 1)
        {
            y+=20;
            repaint();
            if (y>=560)
                {
                    dir=2;
                }
        }
.
.
.

else if (dir == 5)
        {
            x-=10;
            y-=10;
            repaint();
            if(x<=0 )
                {
                    dir=3;
                }
        }
}

推荐答案

由于键事件将仅报告触发该事件的最后一个键,因此您的最后一个if语句将永远无法工作,因为keyCode仅会等于触发事件的最后一个键.

Because the key events will only report the last key that triggered the event, your last if statement will never work, as the keyCode will only ever equal the last key that triggered the event.

相反,您应该维护每个键的状态",并针对该状态进行处理.

Instead, you should maintain a "state" of each key and process against that state instead.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestKeyListener01 {

    public static void main(String[] args) {
        new TestKeyListener01();
    }

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

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

    public class TestPane extends JPanel {

        private boolean arrowUp = false;
        private boolean arrowDown = false;
        private boolean arrowLeft = false;
        private boolean arrowRight = false;

        public TestPane() {
            setFocusable(true);
            addKeyListener(new KeyAdapter() {

                @Override
                public void keyReleased(KeyEvent e) {
                    switch (e.getKeyCode()) {
                        case KeyEvent.VK_DOWN:
                            arrowDown = false;
                            break;
                        case KeyEvent.VK_UP:
                            arrowUp = false;
                            break;
                        case KeyEvent.VK_LEFT:
                            arrowLeft = false;
                            break;
                        case KeyEvent.VK_RIGHT:
                            arrowRight = false;
                            break;
                    }
                    repaint();
                }

                @Override
                public void keyPressed(KeyEvent e) {
                    switch (e.getKeyCode()) {
                        case KeyEvent.VK_DOWN:
                            arrowDown = true;
                            break;
                        case KeyEvent.VK_UP:
                            arrowUp = true;
                            break;
                        case KeyEvent.VK_LEFT:
                            arrowLeft = true;
                            break;
                        case KeyEvent.VK_RIGHT:
                            arrowRight = true;
                            break;
                    }
                    repaint();
                }
            });
        }

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            FontMetrics fm = g2d.getFontMetrics();
            String text = "Up";
            int x = (getWidth() - fm.stringWidth(text)) / 2;
            int y = ((getHeight() / 2) - fm.getHeight());
            draw(g2d, text, x, y, arrowUp);

            text = "Down";
            x = (getWidth() - fm.stringWidth(text)) / 2;
            y = ((getHeight() / 2) + fm.getHeight()) + fm.getAscent();
            draw(g2d, text, x, y, arrowDown);

            text = "Left";
            x = (getWidth() / 2) - fm.stringWidth(text) - 4;
            y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
            draw(g2d, text, x, y, arrowLeft);

            text = "Right";
            x = (getWidth() / 2) + 4;
            y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
            draw(g2d, text, x, y, arrowRight);

            g2d.dispose();
        }

        protected void draw(Graphics2D g2d, String text, int x, int y, boolean pressed) {
            g2d.setColor(pressed ? Color.BLACK : Color.GRAY);
            g2d.drawString(text, x, y);
        }
    }
}

我还建议您使用而是使用键绑定.他们解决困扰KeyListener

I would also recommend that instead of KeyListener, you should use Key Bindings instead. They solve annoying focus issues that plague KeyListener

这篇关于使用键盘在Java中以一定角度移动圆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 06:40