For a school project, I had to make a keylistener that would output whatever you typed to the screen. A JFrame would be initialized to have the focus required for the listener to work. It uses delete and shift methods to determine what to type/delete. Is there any way to make this more efficient, since I have two methods that I don't use and just take up space? Any and all help is appreciated!
import javax.swing.*;
import java.awt.event.*;
public class KeyHandler implements KeyListener {
/*
* KEY FUNCTIONS:
* k.getKeyCode() returns ascii number
* k.getKeyChar() returns char typed
*
* KEY CODES:
* [delete] 8
* [shift] 16
*/
private String output;
public KeyHandler() {
this.output = "";
}
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() != 8) {
if(k.getKeyCode() != 16) {
this.output += k.getKeyChar();
}
} else {
if(this.output.length() - 1 < 0) {
//do nothing
} else {
this.output = this.output.substring(0,this.output.length() - 1);
}
}
this.print();
}
public void keyReleased(KeyEvent k) {}
public void keyTyped(KeyEvent k) {}
public void print() {
System.out.print('\f'); //clear screen in BlueJ
System.out.println(this.output);
}
public static void main(String[] args) {
JFrame frame = new JFrame("KeyEvent Handler");
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener(new KeyHandler());
frame.setVisible(true);
}
}