我正在尝试理解Java事件但我遇到了关键事件的问题。在我的代码中,关键事件不起作用。当我创建这一行add(button);
时,会出现问题(我想是这样)。我该怎么办?
代码:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class KeyTest extends JFrame implements KeyListener {
static JButton button;
private int counter = 0;
private String userInput = "";
private final String secret = "secret";
public KeyTest() {
super("KeyListener Test");
addKeyListener(this);
ActionListener lol = new Akcja();
button = new JButton("tura");
button.addActionListener(lol);
add(button);
pack();
Dimension dimension = new Dimension(400, 400);
setPreferredSize(dimension);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void keyPressed(KeyEvent evt) {
}
@Override
public void keyReleased(KeyEvent evt) {
char c = evt.getKeyChar();
if(counter < secret.length())
checkSecret(c);
}
@Override
public void keyTyped(KeyEvent evt) {
}
private void checkSecret(char c) {
if(c == secret.charAt(counter)) {
counter++;
userInput = userInput+c;
}
else {
counter = 0;
userInput = userInput+c;
}
setTitle(userInput);
}
static class Akcja implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e) {
//to-do
}
}
}