0

I'm wondering if its possible to make a button in JButton Press a key?

So for example If I have a button titled New Button, and I click it with the mouse. I want it to press my left arrow key.

Also is it possible to make it so that it keeps pressing it until I let go of the mouse? So more or less I click it and It presses my left arrow key continuously until I release the mouse then it stops?

Filburt
  • 17,626
  • 12
  • 64
  • 115
  • I believe you should be able to map the JButton to any key when clicked. Not sure about the holding down part, but sounds doable if you're able to detect that the button is being held down. – DigitalNinja Mar 19 '15 at 21:26
  • possible duplicate of [How to simulate keyboard presses in java?](http://stackoverflow.com/questions/7745959/how-to-simulate-keyboard-presses-in-java) – FINDarkside Mar 19 '15 at 21:30

2 Answers2

3

I click it and It presses my left arrow key continuously until I release the mouse then it stops?

What is the point of this?

If you use the keyboard to press the left arrow, the KeyStroke is dispatched to the component that has focus. So if focus is on a text field, the left arrow will move the caret back one character.

If you click on a button, focus is now on the button and if you dispatch the left arrow to the button nothing will happen.

Maybe you are trying to use the left arrow key to do some kind of animation. If so, then you need to create an Action. Then you need to add code so that a button click or the pressing of the left arrow key can invoke this Action.

For the basic concepts of this approach you can read the Swing Tutorial. There are sections on:

  1. How to Use Actions
  2. How to Use Key Bindings

For a working example of this approach you can check out Motion Using the Keyboard. The MotionWithKeyBindings.java code does animation using the keyboard or the button.

Are you trying to do something like this? Here is a simple "Calculator" keyboard:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class CalculatorPanel extends JPanel
{
    private JTextField display;

    public CalculatorPanel()
    {
        Action numberAction = new AbstractAction()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
//              display.setCaretPosition( display.getDocument().getLength() );
                display.replaceSelection(e.getActionCommand());
            }
        };

        setLayout( new BorderLayout() );

        display = new JTextField();
        display.setEditable( false );
        display.setHorizontalAlignment(JTextField.RIGHT);
        add(display, BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout( new GridLayout(0, 5) );
        add(buttonPanel, BorderLayout.CENTER);

        for (int i = 0; i < 10; i++)
        {
            String text = String.valueOf(i);
            JButton button = new JButton( text );
            button.addActionListener( numberAction );
            button.setBorder( new LineBorder(Color.BLACK) );
            button.setPreferredSize( new Dimension(50, 50) );
            buttonPanel.add( button );

            InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            inputMap.put(KeyStroke.getKeyStroke(text), text);
            inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
            button.getActionMap().put(text, numberAction);
        }
    }

    private static void createAndShowUI()
    {
//      UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );

        JFrame frame = new JFrame("Calculator Panel");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( new CalculatorPanel() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

You click a button and the value is displayed in a text field.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Is there a way to keep the focus on whatever im doing even after I press the button? – Chris Elate Mar 19 '15 at 21:47
  • You still haven't answer my question, why are you doing this? I gave you a suggestion what I think you are doing. If we don't know the details we can't give a specific answer. – camickr Mar 19 '15 at 21:53
  • The purpose of this is so that I can use the buttons to move my screen on either a game or an app. Basically im using a touch screen computer and when im laying in bed I hate having my keyboard. So Im trying to make the buttons move the screen for me. – Chris Elate Mar 19 '15 at 21:55
  • And I gave you the proper solution for invoking an Action by either using the keyboard or a button. I posted a second example. You can either type "1" or click the "1" button. – camickr Mar 19 '15 at 21:58
  • @ChrisElate If you use the key bindings properly, it won't make any difference if you use the button or the key board, in fact, you can reduce your code logic as both the button and key binding can share the same the `Action`. +1 to the answer – MadProgrammer Mar 19 '15 at 23:11
0

Do this with the java.awt.Robot class. Do this like so:

//Creating a new robot:
Robot r = new Robot();

//Pressing a key (Put inside click handler method):
r.keyPress(KeyEvent.VK_LEFT /*VK_RIGHT, VK_TOP, and VK_BOTTOM are also acceptable.*/

//Releasing a key (Put inside release handler method):
r.keyRelease(KeyEvent.VK_LEFT /*VK_RIGHT, VK_TOP, and VK_BOTTOM are also acceptable.*/); //Release key

When doing this, you may want to hold the value of the key being pressed. Do this by defining a global variable with the KeyEvent.VK_* value, like so:

//In global space
public static /*Can be private, or protected.*/ int keyPressed = null;

//In click  handler body:
keyPressed = KeyEvent.VK_LEFT /*VK_RIGHT, VK_TOP, and VK_BOTTOM are also acceptable.*/; //Set this to the value of the key you are pressing.

//In mouse release handler body:
r.keyRelease(keyPressed);
DripDrop
  • 994
  • 1
  • 9
  • 18
  • By usng int keyPressed = null; Does that make it continuous? Or do I need to change null to something? – Chris Elate Mar 19 '15 at 21:44
  • No, that just stores the key. The part that holds the key is the fact that you need to release the button for the program to stop holding the key. – DripDrop Mar 19 '15 at 21:47
  • Thanks :) Is there a way to maintain focus on the program Im using? Like Say I want to use this button to type the letter a on something. When I click the button the focus will shift to the button is there a way to keep the focus on the text instead of the button. – Chris Elate Mar 19 '15 at 21:52
  • Hmmm... there is no way that would be easy, but you can use the robot's mouseMove method to move to the text input, and then immediately move back to the button after clicking. Seach up the robot class for further information. – DripDrop Mar 19 '15 at 22:02
  • One has to stop and ask the question why? Simply have the button call the same logic which the keyboard is using...seems like overkill to me and it still requires the component which is interested (which is unlikely to be the button) to be focused first – MadProgrammer Mar 19 '15 at 23:12
  • If you need to use that functionality within the same program, you can use swing methods. My suggestion was for an external program. – DripDrop Mar 19 '15 at 23:24