Java 小例子:通过 WSAD 来移动的窗口

这是一个小例子,演示如何使用 wsad 来控制窗口的移动。这里面有一点技巧。如果简单的使用 keyPressed 或 keyTyped 直接处理按键事件的话,会出现“首次-停顿”现象。解决办法是使用 keyPressed/keyReleased 两个事件来处理,并将控制移动的代码移到另外的线程当中去。

 

import javax.swing.*; import java.awt.HeadlessException; import java.awt.Point; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; /** * 通过 WSAD 来移动的窗口 */ public class MovingWindow extends JFrame { private MovingThread thread = new MovingThread(); private MovingWindow thisWindow = this; public static void main(String[] args) { new MovingWindow().setVisible(true); } public MovingWindow() throws HeadlessException { setDefaultCloseOperation(DISPOSE_ON_CLOSE); setSize(30, 80); setResizable(false); setLocation(100, 100); // 添加键盘事件监听 addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (thread.direction == null) { thread.direction = Character.toString(e.getKeyChar()); } } @Override public void keyReleased(KeyEvent e) { thread.direction = null; } }); // 启动移动窗体的线程 thread.start(); } // 移动窗体的线程。当 direction 为 null 时,就不会移动窗体。 private class MovingThread extends Thread { public String direction = null; private int step = 3; private MovingThread() { setDaemon(true); } @Override public void run() { while (true) { if (direction != null) { if (direction.equals("w")) { moveUp(); } else if (direction.equals("s")) { moveDown(); } else if (direction.equals("a")) { moveLeft(); } else if (direction.equals("d")) { moveRight(); } } try { sleep(50); // 每秒移动 20 次 } catch (InterruptedException e) { e.printStackTrace(); } } } private void moveUp() { Point l = thisWindow.getLocation(); thisWindow.setLocation(l.x, l.y - step); } private void moveDown() { Point l = thisWindow.getLocation(); thisWindow.setLocation(l.x, l.y + step); } private void moveLeft() { Point l = thisWindow.getLocation(); thisWindow.setLocation(l.x - step, l.y); } private void moveRight() { Point l = thisWindow.getLocation(); thisWindow.setLocation(l.x + step, l.y); } } }

你可能感兴趣的:(java,thread,String,null,Class,import)