event listener (how to)

W

wee

hello,

i added an actionListener to a JButton. it works well when i click it with a mouse. if i put the focus on the button using the tab key and press the keyboard enter key, nothing happens. my question then is, how can i make theJButton react to both mouse click and the keyboard enter key? do i need toadd a keypressed listener on top of the actionListener? any help would be appreciated.

thank you.
 
M

markspace

hello,

i added an actionListener to a JButton. it works well when i click it
with a mouse. if i put the focus on the button using the tab key and
press the keyboard enter key, nothing happens. my question then is,
how can i make the JButton react to both mouse click and the keyboard
enter key? do i need to add a keypressed listener on top of the
actionListener? any help would be appreciated.


I think you want to use a key binding:

<http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html>


package test;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class EventTest {

public static void main( String[] args )
{
SwingUtilities.invokeLater( new Runnable()
{

public void run()
{
createGui();
}
} );
}

private static void createGui() {
JFrame frame = new JFrame();

JPanel panel = new JPanel();
JButton b = new JButton( "Test me!" );
b.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
System.out.println( "Action: "+ e );
}
} );
b.getInputMap().put( KeyStroke.getKeyStroke( "ENTER" ),
"Enter!!!");
Action printAction = new AbstractAction() {

public void actionPerformed( ActionEvent e )
{
System.out.println( "Print Action:" );
System.out.println( e );
}
};
b.getActionMap().put( "Enter!!!", printAction );
panel.add( b );
frame.add( panel );

frame.pack();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}

}
 
K

Knute Johnson

hello,

i added an actionListener to a JButton. it works well when i click it
with a mouse. if i put the focus on the button using the tab key and
press the keyboard enter key, nothing happens. my question then is,
how can i make the JButton react to both mouse click and the keyboard
enter key? do i need to add a keypressed listener on top of the
actionListener? any help would be appreciated.

thank you.

Look at JRootPane.setDefaultButton().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top