I'm trying to make it so that when the user presses the Enter key the JButton which is associated with that key gets triggered.
Here's what my code looks like:
import java.awt.event.KeyEvent;
private void formKeyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode()==KeyEvent.VK_ENTER) {
jButton2.setEnabled(true);
}
}
How to trigger a JButton with a key press?
Add an ActionListener to the button. It will fire an event when the button is in focus and the user presses the enter key. See How to Write an Action Listener for more info.
Edit
See also further details in Rob Camick's Enter Key and Button.
ActionListener itself won't be sufficient. You will have to write a KeyListener to get this thing down. A KeyListener which captures Enter button press would look like this.
this.button.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
System.out.println("Hello");
JOptionPane.showMessageDialog(null, "Enter key pressed !");
}
}
});
Related
The title might be a little misleading, didnt know how to put my problem short.
Basically what im doing is im using keyboardlistener to find out which keys are down and according to that im moving my game character.
The problem is, when you click out of the window, while holding down a key my listener doesnt register the keyReleased event.
I tried to fix it by using mouse listener and the mouseExited event, but that doesnt fix it all the time, sometimes it does sometimes it doesnt.
Heres my implementation:
Keyboard:
public void mouseLeftWindow()
{
for(int i =0;i<KEY_COUNT;i++)
{
keys[i] = false;
}
}
#Override
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
if(keyCode>=0 && keyCode<KEY_COUNT)
{
keys[keyCode] = true;
}
}
#Override
public void keyReleased(KeyEvent e)
{
int keyCode = e.getKeyCode();
if(keyCode>=0 && keyCode<KEY_COUNT)
{
keys[keyCode] = false;
}
}
where keys[] is a boolean[] describing, which codes are pressed
mouse:
#Override
public void mouseExited(MouseEvent e)
{
mouseMoved(e);
keyboard.mouseLeftWindow();
}
Your program will listen for further key events even when your mouse exited the component. That means you set everything to false on exit but if a key is still pressed it will be set to true immediately again. I think you are looking for a FocusListener instead of a MouseListener.
addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
keyboard.mouseLeftWindow();
}
});
I have made my own version of Tetris in Java and i have added the possibility of moving the shapes both with JButtons and with certain keyboard keys. The code snippet i used is the following:
leftButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent E) {
moveLeft();
}
});
rightButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent E) {
moveRight();
}
});
rotateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent E) {
rotateMovingShape();
}
});
myPanel.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent event) {
int keyCode = event.getKeyCode();
if (keyCode == event.VK_A)
{
moveLeft();
}
if (keyCode == event.VK_D)
{
moveRight();
}
if (keyCode == event.VK_S)
{
rotateMovingShape();
}
}
});
The problem i have is that after i use the JButtons, i cannot longer control the shapes with the keyboard keys. I suspect it has something to do with gaining/losing focus, but i am not sure. Could anyone tell me what's going on?
You get that problem, because you use KeyListener, instead of that you need to use Key Bindings. For example:
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A,0), "aPressed");
component.getActionMap().put("aPressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("a key");
}
});
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_D,0), "dPressed");
component.getActionMap().put("dPressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("d key");
}
});
// other bindings
where component is your JPanel.
A KeyListener only receives key events when the component has the keyboard focus. Clicking on the buttons transfers the focus to them and away from your panel, so you don't get the events. Any one of the following approaches will solve this:
Call setFocusable(false); on the buttons so that they won't steal the focus.
Add the KeyListener to the buttons too.
Use key bindings instead of a KeyListener, so that you can catch the key press whether the component has focus or not.
As i have seen many answers are too obscure for a entry level student like me.
i am following the steps by first addActionListner(this) to my JTextField.
what i am trying to do next and confuses the most is under:
public void actionperformed(Actionevent ae){
if(ae.getSource() == "Enter pressed")
{
outArea.setText(result);
}
}
which does not work because i feel like the code ae.getSource() == "Enter presses" is not working correctly and even i replaced the action i took under actionPerformed by a simple print line command like System.out.println("working"), it won't execute.
here is what i do if a button is pressed.
public void actionperformed(Actionevent ae){
if(ae.getSource() == "JButton")
{
System.out.println("JButton was pushed");
}
}
no matter how, lets say i have a GUI with a piece of given code like these:
public static void main(string[] args){
new myProg();
}
public myProg(){
....
buildTheGUI();
...}
}
//GUI Objects
...
JTextField input = new JTextField(10);
...
//method building the GUI
public void buildTheGUI(){
...
input.addActionListner(this);
...
//a method called actionPerformed
public void actionperformed(Actionevent ae){
}
i am now trying to detect the enter key by actionListner not by any other method because it's given.
Firstly, actionPerformed is triggerd by an action event, typically on most systems, this is triggered by the Enter key (with context to the JTextField)...so you don't need to check for it.
Secondly, the source of the ActionEvent is typically the control that triggered it, that would be the JTextField in this case.
Thirdly, String comparison in Java is done via the String#equals method...
if ("Enter presses".equals(someOtherString)) {...
Your actionPerformed method for the Button is wrong, try better this:
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JButton) {
JButton button = (JButton) e.getSource();
System.out.println("This button was pushed: " + button.getText());
}
}
And your for KeyListener try this to learn how it works:
#Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyChar());
System.out.println(e.getKeyCode());
}
Dont forget to let your class implement ActionListener and KeyListener.
I have a JButton that has action listener.
btn_.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
// DO STUFF
}
}
And I have a JSpinner that listens for key events.
spn_.addKeyListener(new KeyAdapter()
{
#Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
System.out.println("Someone pressed enter key");
}
}
});
What I would like to do, is whenever user presses enter key while the spinner is selected, I would like it to execute whatever command the button does.
Yes I understand that I can simply have a function for the actions button does, and then execute the same function when user presses enter key. I am asking this because I am curious if it is possible for components in Swing to send actions to each other and how to do it rather than what is the correct way to program.
Yes I understand that I can simply have a function for the actions button does, and then execute the same function when user presses enter key. I am asking this because I am curious if it is possible for components in Swing to send actions to each other and how to do it rather than what is the correct way to program.
If you are implying that executing a function is the correct way, I would suggest that is not the best way to solve the problem.
The correct way is to share the Action, not the method that you invoke.
You should NOT be using a KeyListener at all in this solution. The general solution is to use Key Bindings. Read the Swing tutorial on How to Use Key Bindings for more information.
However, in your case it is even a little easier because you can just share the ActionListener:
ActionListener al = new ActionListner() {...}
JTextField editor = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField();
editor.addActionListener(al);
button.addActionListener(al);
Use doClick() method of JButton:
btn_.doClick()
Within keyPressed as following:
spn_.addKeyListener(new KeyAdapter()
{
#Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
btn_.doClick()
}
}
});
The doClick() method as specified in oracle doc:
Programmatically perform a "click". This does the same thing as if the
user had pressed and released the button.
spn_.addKeyListener(new KeyAdapter()
{
#Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
btn_.doClick(); // fires the actionPerfomed on the button
}
}
});
I have a JTable that has a delete button to delete its rows.
I want to create a shortcut, for example when user selects a row and presses the 'Delete' button on keyboard , that line should be deleted.
My line is deleted with my JButton1 perfectly.
if (e.getSource() == KeyEvent.VK_DELETE) {
// Delete row Method
}
But it doesn't work.
don't to use KeyListener for this job, and in Swing never, use KeyBindings instead
add ListSelectionListener to JTable, notice to test if(table.getSelectedRow > 0)
use KeyBindings for JTable, override Delete key
I don't know what is the exact problem because you provide too few code. However, you can't use getSource() to test which key is typed (pressed, or released). Use getKeyChar() and getKeyCode().
The following is explanation of my code:
You need to add a KeyListener to a component(of course)
The component must have focus
The component must be focusable (set focusable to true)
The component need to request for focus
Override keyTyped keyPressed or keyReleased to retrieve KeyEvent
To check which key is typed in keyTyped, use getKeyChar()
To check which key is pressed or released in keyPressed and keyReleased, use getKeyCode()
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(new Dimension(410, 330));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBackground(Color.GREEN);
panel.setBounds(50, 50, 300, 200);
panel.addKeyListener(new MyKeyListener()); // add KeyListener
panel.setFocusable(true); // set focusable to true
panel.requestFocusInWindow(); // request focus
f.getContentPane().add(panel);
f.setVisible(true);
}
static class MyKeyListener extends KeyAdapter {
#Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '\177') {
// delete row method (when "delete" is typed)
System.out.println("Key \"Delete\" Typed");
}
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE) {
// delete row method (when "delete" is pressed)
System.out.println("Key \"Delete\" Pressed");
}
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE) {
// delete row method (when "delete" is released)
System.out.println("Key \"Delete\" Released");
}
}
}
}
Take a look to this page:
http://www.coderanch.com/t/341332/GUI/java/setting-keyboard-navigation-shortcut-keys
Taken from there:
Create a key listener for that button (it seems you have already made that):
Button btn = new Button("Press Me");
btn.addKeyListener(myKeyListener);
And implement the keylistener:
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_DELETE ){
//Do whatever you want
}
}
Try it and tell me if it works.