简体   繁体   English

尝试使用JFrame在Core Java中借助箭头键移动矩形

[英]Trying to move a rectangle with the help of arrow keys in Core Java using JFrames

I have made a program in which I am trying to move a rectangle down with the help of arrow keys. 我已经制作了一个程序,其中我试图借助箭头键向下移动矩形。 But it is not moving. 但是它并没有动。 Here is my code. 这是我的代码。 Can anyone please help me out and tell why is it not moving ? 谁能帮我一下,为什么不动呢? I have also added a System.out.print( ) in the key down event but its not showing any output on the console. 我还在按键事件中添加了System.out.print(),但在控制台上未显示任何输出。 It seems the keyevent part is not working. 似乎关键事件部分无法正常工作。

  `import java.awt.event.KeyAdapter;
   import java.awt.event.KeyEvent;
   import java.awt.event.KeyListener;

   import javax.swing.ImageIcon;
   import javax.swing.JFrame;
   import javax.swing.JLabel;

public class MovingBoxWithArrowKeys extends JFrame
{
    JLabel l ;

public MovingBoxWithArrowKeys(String title)
{
    super(title);


    l = new JLabel(new ImageIcon("download-box-icon.png"));
    //l.setLocation(10 , 10 );
    l.setBounds(10 , 10 , 400 , 400 );
    l.setVisible(true);
    l.isOptimizedDrawingEnabled();
    l.requestFocusInWindow();
    //l.requestFocus();
    l.addKeyListener(new KeyAdapter() 
    {
        public void keyPressed(KeyEvent k)
        {
            if(k.getKeyCode() == KeyEvent.VK_DOWN)
            {
                l.setLocation(l.getX(), l.getY()+1);
                repaint();
                System.out.print("Down Pressed");
            }
        }
    });



    setLayout(null);
    setSize(this.getMaximumSize());
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setResizable(false);
    setVisible(true);
    //requestFocus();

    getContentPane().add(l);
    //add(l);
}
public static void main(String args[])
{
    MovingBoxWithArrowKeys m = new MovingBoxWithArrowKeys("Moving Box With Keys");

}
}`

Your KeyListener needs to be add to the JFrame because it only works with the component that has the actual focus. 您的KeyListener必须添加到JFrame因为它仅与具有实际焦点的组件一起使用。 And thats not your JLabel its your JFrame . 那不是您的JLabel是您的JFrame
Even if you request the Focus with l.requestFocusInWindow(); 即使您使用l.requestFocusInWindow();请求Focus, l.requestFocusInWindow(); in your initialization code you will lose it to the JFrame because it is one of the components that is not capable of holding a focus 在初始化代码中,您将丢失它给JFrame因为它是无法保持焦点的组件之一

So simply change this: 因此,只需更改以下内容:

l.addKeyListener(new KeyAdapter() {...}

to this 对此

addKeyListener(new KeyAdapter() {...}

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

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