Re: Actionlistener for a full window? Nudge in the right direction would be appreciated
Kevin Ashton wrote:
I have a JPanel with various buttons on it. I would like 'O' to
activate the "Ok" button, 'P' to activate the "Pass" button, etc.
without holding down the 'Alt' button.
Do I add an actionlistener to the JPanel? or JFrame maybe? But then
how would I set it to listen for a spefic key?
Sorry if it's an easy question. I'm still learning how to program.
Any help would be greatly appreciated. Thanks
this might be another way
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Testing extends JFrame
{
JButton okBtn = new JButton("OK");
JButton passBtn = new JButton("Pass");
public Testing()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p = new JPanel();
p.add(okBtn);
p.add(passBtn);
getContentPane().add(p);
pack();
setLocationRelativeTo(null);
okBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
JOptionPane.showMessageDialog(getContentPane(),"OK");
}
});
passBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
JOptionPane.showMessageDialog(getContentPane(),"Pass");
}
});
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventDispatcher(new KeyEventDispatcher(){
public boolean dispatchKeyEvent(KeyEvent ke){
if(ke.getID() == KeyEvent.KEY_PRESSED)
{
if(ke.getKeyCode() == KeyEvent.VK_O) okBtn.doClick();
else if(ke.getKeyCode() == KeyEvent.VK_P)
passBtn.doClick();
}
return false;
}
});
}
public static void main (String[] args){new
Testing().setVisible(true);}
}