• 1

JAVA Swing: Binding Function Keys to a JButton


Question

Does anyone know how to do this? e.g. user presses F1 and it will activate a JButton? I have tried setMnemonic() but this means you have to press alt and the F-Key instead of just the F-Key on its own. Any help would be much appreciated :cool:

Link to comment
Share on other sites

6 answers to this question

Recommended Posts

  • 0

It's been a while since I've done Swing, but I suspect you'll want to add some sort of key listener to the root window to listen for certain key presses. Upon the correct key press perform the correct handling code.

Link to comment
Share on other sites

  • 0
It's been a while since I've done Swing, but I suspect you'll want to add some sort of key listener to the root window to listen for certain key presses.  Upon the correct key press perform the correct handling code.

586414086[/snapback]

Thanks for your suggestion. I have tried using keyReleased on the JFrame but the event never seems to fire. Any other ideas?

Link to comment
Share on other sites

  • 0

how about this:

import javax.swing.*;
import java.awt.event.*;

class TestFrame extends JFrame implements KeyListener
 ?{
  public TestFrame()
    {
    :    //other stuff here

    this.addKeyListener(this);    //need to make the Form listen for keys being typed, pressed, and released.

    :    //other stuff here
    }//end of default constructor
 ?public void keyPressed(KeyEvent e) 
 ? ?{
 ? ?switch(KeyEvent.getKeyText(e.getKeyCode()))
 ? ? ?{
 ? ? ?case 'F': case 'f': /*do stuff here */ break;
 ? ? ?:
 ? ? ?:    //add more cases as needed
 ? ? ?}//end of switch
 ? ?}//end of keyPressed()

 ?public void keyReleased(KeyEvent e) 
 ? ?{
 ? ?}//end of keyReleased()

 public void keyTyped(KeyEvent e) ?
 ? ?{
 ? ?}//end of keyTyped()

 ?}//end of class

hope this helps,

STV

Edited by STV
Link to comment
Share on other sites

  • 0

I got is working guys, thanks for your help. In the end I found a custom class in the source tree that does what I want. Sorry to anyone else wanting to solve this problem but I am unable to post this class, I am sure you will understand :(

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.