Java KeyBindings with JFileChooser
Asked Answered
B

2

2

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

Badmouth answered 23/11, 2011 at 10:9 Comment(0)
U
2

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

Unreality answered 23/11, 2011 at 11:16 Comment(1)
What if you wanted to replace the SPACE key anyway? How could you do that?Bowden
T
1

Try to override method

protected JDialog createDialog(Component parent)

and add your action to the dialog obtained from

super.createDialog(...)

dialog.getContentPane();
Throckmorton answered 23/11, 2011 at 11:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.