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:
- How to Use Actions
- 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.