使用JFileChooser的Java KeyBindings [英] Java KeyBindings with JFileChooser
问题描述
我想将键绑定添加到我的 JFileChooser
,以便在按下SPACE键时打开文件预览窗口。
I would like to add Key bindings to my JFileChooser
in order to open a file preview window when the SPACE key is pressed.
由于源代码太大,我只做了一个简单的脏代码:
Because of the source code is too big, I just did a simple dirty code :
MainWindow.java
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainWindow extends JFrame {
public MainWindow() {
this.setTitle("Test Window");
Dimension dim = new Dimension(800, 600);
this.setSize(dim);
this.setPreferredSize(dim);
MainPanel pane = new MainPanel(dim);
Action damned = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"It Works !");
}
};
pane.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "damned");
pane.getActionMap().put("damned", damned);
this.setContentPane(pane);
this.setVisible(true);
}
}
MainPanel.java
package test;
import java.awt.*;
import javax.swing.*;
public class MainPanel extends JFileChooser {
public MainPanel(Dimension dim) {
this.setSize(dim);
this.setPreferredSize(dim);
}
}
Test.java
package test;
public class Test {
public static void main(String[] args) {
new MainWindow();
}
}
如果我使用的是JPanel而不是JFileChooser,那么工作。
If I use a JPanel instead of a JFileChooser, it works.
谢谢,
Revan
推荐答案
问题是InputMap的类型:默认情况下(没有参数),即WHEN_FOCUSED。由于选择器本身很少聚焦,因此无法找到绑定。而是在WHEN_ANCESTOR中绑定...
the problem is the type of InputMap: by default (that is without parameter), that's WHEN_FOCUSED. As the chooser itself is rarely focused, the binding will not be found. Instead bind in WHEN_ANCESTOR...
pane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke("F1"), "damned");
如你所见,我用F1代替SPACE:需要空间(因此被吃掉)通过文本字段输入名称
As you see here, I replaced the SPACE by F1: the space is needed (and thus eaten) by the textfield which takes the name input
这篇关于使用JFileChooser的Java KeyBindings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!