问题
I am running into problems trying to use KeyListener in java.
I am trying to write a program that runs until a key is pressed, and then outputs that key.
This is a stepping stone to more elaborate code, so the use of a method to print the key pressed is just being used as a kind of prototype.
Here is the code:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class keylistener implements KeyListener{
public keylistener(){
addKeyListener(this);
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
keylistener output = new keylistener();
output.print(key);
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
public void print(int key){
System.out.println(key);
}
public static void main(String[] args){
}
}
The program runs and then ends directly after.
I have never used KeyListener before, and I cannot figure out how to make the program wait for the key to be pressed.
回答1:
The KeyListener is intended to be used in GUI apps, not in console apps as KeyListener requires GUI components to run. Usually in a console app you would use a BufferedReader and InputStreamReader.
Here is a console app that demonstrates the idea of using a while loop with the BufferedReader and InputStreamReader to keep the app running waiting for input. Although there are other ways to do this. I made this very explicit so you can grasp the concept.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StackStuff {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean runs = true ;
System.out.println("Press any key to kill this app...");
while(runs){
input =br.readLine();
if (!(input==null)){
System.out.println(input);
runs=false;
}
}
System.out.println("I am dead!!");
System.exit(0);
}
回答2:
I don't think I've ever added a KeyListener to a console app, (probably because KeyListener
is part of the AWT package, which mainly has GUI components), but here is a sample GUI app to demonstrate.
Your first problem, though, is that you should have added new keylistener()
into your main
method, though that has to be added to a component itself in order to be ran.
public class GuiMain extends JFrame { // A GUI Frame
public GuiMain() {
// Add the listener
this.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
// Print out the code
System.out.println(e.getKeyCode());
}
});
// Show something
add(new JLabel("Hello World!"));
pack();
}
public static void main(String[] args) {
// Run the GUI
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
GuiMain gui = new GuiMain();
gui.setVisible(true);
}
});
}
}
来源:https://stackoverflow.com/questions/39963925/how-to-use-keylistener-properly-in-java