问题
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();
}
}
If I use a JPanel instead of a JFileChooser, it works.
Thank you,
Revan
回答1:
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");
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
回答2:
Try to override method
protected JDialog createDialog(Component parent)
and add your action to the dialog obtained from
super.createDialog(...)
dialog.getContentPane();
来源:https://stackoverflow.com/questions/8240355/java-keybindings-with-jfilechooser