如果按下的键是更新 GUI 的触发器,那是您需要合并 SwingTimers 的时候。如果它没有触发对您的 GUI 的更新,您可以只使用普通线程。
我认为这些文章所指的是
- 使用
KeyListener
- 使用 Swing Timer 检查在给定的时间间隔(比如每 100 毫秒)按下了哪些键
以下是如何将其合并到您的示例KeyListener
:
public class Keyer implements KeyListener{
/** Stores currently pressed keys */
HashSet<Integer> pressedKeys = new HashSet<Integer>();
public Keyer(){
//Check every 100ms if there's keys pressed
//(This is the Swing Timer they talk about)
new Timer(100, new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
String keysString = "";
if(!pressedKeys.isEmpty()){
Iterator<Integer> i = pressedKeys.iterator();
while(i.hasNext()){
keysString += i.next() + ",";
}
}
System.out.println(keysString);
}
}).start();
}
@Override
public void keyPressed(KeyEvent ovent){
//Add key to hashSet when pressed
int keyCode = ovent.getKeyCode();
pressedKeys.add(keyCode);
}
@Override
public void keyReleased(KeyEvent ovent){
//Remove key from hashset when released
int keyCode = ovent.getKeyCode();
pressedKeys.remove(keyCode);
}
@Override
public void keyTyped(KeyEvent ovent){}
}
这是一个将所有内容放在一起的示例 - 更新的标签告诉您确切按下了哪些键(通过键码)。
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class TempProject extends JPanel{
/** Label to update with currently pressed keys */
JLabel output = new JLabel();
public TempProject(){
super();
setFocusable(true);
add(output, BorderLayout.CENTER);
requestFocus();
addKeyListener(new Keyer());
}
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setContentPane(new TempProject());
frame.pack();
frame.setVisible(true);
new TempProject();
}
});
}
public class Keyer implements KeyListener{
/** Stores currently pressed keys */
HashSet<Integer> pressedKeys = new HashSet<Integer>();
public Keyer(){
//Check every 100ms if there's keys pressed
//(This is the Swing Timer they talk about)
new Timer(100, new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
String keysString = "";
if(!pressedKeys.isEmpty()){
Iterator<Integer> i = pressedKeys.iterator();
while(i.hasNext()){
keysString += i.next() + ",";
}
}
output.setText(keysString);
}
}).start();
}
@Override
public void keyPressed(KeyEvent ovent){
//Add key to hashSet when pressed
int keyCode = ovent.getKeyCode();
pressedKeys.add(keyCode);
}
@Override
public void keyReleased(KeyEvent ovent){
//Remove key from hashset when released
int keyCode = ovent.getKeyCode();
pressedKeys.remove(keyCode);
}
@Override
public void keyTyped(KeyEvent ovent){}
}
}
编辑
另外,请参阅@HovercraftFullOfEels 发布的关于KeyListener
. 根据您要完成的工作,您可能需要考虑使用键绑定(与本文应用的原理相同)。如果您想看一下,这里有一个关于键绑定的有用教程。