How do I move a graphic across the screen with arrow keys?

瘦欲@ 提交于 2019-12-01 10:37:11
Hovercraft Full Of Eels

Two big problems here:

public void paintComponent(Graphics g){
    super.paintComponent(g);
    ImageIcon i = new ImageIcon("C:\\Users\\Bryan\\Pictures\\ship.gif");
    i.paintIcon(this, g, 0, 0);
}
  1. You're reading from a file from within paintComponent(...). Never do this as this will slow your drawing unnecessarily. Read the image once, perhaps in a constructor, and then use the stored image variable in drawing. The paintComponent method should be for painting only, and it should be lean, mean and fast.
  2. You're drawing at 0, 0 always. If you want to move something, draw at a variable position, and then change the values held by the variable and repaint.

Also: You should use Key Bindings to accept key strokes in a Swing application as this will help solve focus issues.

For example, please have a look at my code in this answer.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!