java键盘事件,如何监听连续按两次按键?
例如dnf中连按两次行走键为奔跑。尝试过一些方法,但不是很理想,有没有大神说说思路,或现成的方法。...
例如dnf中连按两次行走键为奔跑。尝试过一些方法,但不是很理想,有没有大神说说思路,或现成的方法。
展开
1个回答
展开全部
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.*;
import javax.swing.*;
public class KeyEventDemo extends JFrame implements KeyListener, ActionListener {
JTextArea displayArea;
JTextField typingArea;
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
KeyEventDemo frame = new KeyEventDemo("KeyEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set up the content pane.
frame.addComponentsToPane();
// Display the window.
frame.pack();
frame.setVisible(true);
}
private void addComponentsToPane() {
JButton button = new JButton("Clear");
button.addActionListener(this);
typingArea = new JTextField(20);
typingArea.addKeyListener(this);
displayArea = new JTextArea();
displayArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(displayArea);
scrollPane.setPreferredSize(new Dimension(375, 125));
getContentPane().add(typingArea, BorderLayout.PAGE_START);
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(button, BorderLayout.PAGE_END);
}
public KeyEventDemo(String name) {
super(name);
}
long time = System.currentTimeMillis();
long timeInterval = 300;
/** Handle the key typed event from the text field. */
public void keyTyped(KeyEvent e) {
// displayInfo(e, "KEY TYPED: ");
}
/** Handle the key pressed event from the text field. */
public void keyPressed(KeyEvent e) {
System.out.println(System.currentTimeMillis() - time);
if (System.currentTimeMillis() - time < timeInterval)
displayArea.setText("Double clicked");
else
displayArea.setText("Single clicked");
time = System.currentTimeMillis();
// displayInfo(e, "KEY PRESSED: ");
}
/** Handle the key released event from the text field. */
public void keyReleased(KeyEvent e) {
// displayInfo(e, "KEY RELEASED: ");
}
/** Handle the button click. */
public void actionPerformed(ActionEvent e) {
// Clear the text components.
displayArea.setText("");
typingArea.setText("");
// Return the focus to the typing area.
typingArea.requestFocusInWindow();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询