【发布时间】:2016-04-16 17:11:48
【问题描述】:
我编写了一个程序,我试图在箭头键的帮助下向下移动一个矩形。但它不动。这是我的代码。谁能帮我看看它为什么不动?我还在按键按下事件中添加了一个 System.out.print(),但它没有在控制台上显示任何输出。看来 keyevent 部分不起作用。
`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");
}
}`
【问题讨论】:
标签: java animation keylistener