Recognize the pressed Key

Hello,
I want to recognize if the Ctrl Key is pressed or not. This could usually be done by adding a KeyAdapter or Listener to the JComponent and … .
The KeyAdapter solution unfortunately does not help me here, because of my special situation.
However, I execute a special method, and I would like to recognize if the Ctrl key is pressed. I need a Static solution, which gives me this information.
Can I do this at all?
Is there any static method, which returns this information about the keyboard?
Thanks in advance.
sssako

How can I solve the problem that invisible menu items are inactive?at best this is a very poor hack.
(there are much better ways to achieve what you want)
ctrl-O to activate
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Testing
  public void buildGUI()
    JMenu menu = new JMenu("File");
    JMenuItem open = new JMenuItem("Open");
    JMenuItem exit = new JMenuItem("Exit");
    menu.add(open);
    menu.add(exit);
    JMenuBar menuBar = new JMenuBar(){public boolean isShowing(){return true;}};//<-----------------
    open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_DOWN_MASK));
    menuBar.add(menu);
    menuBar.add(open);
    menuBar.setVisible(false);
    JFrame f = new JFrame();
    f.getContentPane().add(menuBar,BorderLayout.CENTER);//must add it in a way that it will be 'knocked out'
    f.getContentPane().add(new JTextArea(5,20),BorderLayout.CENTER);//this knocks out the menuBar
    f.pack();
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    open.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent ae){
        System.out.println("OK");
  public static void main(String[] args)
    SwingUtilities.invokeLater(new Runnable(){
      public void run(){
        new Testing().buildGUI();
}[edit]
just realized it doesn't need the isShowing() override or the setVisble(false)
works OK just being knocked out
Edited by: Michael_Dunn on Oct 29, 2007 6:58 PM

Similar Messages

  • How to recognize the tab key in a JTextField

    I have a drawing program with a main window and a tools palette, which is a JDialog. The tools palette has JToggleButtons and one JTextField. When you have the focus in the JTextField and you press tab repeatedly, it tabs through all the JToggleButtons and then back into the JTextField.
    However I would like to recognize the pressing of the tab key and ask for the focus to go back to the main window.
    I subclassed the JTextField, added a KeyAdapter, but it does not recognize the tab key. I also added the processKeyBinding method, but it doesn't recognize the tab key either.
    How can I recognize the tab key?
    Here is a self-contained test program that illustrates the problem:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class AnanyaCurves extends JFrame
      Tools tools;
      public AnanyaCurves(Dimension windowSize)
        Basics.ananyaCurves = this;
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        setTitle("Ananya Curves");
        tools = new Tools(this);
      public static void main(String[] args)
        int toolsWidth;
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        toolsWidth = 200;
        Dimension windowSize = new Dimension(screenSize.width - toolsWidth, screenSize.height - 58);
        AnanyaCurves ananyaCurves = new AnanyaCurves(windowSize);
        ananyaCurves.pack();
        ananyaCurves.setBounds(toolsWidth, 0, windowSize.width, windowSize.height);
        ananyaCurves.setVisible(true);
        ananyaCurves.requestFocus();
      public void setVisible(boolean b)
        tools.setVisible(b);
        super.setVisible(b);
    class Basics extends java.lang.Object
      public static AnanyaCurves ananyaCurves;
      public Basics()
    class Tools extends JDialog
      JToggleButton btnGrid;
      JTextField textGrid;
      JPanel panel;
      public Tools(JFrame frame)
        super(frame, "Tools", false);
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        btnGrid = makeBtn("Grid");
        textGrid = makeTextField();
        panel = makePanel();
        pack();
      public JToggleButton makeBtn(String name)
        JToggleButton btn = new JToggleButton();
        btn.setMaximumSize(new Dimension(108, 24));
        btn.setPreferredSize(new Dimension(108, 24));
        btn.setText(name);
        btn.setFont(new Font("Verdana", Font.PLAIN, 11));
        btn.setMargin(new Insets(5, 10, 5, 10));
        btn.setOpaque(true);
        return btn;
      public ACJTextField makeTextField()
        ACJTextField textField = new ACJTextField();
        textField.setFont(new Font("Verdana", Font.PLAIN, 12));
        textField.setMaximumSize(new Dimension(108, 20));
        textField.setPreferredSize(new Dimension(108, 20));
        textField.setText("0.25");
        textField.setEnabled(true);
        return textField;
      public JPanel makePanel()
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.add(btnGrid);
        panel.add(textGrid);
        getContentPane().add(panel);
        return panel;
    class ACJTextField extends JTextField
      KeyAdaption keyAdaption;
      public ACJTextField()
        super();
        keyAdaption = new KeyAdaption();
        this.addKeyListener(keyAdaption);
      class KeyAdaption extends KeyAdapter
        public void keyPressed(KeyEvent event)
          int keyCode = event.getKeyCode();
          if (keyCode == KeyEvent.VK_TAB)
            Basics.ananyaCurves.requestFocus();
      protected boolean processKeyBinding(KeyStroke keyStroke, KeyEvent keyEvent, int int2, boolean boolean3)
        int keyCode = keyEvent.getKeyCode();
        if (keyCode == KeyEvent.VK_TAB)
          Basics.ananyaCurves.requestFocus();
          return false;
        return super.processKeyBinding(keyStroke, keyEvent, int2, boolean3);
    }Thanks for looking at this.

    Wow, Michael, you work like magic! Thanks so much! I would be happy to give you a commercial key to my Ananya Curves program also once the second release is on my website. It's a program for drawing curves in an easier way without pulling on tangent lines, with all control points right on the curve. Just send me an email to [email protected] if you are interested!

  • How do I find out if the pressed key is printable?

    I have made a game and now I'm working on a hiscore table for it. But with my function the program doesn't know if the pressed key is printable or if it's shift, ctrl or something like that. And I made it possible to enter maximum 40 letters as name, so if the user holds the shift key for a while then the whole String is filled with shift characters and nothing shows on the screen and he/she isn't able to type in any more letters... So is there any way to find out if the pressed key contains a printable char?
    This is what my function looks like now. My program is quite big so I just post the function and try to explain what is happening
    /* high is an array of
    int score;
    String name;
    boolean WritingName;
    boolean GAMEOVER;
    boolean newgame;
    public void keyPressed(KeyEvent e) {
         if (GAMEOVER){  // checks if the game has ended
             char button = e.getKeyChar();
             int keyCode = e.getKeyCode();
             if (newgame){  // this is false if the hi-score list is showing otherwise its true. i.e. its true when typing name for hiscore list
                   if (keyCode == 10) {       // check if the pressed key is enter
                        WritingName = false;  // Tells an other function that the user has finished typing his/her name so it can save it and start showing the hiscore-list on the screen
                   } else {
                        if (keyCode == 8){    // check if the pressed key is backspace and if so removes the last char from the string
                             if (high[99].name.length() > 0){
                                  high[99].name=high[99].name.substring(0,high[99].name.length()-1); 
                        } else {  // if any other key is pressed then add it to the end of the string
                             if (high[99].name.length() <= 40 ) high[99].name += button;
                   paint(getGraphics());
              } else {  // checks if space is pressed to stop showing the hiscore-list and start a new game
                   if (keyCode == 32) newgame = true;
    }

    But with my function the program doesn't know if the pressed key is printable or if it's shift, ctrl
    or something like thatProbably the easiest way is to check and see if e.getKeyChar() < a space character or if e.getKeyCode() >= 127. You can use e.getModifiers() to get the modifier, etc... -- take a look at the documentation for java.awt.event.KeyEvent class.
    V.V.

  • I purchased a License for Adobe Photoshop Elements 13 plus Adobe Premiere Elements 13 and Adobe doesn't recognize the License Key, Adode customer services aren't interested.

    I purchased a License for Adobe Photoshop Elements 13 plus Adobe Premiere Elements 13 and Adobe doesn't recognize the License Key, Adobe customer services aren't interested, neither are Ebuyer.com.
    Where do I go next? Credit card company to ask for a refund?

    57dibbs
    Has you contacted the seller through its Customer Service?
    If that is the case and Customer Service has no idea of what you were given as a Product Key and how to use it, have you considered asking
    your question in the seller's forum (PC software section)?
    But, I have another idea for you to try first....are you involved in a student teacher purchase with prepaid card? If so, please click on the following link
    http://helpx.adobe.com/x-productkb/global/find-serial-number-student-teacher.html#card-sub mit-product-code
    and go to the section on "I received a prepaid card, and I need help". In that section go to "2" which is for
    "Submitting my product code and proof of eligibility to Adobe". You will notice there is a link to click on that
    is related to country. Make the appropriate choice and see if that solves the problem. You should see
    Visit the page listed on the back of your prepaid card to submit your code and proof.
    For customers inside North America, www.adobe.com/go/edu-validate
    For customers outside North America, submit through your region's customer portal below:
    Europe, Middle East, Africa | Germany | France | Spain | Italy | Netherlands | Czech Republic | Poland | Asia/Pacific | Korea
    Verification can take anywhere from 2 to 30 days to validate.
    If the above does not apply to you, then I would explore the seller forum for answers if you cannot get them from Adobe Chat or the seller's
    Customer Service. Getting your money back from the seller should be tried as soon as possible if you find no solution.
    Thank you.
    ATR

  • Since upgrading from Windows Vista to Windows 7 both Internet Explorer and Firefox will not recognize the numbers keys of my keyboard. I get numbers in Word and every other situation, just not in the internet programs.

    Since upgrading from Windows Vista to Windows 7 both Internet Explorer and Firefox will not recognize the numbers keys of my keyboard. I get numbers in Word and every other situation, just not in the internet programs. I have tried uninstalling Firefox and reinstalling with no results.

    If there are problems with importing the IE Favorites in Firefox then export the favorites in IE to an HTML file and import that file in the Firefox Bookmarks Manager.
    If you do not have the menu bar in IE then right-click the toolbar at the top to enable the Menu Bar.
    *Export the favorites in IE to an HTML file (bookmarks.html):<br>File > Import and Export
    *Import the HTML file in Firefox:<br>Bookmarks > Show All Bookmarks > Import & Backup > Import Bookmarks from HTML
    See "Import from another browser" and "Import from file":
    *http://kb.mozillazine.org/Import_bookmarks

  • Start with the Option key down - Which port to connect the keyboard?

    When I need to start my Mac with the Option key down in order to select a boot volume, I have noticed that the system ignores the Option key press and boots into a previous boot volume if a USB keyboard is plugged into an external USB hub. That's understandable because the boot sequence may not detect the keyboard on the external USB bus fast enough for the system to recognize the Option key press.
    My Mac will always recognize the Option key press at a boot time if the USB keyboard is plugged into a USB port on the Mac.
    I want to know what if the boot sequence will detect the keyboard +soon enough+ to recognize the Option key press if the keyboard is connected to a USB port on a PCIe USB expansion card.
    If you know the answer, please let me know because, if the answer is no, I would not want to invest money into an expansion card.

    Even if it doesn't work with the card, you can plug the keyboard into a built-in port and use the card's ports for other USB devices. The total number of USB ports would be the same.

  • How can I use the enter key instead of tab to change field focus?

    I am using Acrobat 9 Pro.
    We have a fillable PDF where the users enter numbers into fields.  They want to be able to use the <enter> key on the 10-key pad instead of the <tab> key on the keyboard to move the focus to the next data entry field.
    How can I set my PDF so that it recognizes the <enter> key instead of the <tab> key for changing focus?
    Thanks!

    You can use a custom Keystroke script, something like:
    // Custom Keystroke script for text field
    if (event.willCommit && event.commitKey === 2) {
        getField("Text2").setFocus();
    Where "Text2" is the name of the next field. This doesn't disable the Tab key though. For more information, see: http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.608.html

  • Remapping the Fn key in Windows   * a solution *

    Howdy,
    If you own a Mac and you're running Windows via Boot Camp, it's likely that you've noticed that there are problems with the operation of the Fn key. Because the keyboard doesn't have a Delete key, it's extremely annoying that you can't use Fn+Backspace in order to get the Delete function.
    As discussed in this thread it's possible to remap normal keys on your keyboard with a remapping tool like AutoHotKey. Unfortunately this application doesn't recognize the Fn key by default, so you're still stuck with other key combinations like Command+Backspace = Delete.
    I don't use Boot Camp on my MacBook, but I do have a PC with Windows XP. I recently purchased an Apple Wireless Keyboard, which is basically identical to my MacBook keyboard. Using it in Windows is no problem, but the Fn and Eject key both don't work. So I suppose the problem is the same for users of Windows through Boot Camp.
    First I used AutoHotKey to remap Command+Backspace to Delete. But I couldn't get over the fact that there were two keys that I couldn't use. So I kept looking for a solution, and finally found one. Using a DLL file for adding support for Human Interface Devices, written by one of the AHK forum members, I was able to get a response back from my Fn and Eject key. I wrote a script that let's you alter the behavior of the Fn key, so it will act as a modifier.
    At this point my Fn key is fully functional, and I mapped all the basic OS X functions so they can be used in Windows. So whether I'm using Leopard on my MacBook or Windows on my PC, everything is the same. This means:
    Fn+Backspace = Delete
    Fn+F10 = Mute/Unmute
    Fn+F11 = Volume Down
    Fn+F12 = Volume Up
    Eject key ejects my drive (without or with a delay just as in OS X)
    And so forth.
    Because the Fn key question is a common problem for a lot of people, I decided to write a full guide explaining every step of the way in full detail. The guide can be found right here:
    Mystery of the Fn key - A guide to remapping the Fn key in Windows
    The DLL used to retrieve information from the Fn and Eject key has already been used for many other purposes, and made it possible to map a lot of different keys on many different keyboards and other devices like mice and remote controls. By doing so it has proven its worth, and I'm sure that you'll be able to get your Fn key and other special keys working just fine. Whether it's on your Mac using Boot Camp, on a PC with using a keyboard with special hotkeys or on a PC notebook. The guide is based on remapping my Apple Wireless Keyboard, so at least I'm sure that it'll work for Apple keyboards.
    Feedback on my guide and script and whether you succeeded remapping your Fn and Eject key is much appreciated.
    Good luck!

    Well I tried but none of the settings recognized Fn nor Eject on my MBP (penryn w/ OSX and Vista). I even ran through dozens of possible Usage/Page combinations. My other keys were recognized and so what my mouse/trackpad. But not Fn and Eject.
    As you state in the write-up "If your key isn't recognized by one of the devices and their settings as listed in the application, it's unfortunately not likely that you'll get your key to work."
    Thanks anyway. I really thought I found the answer in this thread...
    oh well.
    D'
    PS. It really shouldn't be this hard to delete email using one hand....

  • Is ipad able to recognize the magic mouse

    My ipad recognizes the wireless key board but not the wireless mouse.  Is there a trick to make it recognize the wireless mouse?

    No.
    And there is No Cursor on an iPad.

  • How do I turn on long press keyboard to write the same character many times with one keystroke only? I can only write 1 letter at a time with each key press. To write "aaaaa" I need to press 5 times the A key. I didn't use to do this.

    I know this has something to do with INSERT key in Windows I guess. But suddenly I was using Mac OS X Lion and a keyboard sign appeared in the top bar, and the keyboard didnt work as it usually does. I mean, I wanted the long press key to write multiple caracters of course. Please help!

    It's now a hidden option that can be turned on with a terminal command.  The easiest way to do this is to download TinkerTool from this site:
    http://www.bresink.com/osx/0TinkerTool/download.php5
    Then go to Tinkertool > General tab > Select "support key repeat".
    Logoff and login again.
    Regards,
    Captfred

  • I had a problem with my mouse double(multiple) clicking when I didn't want it to, now pressing enter in a window like this will close the current window and open one of my Taboo sites, and the cursor keys don't work.

    This happens in any text entry window, but there is no problem with Wordpad or Word or other apps, just in Firefox. It's like the keyboard mapping has gotten fouled up in Firefox, but I can't find where I might check what is going on.

    You may have '''Switched ON Caret Browsing'''. press '''F7 (on Mac: fn + F7)''' to toggle '''Caret Browsing ON/OFF'''
    * click '''Firefox''' button and click '''Options''' -> Advanced -> General -> remove
    Checkmark from '''Always use the cursor keys to navigate within pages'''
    * http://kb.mozillazine.org/Scrolling_with_arrow_keys_no_longer_works
    * http://kb.mozillazine.org/Accessibility_features_of_Firefox
    Check and tell if its working.

  • Since upgrading to Firefox 10.0.2 my AVG extension has had to be disabled, as after typing in any web address in the address bar, the enter key had no effect and I could not go to the site without pressing the Reload arrow on right.

    I have recently upgraded Firefox to the latest version 10.0.2. After that I could not enter any website address and press the enter key and get to the website, nor could I select a website from the dropdown list of previously visited websites. The only way I could get there was by pressing the arrow on the right side of the address box (Reload current page). Once I disabled the AVG extension, everything worked normally. As soon as I enabled the AVG extension, it stopped working again.

    Follow these steps for the controls to work:
    # Start > Programs > Mozilla Firefox > Mozilla Firefox
    # Find the “Tools” menu at the top of the browser window and select “Add-ons”.
    # Click on the “Extensions” icon to make sure you’re in the correct option menu.
    # Locate “AVG Safe Search” and click on the containing line to highlight and select the add-on.
    # Click the “Disable” button and close the Add-ons window.
    # Close down any Firefox windows you may have open.
    # That’s It – You’re Done!

  • I have a macbook (circa 2008) version mac os x10.6.8. The 'l' key on my keyboard is hard to press down and doesn't always come up on the screen.

    I've never had a problem with any of the keys on my keyboard up until now. The 'l' key has become like hard and I have to press down harder and more deliberately then I normally do. Otherwise an 'l' doesn't show up on the screen. It's not a settings or technical problem. I feel like just needs to be cleaned or something like that but I don't know. It's really frustrating whenever I'm typing especially since 'l' is a pretty common letter. Please help!

    You can try this but I'm not sure if it will work http://m.wikihow.com/Temporarily-Remove-a-Key-from-a-Macbook
    ALso found this video on YouTube https://www.youtube.com/watch?v=kh88cn_rtLo
    The keyboard, trackpad and top case are an integral unit, you'll probably have to replace the top case https://www.ifixit.com/Guide/MacBook+Core+2+Duo+Upper+Case+Replacement/515

  • How can I stop a sound from looping so it plays only once each time the up key is pressed?

    Hi there here is my code, the basis is it is playing a mp3 from my library.
    Basically as the topic suggests I only want the sound to play once each time the UP arrow key is pressed. At the moment when you hold the up arrow down the sound keeps triggering and looping and gets really loud and noisy.
    Here is my code for my game:
    package com.chasegame.components
              import flash.display.MovieClip;
              import flash.display.Stage;
              import flash.events.Event;
              import com.tech.utils.KeyObject;
              import flash.ui.Keyboard;
              import flash.media.Sound;
              import flash.media.SoundChannel;
              public class SpaceShip extends MovieClip
                        private var key:KeyObject;
                        private var speed:Number = 0.3;
                        private var rotateSpeed:Number = 5;
                        private var vx:Number = 0;
                        private var vy:Number = 0;
                        private var friction:Number = 0.95;
                        private var shipSound:roar = new roar();
                        private var shipSoundChannel:SoundChannel = new SoundChannel();
                        public function SpaceShip () : void
                                            key = new KeyObject(stage);
                                            addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
                        public function loop(e:Event) : void
                                            if (key.isDown(Keyboard.UP))
                                                           vy += Math.sin(degreesToRadians(rotation)) * speed;
                                                           vx += Math.cos(degreesToRadians(rotation)) * speed;
                                                           shipSoundChannel = shipSound.play();
                             else
                                                           vy *= friction;
                                                           vx *= friction;
                                  if (key.isDown(Keyboard.RIGHT))
                                            rotation += rotateSpeed;
                                  else if (key.isDown(Keyboard.LEFT))
                                            rotation -= rotateSpeed;
                                  y += vy;
                                  x += vx;
                                  if (x > stage.stageWidth)
                                            x = 0;
                                  else if (x < 0)
                                            x = stage.stageWidth;
                                  if (y > stage.stageHeight)
                                            y = 0;
                                  else if (y < 0)
                                            y = stage.stageHeight;
                        public function degreesToRadians(degrees:Number) : Number
                                  return degrees * Math.PI / 180;

    If you want the sound to only play once when the key is pressed then you don't want to have it in the ENTER_FRAME event handler like you have it.  It is starting new sounds at the frame rate of your file the way you have it now.
    Try having an event listener dedicated to a KeyboardEvent.KEY_DOWN event where you detect when the UP key gets pressed and use that to trigger playing the sound.

  • I have MacAir with OS 10.8.4, how can I cancel the automatic link of my USB flashdisk to Mac instead of BootCamp, since I have one time press the ALT key before choosing "MAC" or "BOOTCAMP". Thanks

    I have MacAir with OS 10.8.4, how can I cancel the automatic link of my USB flashdisk to Mac instead of BootCamp, since I have one time press the ALT key before choosing "MAC" or "BOOTCAMP". Thanks

    That only happens when you are running Windows in a Virtual Machine with OS X as the host. Shut down the VM and restart your Mac.  Once the VM is running again and you insert a USB flash drive you should get that prompt again.

Maybe you are looking for

  • Programs not responding after 10.3.9 upgrade

    I upgraded my operating system to 10.3.9 combined update and now my iTunes, Quicktime & Final Cut Pro will not open. I have to force quit them because they don't respond. I tried reinstalling iTunes but that didn't work. Short of pulling out my boot-

  • Statspack report analyising

    Dear frnds How can i analyze a statspack report,My manager gave me a statspack report and told me to analyze .The report contains around 70 pages.He told me to analyze and give the recomendation to improve performance ,How can do this pls help with r

  • Changing images on JButtons

    hi all, I have a collection of icons that having images available in multiple sizes. The program my company is working on is geared towards deaf/hard of hearing and sight impaired individuals. I have assigned all the buttons images - however I want t

  • Retina display in imac

    Hai I am in the process of moving from Mac mini to imac. Is a retina display model on the horizon in imac? Badrakumar

  • System and Iview template selection to create SSO connection

    Hello everybody, a. In the system landscape when you create a system to connect with an external system (R/3) what have you to choose, SAP system using connection string, dedicated application server or with load balancing? What is the difference bet