简体   繁体   English

在Java中使用KeyListener移动形状

[英]Moving Shapes With KeyListener In Java

I'm trying to write a program that allows a user to move a shape with arrow keys and change its color with the enter key. 我正在尝试编写一个程序,该程序允许用户使用箭头键移动形状并使用Enter键更改其颜色。 I wasn't taught anything about GUIs or event-based programming, so this is my first experience with any of that. 我没有学过任何有关GUI或基于事件的编程的知识,所以这是我的第一次经验。 I think I understand the basics of it, but I'm having trouble just finishing the syntax to make everything run. 我想我了解它的基础知识,但是我在完成语法以使所有内容运行时遇到麻烦。 The tutorials I find online use timers, which I'm not using. 我在网上找到的教程没有使用计时器。 Here's my current code: 这是我当前的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Lab15Panel extends JPanel
{
    Color[] colors = new Color[]{Color.blue, Color.green, Color.red, Color.orange, Color.yellow};
    int initialX = 90;
    int initialY = 80;

public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    g.setColor(colors[0]);


    g.fillRect(initialX, initialY, 100, 100);


    Lab15Key listen = new Lab15Key();

}

private class Lab15Key implements KeyListener
{
    @Override
    public void keyTyped(KeyEvent event)
    {
        if (event.getKeyChar() == KeyEvent.VK_LEFT)
        {
            initialX++;
        }
    }

    @Override
    public void keyReleased(KeyEvent event)
    {}

    @Override
    public void keyPressed(KeyEvent event)
    {}
}

} }

I make my frame in a different class. 我在不同的班级做相框。 Right now I'm unsure of two things: 1. How do I use addKeyListener with the filled shape? 现在,我不确定两件事:1.如何使用填充形状的addKeyListener? Is there a way to refer to the filled shape? 有没有办法引用填充的形状? 2. Is my idea of "moving" the shape correct? 2.我“移动”形状的想法正确吗? That is, creating variables outside of the methods for the position of the shape and then using my KeyEvents to change those numbers? 也就是说,要在形状位置的方法之外创建变量,然后使用我的KeyEvent更改这些数字? Or will the shape not be moved in this case? 还是在这种情况下不移动形状? (Note I've only written the code for the up key event.) (请注意,我只编写了向上键事件的代码。)

Any help you can give me would be appreciated. 您能给我的任何帮助将不胜感激。 I'm definitely a Java novice, and I'm just trying to understand these basic concepts but the resources I have aren't helping. 我绝对是Java的新手,我只是想了解这些基本概念,但是我所获得的资源却无济于事。

You need to add your KeyListener to your panel to actually make it listen for key presses. 您需要将KeyListener添加到面板中才能真正使它侦听按键。 This is known as registering the listener. 这称为注册侦听器。 I would put it in the constructor: 我将其放在构造函数中:

public Lab15Panel()
{
    Lab15Key listen = new Lab15Key();
    this.addKeyListener(listen);
}

Without this step, you are creating the listener, but it has nobody to tell when it hears something. 没有此步骤,您将创建侦听器,但是没有人可以告知何时听到声音。

If you just want your panel to get repainted each time the key gets pressed, then you could do something like this in your KeyListener: 如果只希望每次按键时都重新绘制面板,则可以在KeyListener中执行以下操作:

@Override
public void keyTyped(KeyEvent event)
{
    if (event.getKeyChar() == KeyEvent.VK_LEFT)
    {
        initialX++;
    }
    Lab15Panel.this.repaint(); // Calls repaint on the instance of the enclosing class
}

There are a number of issues working against you... 有许多问题对您不利...

  1. You've not registered the KeyListener with the component, so it will never receive key events 您尚未向组件注册KeyListener ,因此它将永远不会收到按键事件
  2. You don't repaint the panel when you change the state of the rectangle, remember, Swing uses a passive painting algorithm, so it only paints the UI when it thinks it needs to. 更改矩形的状态时,您无需重新绘画面板,请记住,Swing使用被动绘画算法,因此它仅在认为需要时才绘画UI。 You need to give Swing a nudge by calling repaint 您需要通过调用repaint来给Swing微调
  3. Your component isn't focusable, meaning that even if you did the other two things, you'd probably still not get it it work. 您的组件不可聚焦,这意味着即使您完成了其他两件事,您仍然可能无法使其正常工作。

KeyListener is a pain, it will only be triggered of the component it is attached to IS focusable AND HAS focus, generally, you are better off use Key Bindings KeyListener是一件很痛苦的事情,它只会在它附加到IS可聚焦且具有HAS焦点的组件上时才触发,通常,最好不要使用Key Bindings

See How to use key bindings for more details 有关更多详细信息,请参见如何使用键绑定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM