我正在尝试使用一个窗口来制作一个程序,该JFrame
窗口可以让用户从键盘输入。因此,如果用户键入一个单词,语句类应该查看该单词是否在其中,然后打印出来。
因为现在我无法让语句类与键盘类一起工作。我真的不想用这种方式来获取键盘输入,所以你们知道任何更好的方式,那就是炉排。
问题:修复语句类获取键盘输入。
这是语句类:
public class Statements {
Keyboard input;
public Statements(Keyboard input){
this.input = input;
}
public void tick() {
if(input.up){
System.out.println("inventory");
}
}
这是键盘类,如果您想使用键盘上的所有字符,这是创建按键侦听器的不好方法。但这是我知道的唯一方法。
public class Keyboard implements KeyListener {
private boolean[] keys = new boolean[200];
public boolean up, down, left, right, i;
public void update(){
up = keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W];
down = keys[KeyEvent.VK_DOWN] || keys[KeyEvent.VK_S];
left = keys[KeyEvent.VK_LEFT] || keys[KeyEvent.VK_A];
right = keys[KeyEvent.VK_RIGHT] || keys[KeyEvent.VK_D];
//all the char on the keyboard
...
...
i = keys[KeyEvent.VK_I];
}
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
public void keyTyped(KeyEvent e) {
}
}
主班
private static final long serialVersionUID = 1L;
public static final int WIDTH = 100;
public static final int HEIGHT = WIDTH / 16 * 9;
public static final int SCALE = 3;
private boolean running = false;
private Thread thread;
private JFrame frame;
private Keyboard key;
private Statments stat;
public Main() {
Dimension size = new Dimension(WIDTH * SCALE, HEIGHT * SCALE);
setPreferredSize(size);
frame = new JFrame();
key = new Keyboard();
stat = new Statments(key);
addKeyListener(key);
}
public synchronized void start() {
running = true;
thread = new Thread(this, "Display");
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
while (running) {
frame.requestFocus();
tick();
}
stop();
}
public void tick(){
key.update();
stat.tick();
}
public static void main(String args[]) {
Main main = new Main();
main.frame.setResizable(false);
main.frame.setTitle("game");
main.frame.add(main);
main.frame.pack();
main.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.frame.setLocationRelativeTo(null);
main.frame.setVisible(true);
main.start();
}
}