Keypress listener anywhere in a JFrame

Hello!
I want to listen for a keypress (F12) from anywhere in my JFrame window, exactly like if I added a menubar with an accelerator.
I can't just register a KeyListener on the JFrame because I have serveral panels on it.
Any ideas?
//John

Thanks! works great now, here is the code if anybody is intrerested:
      private void addKeyBindings() {
           Action finishAction = new AbstractAction() {
                private static final long serialVersionUID = 1L;
                public void actionPerformed(ActionEvent e) {
                     onButtonFinishClick( e ); //Forward
           //Set input actions
           InputMap im = _bFinish.getInputMap( WHEN_IN_FOCUSED_WINDOW );
           ActionMap am = _bFinish.getActionMap();
           KeyStroke ks = KeyStroke.getKeyStroke( "F12" );
           im.put( ks, "onf12" );
           am.put( "onf12", finishAction );
      }

Similar Messages

  • Trapping KeyEvents anywhere in a JFrame for a status bar

    Hi all,
    There are a few examples of how to implement a status bar in the archives, but I haven't seen anything that tells you how to trap KeyEvents (e.g. pertaining to CapsLock etc.) which occur anywhere in a JFrame: once you start adding focusable components (particularly but not exclusively JTextComponents) to a JFrame the JFrame itself is often not sent the KeyEvents, so a rudimentary addKeyListener() is not the answer.
    Could this involve the use of KeyboardFocusManager or sthg? NB to experts: I have read the tutorial on the focus subsystem to no avail. The key seems to be to trap the event thread in some way, perhaps??
    All help greatly appreciated...
    Mike

    Add a AWTEventListener on Toolkit.getDefaultToolkit() with appropriate mask. See javadocs of addAWTEventListener method.

  • Regarding listener on component in JFrame!!!!!

    I am making JFrame having a JPanel added to its North
    now in this JPanel i have JButton .
    Now i m adding key listener to the JPanel
    the problem is when i put focus on button and press any key
    the key pressed method is not called
    however i read that if button is not registered with listener then the event is dispacthed to its upper hierarchy and so looks for panel to be listened but here nothing is happened
    why????????????????
    i am confused
    let me know whats the problem
    thanks in advance
    upasna

    Hi,
    In the new (not very new) event model the events is not propagated
    to its parents. So to solve your problem simply add a listener to you Button
    instead to your Panel
    Hope this help

  • Can one get keyPressed events anywhere other than in Canvas?

    Hi there,
    I have a form displayed
         display.setCurrent(form);
    but I would like to receive keyPressed events, in particular "game actions" UP DOWN LEFT RIGHT.
    As far as I can tell, this isn't possible unless I have a Canvas displayed. :-(
    The form is displaying data (a couple of string items) and the soft key commands.
    This is only my second MIDP app, so any help would be appreciated.
    Thanks,
    colin

    1. Don't know.
    2. Hopefully you have a backup to restore from. Contacts are separate from iTunes, but if you enabled iCloud, then your contacts should be preserved (if you do not use Outlook, Address Book, etc.)

  • JFrame restoration problem.

    Hello everyone!!
    My problem is:
    I have a jframe inside of that there's a jpanel.
    the jpanel mouse listener calls a method in a different class that uses the graphic reference of the jpanel to draw. once I minimize and maximize the jframe the drawing disappear. once I click on the area where drawing used to be it appears again.
    I have an inner window listener class in the jframe which calls the same method in the same instance of the other class but nothing happens until I click on the area on the mouse listener calls the method!!
    please help.

    Go through ths tutorial:
    The Java™ Tutorials: [Performing Custom Painting|http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html]
    After that, if you still have a question, post a SSCCE that clearly demonstrates the problem.
    db

  • How can I change the Jframe Java help Icon

    How can I change then Jframe Java help Icon?.
    I am using then HelpSet class and HelpBroker.
    I want to change the java help icon
    Any Idea? thanks. ...

    It can be done, but it's ugly...
    Add in a listener to your topmost JFrame to sense when the focus is lost, since this happens when a help window comes up. When the focus leaves the main window, check all the windows that are up to see if one is a help window. If so, this will give you a reference to the help window and you can drill down to change what you want.
    Here's an example that changes the icon and removes the borders from the javahelp buttons.
    WindowListener wndCloser = new WindowAdapter() {
              //A necessarily roundabout method to affect
              //look and feel aspects of the javahelp viewer.
              //(there is no way to get at these components directly.)
              //When the main frame loses focus, it may be because
              //the help viewer was brought up. Look through all
              //the current frames to see if one is a help viewer.
              //If it is, change the look of the help viewer
              //to what we want.
              Frame m_helpFrame = null;
              public void windowDeactivated(WindowEvent e) {
              if (m_helpFrame != null)
                   return;
              Frame[] frames = getFrames();
              for (int k = 0; k < frames.length; k++) {
                   if (!(frames[k] instanceof JFrame))
                   continue;
                   JFrame jf = (JFrame)frames[k];
                   if (jf.getContentPane().getComponentCount()==0)
                   continue;
                   Component c = jf.getContentPane().
                   getComponent(0);
                   if (c == null || !(c instanceof JHelp))
                   continue;
                   m_helpFrame = jf;
                   //now that we know the Frame, we can change the title icon
                   final Image image2 = <your icon here>
                   m_helpFrame.setIconImage(image2);
                   JHelp jh = (JHelp)c;
                   for (int s=0; s<jh.getComponentCount(); s++) {
                   c = jh.getComponent(s);
                   if (c == null || !(c instanceof JToolBar))
                        continue;
                   JToolBar jtb = (JToolBar)c;
                   //now that we've accessed the toolbar, we can
                   //modify the look of the buttons.
                   for(int i=0; i<jtb.getComponentCount(); i++) {
                        Component comp = jtb.getComponentAtIndex(i);
                        if(comp instanceof JButton) {
                        JButton button = (JButton)comp;
                        button.setBorder(null);

  • Listening for new cachings getting created?

    I'd like to be able to register my own MBeans on each distributed CacheServer for each cache that lives on that server. Is it possible to register a listener anywhere that gets called when a new cache gets created? Alternatively, is it possible to register a listener that is called after the cache factory has finished starting all the "autostart" caches?
    I'm using version 3.3
    thanks
    sam
    ps - I'm already registering my own custom global mbeans... but they are created before any of the caches get created.

    Sam
    You can specify your custom CacheFactory class in the override file so you can still use DefaultCacheServer
    When I needed to intercept cache creation I extended DefaultConfigurableCacheFactory and overrode this method:
    public NamedCache configureCache(CacheInfo cacheInfo, XmlElement xmlScheme, ClassLoader classLoader)
    Then just call the super class version before or after doing whatever you need to.
    The XML for the override file looks like this
    <coherence>
         <configurable-cache-factory-config>
              <class-name>com.oracle.coherence.common.configuration.AdvancedConfigurableCacheFactory</class-name>
              <init-params>
                   <init-param>
                          <param-type>java.lang.String</param-type>
                          <param-value system-property="tangosol.coherence.cacheconfig">coherence-cache-config.xml</param-value>
                   </init-param>
              </init-params>
         </configurable-cache-factory-config>
    </coherence>The above snippet is taken from the Incubator common library. You would replace com.oracle.coherence.common.configuration.AdvancedConfigurableCacheFactory with the name of your class.
    You need to call the override file tangosol-coherence-override.xml and put it on the class path or if you call it anything else then specify the name as a JVM argument with -Dtangosol.coherence.override=<name of your file>
    Jonathan

  • Fire event when clicking anywhere but on a specific component?

    Hi,
    I'm having some problems with a feature in my project. I wan't to be able to handle the text inside a JTextField when i click anywhere in my JFrame but the JTextField. Consequently, if I click outside of the JTextField I wan't an event to fire. How do I accomplish this as simple as possible?
    Thanks

    Have a look at the java.awt.Toolkit.addAWTEventListener(...) method.
    Piet

  • Listening problem

    Ok here goes.
    I currently have a main Jframe which contains a splitpanel. On the left side the split panel there is a jtree which is generated using beans. A jtree listener loads on the right hand side diffarent jpanels which are on separate files(classes) depending on which node the user selected. The jpanels loaded contain textboxes, labels and a save button. The problem is, I need the main class(Frame) to know if the save button has been pressed so that I can refresh the tree. Do i need to use a listener on this external class???
    any help would be greatly appreciated!!
    Thanks in advance.

    You should make the main frame an action listener.
    public myFrame extends JFrame implements ActionListener Then add it to the save buttons' actionlisteners.
    saveButton.addActionListener(this);In the frame's actionperformed event, update the tree.
    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == saveButton) {
            // do your updating
    }Here is a link that should help:
    http://java.sun.com/docs/books/tutorial/uiswing/events/index.html

  • Dispatching events...

    Hi,
    I am working on a project for a system that will not have a mouse. Ideally I would like the screen to function almost like a video game would -- even though it is not a game. By this I mean that all keystrokes are handled at the window level and dispatched to the correct component depending on the keystroke.
    Currently I have inhibited the ability of components on the form to gain focus. When I press a key, the listener associated with the JFrame responds... I then attmpt to use dispatchEvent inside of a case statement to route events to the proper components (In this case a JTextField) The problem is, is that allthough the dispatchEvent call is made, the JTextField doesn't do anything with it. I am just typing characters so I would expect all these keystrokes to show up in the JTextField, but it does not work.
    Does anybody know why this might not work?
    -Benjamin

    Here is a code snippet that actually seems to work. The problem was that I was dispatching a keyPressed event rather than a keyTyped.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class NoFocus extends JFrame implements KeyListener {
       private class JTextFieldNF extends JTextField {
          public JTextFieldNF(int size) {
             super(size);
          public boolean isFocusTraversable() {
             return false;
       JTextFieldNF tfnf;
         public NoFocus() {
          tfnf = new JTextFieldNF(20);
          getContentPane().setLayout(new FlowLayout());
          getContentPane().add(tfnf);
          addKeyListener(this);
         public void keyPressed(KeyEvent evt) {
       public void keyTyped(java.awt.event.KeyEvent evt) {
          switch (evt.getKeyCode()) {
             // Route up and down key somewhere else
             case KeyEvent.VK_UP:
             case KeyEvent.VK_DOWN:
                break;
             // All keystrokes not expicitly used are piped to tfnf
             default:
                      tfnf.dispatchEvent(evt);
       public void keyReleased(java.awt.event.KeyEvent A) {
         public static void main(String args[])
              JFrame frame = new NoFocus();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.setSize(200,200);
              frame.setVisible(true);

  • How to catch ctrl+x on a textfield?

    i've set ctrl-x as a shortcut to end my app but whenever my textfield holds focus, ctrl-x is disabled. how can i enable it? if i implement keylistener, where shld i define it in? keyPressed?

    KeyListener should be global throughout the program if CTRL + X is detected. Try programming it into the main contructor class of the java file the has the main() method within it. This way, the key will only be listened for when the JFrame is selected, if you are using a JFrame in the main class.

  • Problem with switching KeyListeners with different functions

    I have two KeyListener objects; one that listens for keyPressed events and another that listens for keyTyped events. I have a JFrame that, depending on the situation, may need one or the other, and often switches between the two. When I switch from the "keyPressed" KeyListener to the "keyTyped" KeyListener, there is a problem if the event is both a keyPressed type event and a keyTyped type event. To illustrate the point, say the KeyTyped listener is for an input field. Let's say the user has to press the "G" key to get to the input field, and when he or she presses "G" the JFrame will first remove the "keyPressed" listener and then add the "keyTyped" listener for the input field. This would seem to be a safe order to go about things; however, when the input field displays, there is a "g" already in the field. What should I do to avoid this kind of situation?

    set the text with yourtexfield.setText(null) method for text field after removing the listener

  • Buttons disappear

    Hi all,
    I'm sorry, I'm not sure if my problem relates to some of the other postings I've read on the forum or if it's something else I'm not aware of but the problem is this: I display a JFrame with a few JButtons for different options, like a menu of sorts and it works fine but if I recall my method to display the JFrame again later the buttons aren't visible, they're there and work if you click where they should be but I was hoping someone could tell me what I'm doing wrong. Why won't they show up?
    Thanks in advance
    Denise

    Every time you call drawMenu you are creating another panel3 and adding the buttons to it; they can only be used once, ie, added to one component. Try setting up your frame, panel and buttons one time and then using your event handling code to control the visiblitiy of your frame instead of trying to recreate parts of it.
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class laingden
      private JButton lookupButton = new JButton("Browse Known Issues");
      private JButton createButton = new JButton("Log New Issue");
      private JButton exitButton = new JButton("Exit");
      private ButtonListener listener = new ButtonListener();
      private JFrame frame = new JFrame();
      public laingden()
        JPanel panel3 = new JPanel();
        panel3.setLayout(new GridLayout(1,3));
        panel3.add(lookupButton);
        panel3.add(createButton);
        panel3.add(exitButton);
        lookupButton.addActionListener(listener);
        createButton.addActionListener(listener);
        exitButton.addActionListener(listener);
        frame.getContentPane().add(panel3, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
      public static void main(String args[])
        new laingden();
      private class ButtonListener implements ActionListener
        public void actionPerformed(ActionEvent event)
          String input;
          if ((JButton)(event.getSource()) == lookupButton)
            frame.hide();
            JOptionPane.showMessageDialog(null, "Menu closed");
            //I call another method here
    //        drawMenu();
          else if ((JButton)(event.getSource()) == createButton)
            frame.hide();
            JOptionPane.showMessageDialog(null, "Menu closed");
            //I call another method here
    //        drawMenu();
          else if ((JButton)(event.getSource()) == exitButton)
            System.exit(0);
    }

  • Multiple keystrokes selection for a JComboBox in JTable

    Has anyone used multiple keystrokes selection in a JComboBox inside JTable before? I can get it done outside JTable by using: http://javaalmanac.com/egs/javax.swing/combobox_CbMultiKey.html
    Looks like JTable has all kinds of problems to support JComboBox.
    Suggestions?
    Thanks,
    James

    If I read you right, you want to use a multiple keystroke combo box as an editor in a JTable?
    If you create the JComboBox as you would like it and then install it as an editor in the column(s) JTable the editor will work like the JComboBox
    Example:
    //- you would have that keyselection Manager class
    // This key selection manager will handle selections based on multiple keys.
    class MyKeySelectionManager implements JComboBox.KeySelectionManager {    ....    };
    //- Create the JComboBox with the multiple keystroke ability
    //- Create a read-only combobox
    String[] items = {"Ant", "Ape", "Bat", "Boa", "Cat", "Cow"};
    JComboBox cboBox = new JComboBox(items);
    // Install the custom key selection manager
    cboBox.setKeySelectionManager(new MyKeySelectionManager());
    //- combo box editor for the JTable
    DefaultCellEditor cboBoxCellEditor = new DefaultCellEditor(cboBox);
    //- set the editor to the specified COlumn in the JTable - for example the first column (0)
    tcm.getColumn(0).setCellEditor(cboBoxCellEditor); Finally, it may be necessary to to put a KeyPressed listener for the Tab key, and if you enter the column that has the JComboBox:
    1) start the editting
    table.editCellAt(row, col);2) get the editor component and cast it into a JComboBox (in this case)
    Component comp = table.getEditorComponent();
    JComboBox cboComp = (JComboBox) comp;3) give this compent the foucus to do its deed     
    cboComp.requestFocus();Hope this helps!
    dd

  • Trying to print a list using JOptionPane

    I am very new to Java and programming, so please forgive me if this should be apparent. I wrote a program for school which was for ordering pizzas. I wrote it as a console program and after much frustration it finally worked. Now I am trying to change it to a GUI program using JOptionPane. I was hoping that since I already had the logic written and working, I could focus on the GUI aspect. I was wrong. I want to print a list of enums on a JOptionPane and cannot figure out how to do it My code in the console program was:
    System.out.println("The available crust styles are: ");
         for(Pizza.Style style : Pizza.Style.values())
              System.out.println(style+" ");
    So how can I iterate through the for loop to list all of the styles in the JOptionPane? Do I need to turn it into a method with a return and then cal the method like
    JOptionPane.showMessageDialog(null, crustMethod()); ??

    OP said:
    ... Now I am trying to change it to a GUI program using JOptionPane. I was hoping that since I already had the logic written and working, I could focus on the GUI aspect. I was wrong. ...I wouldn't use JOptionPane. You need JFrame and maybe, but I doubt it, a JDialog. OP, the GUI is more than likely to be nothing more than a form that allows users to set certain properties or fields in a Java class. For example let's say we have this class.
    public class Point
      public int x;
      public int y;
    }Then a GUI for this would be something like a JPanel with two (2) JLabels and two (2) JTextFields. Maybe something like so...
    import java.awt.*;
    import javax.swing.*;
    public class PointGUI extends JPanel
      public JLabel xLabel = new JLabel("Coordinate X:");
      public JLabel yLabel = new JLabel("Coordinate Y:");
      public JTextField xField = new JTextField(4);
      public JTextField yField = new JTextField(4);
      public PointGUI(){
        setLayout(new GridLayout(2, 2));
        add(xLabel);
        add(xField);
        add(yLabel);
        add(yField);
    }Then to run the program...
    import javax.swing.*;
    public class Test
      public static void main(String[] args){
        SwingUtitlities.invokeLater(new Runnable(){
          public void run(){
            PointGUI gui = new PointGUI();
            JFrame f = new JFrame("PointGUI");
            f.getContentPane().add(gui, "Center");
            f.pack();
            f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
            f.setVisible(true);
    }... actually all the program does is display the GUI. But, can you see that the GUI's JLabels and JTextFields describe all the public properties of the Point class? Can you see that the entire GUI can be placed anywhere in a JFrame, or maybe even in a JDialog? From this point on, you can add other functions and features to your classes, GUI's and the main apps that run them.
    A hint on your project, you may need to write a Pizza class that decribes all the things a single pizza can be - then come up with a GUI for that and an app that runs it.

Maybe you are looking for

  • Photoshop Elements 3 and 4 doesn't work on Intel Macbook

    Hi, and thanks in foreword, so my problem is nether of 3 or 4 doesn't work on my computer. Here are the crash reports. Those haven't worked after install. Just tell if you need more information. Please help me repair this problem! Process:         Ph

  • AppleWorks Icon does not stay in the same position after saving

    After I installed AppleWorks 6.2.8, each time I save the file (word prosessor or data base) the icon on the desktop always moves to the right side of the screen below the hard drive icons. If I drag it to different position, then save the file it wil

  • Interactive Image: Text Styles?

    Is there a standard text style we can edit to modify what shows up in the text boxes when an interactive image zooms in? According to the Style menu it's "Body Bullet" text, which just by looking at it you know that's not right. I don't see an "Inter

  • Help: How to Validate XML using SAXParser and return the entire error list

    Hi, I have a problem, I'm trying to validate a xml document against the DTD. Here Im using SAXParser and having the ErrorHandler object passed when setting the error Handler, like parser.setErrorHandler(errorHandlerObj). I need an output like where t

  • Moving FINDER files without Dupes TRICK

    I got on the phone with a mac help guy and he came up with a method for finding all my images on my hard drive or all my movies on my hard drive (came from windows) - by opening spotlight, entering something like "test" in the search box, clicking ad