Re: Passing KeyEvent upward
On 7/22/2012 5:26 PM, markspace wrote:
Sounds like an accelerator to me.
Here's the simplest example I could think of. Tell me if it works like
what you want.
package quicktest;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
/**
*
* @author Brenden
*/
public class Accelerator {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
JTextArea ta = new JTextArea();
frame.add(ta);
JMenuBar mbar = new JMenuBar();
JMenu file = new JMenu("File");
mbar.add(file);
JMenuItem blarg = new JMenuItem("blarg");
blarg.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_1, ActionEvent.ALT_MASK));
blarg.addActionListener( new Blarg( ta ) );
file.add(blarg);
frame.setJMenuBar(mbar);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize( 400, 400 );
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private static class Blarg implements ActionListener {
private final JTextArea ta;
public Blarg(JTextArea ta) {
this.ta = ta;
}
@Override
public void actionPerformed(ActionEvent e) {
ta.append( " blarg" );
}
}
}