0

Within my Java application I have a JFrame with some buttons and a COM component that has keyboard shortcuts. I need the buttons to perform these shortcuts when the User click them.

For example: The print button should be clicked to perform Ctrl + P.

How can I implement this?

Thanks.

linuxunil
  • 313
  • 2
  • 14

2 Answers2

2

The print button should be clicked to perform Ctrl + P

Hitting Ctrl + P triggers an Action (at least, I suppose you are using Key Bindings). Just couple that Action to the JButton as well.

You shouldn't try to let the button perform a Ctrl + P. Share the Action, which can be seen as the model behind the JButton and the key binding

Robin
  • 36,233
  • 5
  • 47
  • 99
2

You can use Action and KeyBindings. Check out this example:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class TestKeyBinding {

    private JFrame frame;

    public final class PrintAction extends AbstractAction {

        public PrintAction() {
            super("Print");
        }

        @Override
        public final void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(frame, "Perform some printing");
        }
    }

    protected void initUI() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        PrintAction printAction = new PrintAction();
        JButton button = new JButton("Print");
        button.registerKeyboardAction(printAction, KeyStroke.getKeyStroke(KeyEvent.VK_P, KeyEvent.CTRL_DOWN_MASK),
                JComponent.WHEN_IN_FOCUSED_WINDOW);
        button.setAction(printAction);
        JComponent comp = new JComponent() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(100, 100);
            }
        };
        frame.add(comp, BorderLayout.NORTH);
        frame.add(button);
        frame.setSize(300, 300);
        frame.setVisible(true);
        comp.requestFocusInWindow();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestKeyBinding().initUI();
            }
        });
    }
}
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • @linuxunil: Also consider `getMenuShortcutKeyMask()`, seen [here](http://stackoverflow.com/a/5129757/230513), for improved cross-plaform experience. – trashgod Mar 22 '13 at 00:53