[英]Why wont this KeyEvent work?
我正在java中制作一些東西,當F1鍵被擊中JDialog窗口到apear時。我的當前代碼:
public class Keyboard implements KeyListener {
private boolean[] keys = new boolean[120];
public boolean up, down, left, right, assets;
public void tick() {
assets = keys[KeyEvent.VK_F1];
}
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
public void keyTyped(KeyEvent e) {
}
}
在我的主要類下,使用tick()方法:
keyboard.tick();
if(keyboard.assets) ac.run();
鍵盤變量是指鍵盤類,而ac變量是指此類:
public class AssetsChooser extends JDialog {
JFileChooser fc = new JFileChooser();
public void run() {
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
add(fc);
System.out.println("It works.");
}
}
當我運行我的游戲並點擊F1時,沒有出現JDialog窗口,控制台也沒有顯示該方法。
在Swing中經常存在與KeyListener
相關的焦點問題。 如KeyListener
教程中所述:
“要定義對特定鍵的特殊反應,請使用鍵綁定而不是鍵偵聽器。有關詳細信息,請參閱如何使用鍵綁定 。”
一個例子(只需點擊F1 ):
import java.awt.event.*;
import javax.swing.*;
public class TestF1KeyBind {
public TestF1KeyBind() {
final JFrame frame = new JFrame("Frame");
JPanel panel = new JPanel();
InputMap im = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), "openDialog");
ActionMap am = panel.getActionMap();
am.put("openDialog", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog(frame, true);
dialog.setSize(300, 300);
dialog.setTitle("Dialog");
dialog.setLocationByPlatform(true);
dialog.setVisible(true);
}
});
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TestF1KeyBind();
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.