Using KeyListener

I'm looking for something similar to some code I wrote in C++ not too long ago. It uses windows.h I believe, and the exact code segments needed are:
#define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)and then
if(KEY_DOWN(VK_UP))Basically, what I'm looking for is something that will return a boolean value for a specific key or the value of the key currently being pressed. I think what I want is keylistener, but I can't manage to get any of the examples to work, and a lot of them are quite complicated.
I'm using Java 5.0 if it matters.

I'm looking for something similar to some code I
wrote in C++ not too long ago. It uses windows.h I
believe, and the exact code segments needed are:
#define KEY_DOWN(vk_code)
((GetAsyncKeyState(vk_code) & 0x8000) ? 1 :
0)and then
if(KEY_DOWN(VK_UP))Basically, what I'm looking for is something that
will return a boolean value for a specific key or the
value of the key currently being pressed. I think
what I want is keylistener, but I can't manage to get
any of the examples to work, and a lot of them are
quite complicated.
I'm using Java 5.0 if it matters.I do not code in C++, and so the code you posted I could only guess at. However, that said, I imaging you want KeyEvent.getKeyCode(), and that you want it on keyPressed events. What you wanna do is check out the API docs for the vers you are using and go up and down the list of methods available.
Posting the code you have tried is - I totally agree - is the best way for any of us to point out what's right from what's wrong ... if you keep the snippet concise and well arranged.
!!Bill (today)

Similar Messages

  • Problem using KeyListener in a JFrame

    Let's see if anyone can help me:
    I'm programming a Maze game, so I use a JFrame called Window, who extends JFrame and implements ActionListener, KeyListener. Thw thing is that the clase Maze is a JPanel, so I add it to my Frame and add the KeyListener to both, the Maze and the Window, but still nothing seems to happen.
    I've tried to remove the KeyListener from both separately, but still doesn't work...
    Any suggestions???

    This is the code for my Window.java file. May be someone can see the error...
    package maze;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Window extends JFrame implements ActionListener, KeyListener {
      private Maze maze;
      private JButton crear = new JButton("New");
      public Window(int size, String s) {
        super("3D Maze");
        boolean b = true;
        if (s.equalsIgnoreCase("-n"))
          b = false;
        else if (s.equalsIgnoreCase("-v"))
          b = true;
        Container c = getContentPane();
        c.setLayout(new BorderLayout());
        maze = new Maze(size,size,b);
        crear.addActionListener(this);
        addKeyListener(this);
        maze.addKeyListener(this);
        c.add(crear,BorderLayout.NORTH);
        c.add(maze,BorderLayout.CENTER);
        setSize(600,650);
        show();
      public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == e.VK_UP || e.getKeyCode() == e.VK_W)
          maze.walk();
        else if (e.getKeyCode() == e.VK_DOWN || e.getKeyCode() == e.VK_S)
          maze.back();
        else if (e.getKeyCode() == e.VK_LEFT || e.getKeyCode() == e.VK_A)
          maze.turnLeft();
        else if (e.getKeyCode() == e.VK_RIGHT || e.getKeyCode() == e.VK_D)
          maze.turnRight();
        else if (e.getKeyCode() == e.VK_V)
          maze.alternaMostrarCreacion();
        else if (e.getKeyCode() == e.VK_M)
          maze.switchMap();
      public void keyTyped(KeyEvent e) {}
      public void keyReleased(KeyEvent e) {
      public void actionPerformed(ActionEvent e) {
        maze.constructMaze();
      public static void main(String[] args) {
        int i = 30;
        String s = "-v";
        if (args.length != 0) {
          try {
            i = Integer.parseInt(args[0]);
            if (!(i >= 15 && i <= 50))
              i = 30;
            s = args[1];
          catch(Exception e) {}
        Window w = new Window(i,s);
        w.addWindowListener(
          new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              ImageIcon im = new ImageIcon("./Logo.gif");
              String s = "";
              s += "3D MAZE\n\n";
              s += "Creator: Allan Marin\n";
              s += "http://metallan.topcities.com\n\n";
              s += ""+((char)(169))+" 2002";
              JOptionPane.showMessageDialog(null,s,"About...",JOptionPane.PLAIN_MESSAGE,im);
              System.exit(0);
    }

  • Needing help: using Keylistener to change images

    I am trying to using the arrow keys to switch between pictures i have but i cant get it to work... mind that im relativly new at java. Here is what i trying to do:
    starts at pic1: press up: frame now has pic2: press down: frame now shows pic1
    my code so far:
    public class test2 {
    static JFrame frame;
    static int position = 0;
    public static void main(String args[]){
    JFrame.setDefaultLookAndFeelDecorated(true);     
    frame = new JFrame("Frame Title");
    JMenuBar menuBar = new JMenuBar();
    JMenu menuFile = new JMenu("File");
    JMenu menuHelp = new JMenu("Help");
    JMenuItem menuFileExit = new JMenuItem("Exit");
    JMenuItem menuFilePlay = new JMenuItem("New");
    JMenuItem menuFileAbout = new JMenuItem("About");
    JMenuItem menuFileHelp = new JMenuItem("Help");
    menuFile.add(menuFilePlay);
    menuHelp.add(menuFileAbout);
    menuHelp.add(menuFileHelp);
    menuFile.add(menuFileExit);
    menuBar.add(menuFile);
    menuBar.add(menuHelp);
         frame.setJMenuBar(menuBar);
    frame.setSize(1025, 769);
    JLabel temp3 = new JLabel(new ImageIcon("EQ2_000000.gif"));     
    JPanel temp4 = new JPanel();
    temp4.add(temp3);
    frame.getContentPane().add(temp4);
    frame.setVisible(true);
    frame.setIconImage(new ImageIcon("bear.gif").getImage());
    menuFileExit.addActionListener
    new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.exit(0);
    menuFileAbout.addActionListener
    new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    JFrame About = new JFrame("About");
    About.setSize(200, 200);
    About.setIconImage(new ImageIcon("bear.gif").getImage());
                        JLabel temp = new JLabel(new ImageIcon("bear.gif"));     
                        JPanel temp2 = new JPanel();
                        temp2.add(temp);
                        About.setContentPane(temp2);
                        About.setVisible(true);
    menuFileHelp.addActionListener
    new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    JFrame About = new JFrame("Help");
    About.setSize(200, 200);
    About.setIconImage(new ImageIcon("bearr.gif").getImage());
                        About.setVisible(true);
         frame.addWindowListener
    new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.addKeyListener
    new KeyAdapter() {
    public void keyPressed(KeyEvent ke) {
                        switch (ke.getKeyCode()) {
                   case KeyEvent.VK_LEFT:
                   break;
    case KeyEvent.VK_RIGHT:
    break;
                        case KeyEvent.VK_UP:
                             frame.getContentPane().removeAll();
                             position = position + 1;
                             JLabel temp7 = new JLabel(new ImageIcon("pics/EQ2_00000" + position + ".gif"));     
                        JPanel temp8 = new JPanel();
                        temp8.add(temp7);
                        frame.getContentPane().add(temp8);
                        System.out.print(" u, " + position );
                   break;
    case KeyEvent.VK_DOWN:
         frame.getContentPane().removeAll();
    position = position - 1;
                             JLabel temp5 = new JLabel(new ImageIcon("pics/EQ2_00000" + position + ".gif"));     
                        JPanel temp6 = new JPanel();
                        temp6.add(temp5);
                        frame.getContentPane().add(temp6);
                             System.out.print(" d, " + position);
    }

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class KeyControl
        BufferedImage[] images;
        int imageIndex;
        JLabel label;
        public KeyControl()
            loadImages();
            imageIndex = 0;
            label = new JLabel(new ImageIcon(images[0]));
            //label.requestFocusInWindow();
            registerKeys(label);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(label);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        private void changeImage(int index)
            label.setIcon(new ImageIcon(images[index]));
            label.repaint();
        private Action up = new AbstractAction()
            public void actionPerformed(ActionEvent e)
                imageIndex = (imageIndex - 1) % images.length;
                if(imageIndex < 0)
                    imageIndex = images.length - 1;
                changeImage(imageIndex);
        private Action down = new AbstractAction()
            public void actionPerformed(ActionEvent e)
                imageIndex = (imageIndex + 1) % images.length;
                changeImage(imageIndex);
        private void registerKeys(JComponent c)
            c.getInputMap().put(KeyStroke.getKeyStroke("UP"), "UP");
            c.getActionMap().put("UP", up);
            c.getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "DOWN");
            c.getActionMap().put("DOWN", down);
        private void loadImages()
            String[] fileNames = { "greathornedowl.jpg", "mtngoat.jpg" };
            images = new BufferedImage[fileNames.length];
            for(int j = 0; j < images.length; j++)
                try
                    URL url = getClass().getResource("images/" + fileNames[j]);
                    images[j] = ImageIO.read(url);
                catch(MalformedURLException mue)
                    System.err.println("url: " + mue.getMessage());
                catch(IOException ioe)
                    System.err.println("read: " + ioe.getMessage());
        public static void main(String[]args)
            new KeyControl();
    }

  • How to add a KeyListener for the JFrame (when I'm typing in a JTextField)?

    I have some problem with KeyListener..
    I add a KeyListener (I named it "listener") for my JFrame and it works fine. Then I add JTextField to the JFrame. When I'm typing some text in the JTextField - my "listener" does not work. (cause my JTextField doesn't have a KeyListener).
    I just want to make an ability to process hot keys which user presses in my java program..
    Does anyone know how to do it?

    In future, please ask Swing questions in the [Swing Forum.|http://forums.sun.com/forum.jspa?forumID=57]
    Don't use KeyListener. In fact KeyListener is seldom useful. Use key binding: [http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]
    Or you can have menu items with accelerators (hot keys).

  • JTextArea and typing one char at a time!

    Hi everyone!
    I'm developing an small app. In certain cases, the user may want to edit a little piece of text. For this, I show a new Frame with a JTextArea with the selected text, so the user can edit it...
    But I want to control this edition: the user only can type one char at a time, disable selecting text and waiting a short time (250ms) between char and char...
    Some ideas? Some suggestion?
    Should I use keylistener and wait for the KeyPressed event and wait inside 250 ms?
    The reason for the waiting: when the user type a new char (or delete an existing one), I need to do some calculations. And it must be char by char, if the user select text and replace it, or if the user type fast... my program crash.
    Thanks in advance!

    Use a DocumentFilter and add the character yourself one at a time.
    Or better perform the calculation there.
    http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter
    Also perform the calculation in the Event Dispatch Thread so it will wait until the calculation is finished before accepting new input.

  • Blackberry controls and midlets

    Midlet meets blackberry let the battle for who can use the escape key begin!
    If you're having trouble mapping keys from the blackberry to your midlet..this will definitely help you!
    in this post I go over: Adding menu items to the blackberry menu, and gaining access to undetected keys such as the Escape Key.
    First of all, that **** menu how do I add stuff to it?
    Well...that in itself is a hastle but lemme just say, that menu
    is in a nutshell a CommandListener. Same freakin menu. Later on in this post I show how to map the escape key..and i'm guessing pretty much every other key...of course
    the only key I ever had a problem with was the EscapeKey/HangUpKey
    Anyways if you want that BlackBerry Menu Code here
    * MIDletDemo.java
    * Copyright &copy; 1998-2008 Research In Motion Ltd.
    * Note: For the sake of simplicity, this sample application may not leverage
    * resource bundles and resource strings.  However, it is STRONGLY recommended
    * that application developers make use of the localization features available
    * within the BlackBerry development platform to ensure a seamless application
    * experience across a variety of languages and geographies.  For more information
    * on localizing your application, please refer to the BlackBerry Java Development
    * Environment Development Guide associated with this release.
    import java.util.*;
    import java.io.*;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.lang.*;
    * An Example MIDlet.
    * The application must extend the MIDlet class to allow the application management
    * software to control the MIDlet.
    public class MIDletDemo extends MIDlet implements CommandListener
        private Alert _alert;
        private int _time;
        private Form _form;
        private myCanvas customCanvas;
        private Display _display;
        private UpdateThread _updateThread;
         * The thread that updates the explosion dialog box.
        private class UpdateThread extends Thread
            private boolean _disarmed;
            public void run()
                _disarmed = false;
                int i = _time;
                while (i > 0 && !_disarmed)
                    try
                        _alert.setString(Integer.toString(i));
                        synchronized(this)
                                this.wait(1000);
                        System.out.println("timeout in:" +i);
                    catch(InterruptedException e)
                        System.out.println("MyMidlet: Exception: " + e);
                    i--;
                if(!_disarmed)
                    _alert.setString("BOOM");
            void disarm()
                _disarmed = true;
         * Thread that pops up the program's main dialog box.
        private class GoCommand extends Command implements Runnable
            private GoCommand(String label, int type, int priority)
                super(label, type, priority);
            public void run()
                _alert.setString(Integer.toString(_time));
                _alert.setTimeout(_time * 1000 + 5000);
                _updateThread = new UpdateThread();
                _updateThread.start();
                _display.setCurrent(_alert, _form);
         * <p>The default constructor. Creates a simple screen and a command with an alert
         * dialog box which pops up when the command is selected.
        public MIDletDemo()
            _alert = new Alert("The Thermonuclear Device has been activated!\nTo disarm the device, dismiss this Alert.\nDevice will detonate in:");
            _alert.setCommandListener(this);
            _time = 10;
            // Create a simple screen.
            _form = new Form("Thermo-Nuclear Event");
          _form.append("Choose 'Go' from the menu.");
         customCanvas = new myCanvas();
            _display = Display.getDisplay(this);
            // Add our command.
            //_form.addCommand(new GoCommand("Go", Command.SCREEN, 1));
    customCanvas.addCommand(new GoCommand("Go", Command.SCREEN, 1));
    customCanvas.setCommandListener(this);
            //_form.setCommandListener(this);
            _display.setCurrent(customCanvas);
        //_display.setCurrent(_form);
        public void commandAction(Command c, Displayable s)
            if ( c instanceof Runnable )
                ((Runnable)c).run();
            if( c == Alert.DISMISS_COMMAND )
                _updateThread.disarm();
            _display.setCurrent(playerGUI);
         * <p>Signals the MIDlet that it has entered the Active state.
        public void startApp()
            // Not implemented.
         * <p>Signals the MIDlet to stop and enter the Pause state.
        public void pauseApp()
            // Not implemented.
         * <p>Signals the MIDlet to terminate and enter the Destroyed state.
         * @param unconditional When set to true, the MIDlet must cleanup and release all
         * resources. Otherwise, the MIDlet may throw a MIDletStateChangeException to
         * indicate it does not want to be destroyed at this time.
        public void destroyApp(boolean unconditional)
            // Not implemented.
    }now keep in mind, I took this from a nice little example MIDlet called DemoMidlet inside the BlackBerry JDE
    so it's not like they didn't make an effort. I mean I pretty much took it out of their examples located in
    C:\Program Files\Research In Motion\BlackBerry JDE 4.6.0\samples\com\rim\samples\device\midletdemo
    but lets face it...some of us like to use the Canvas Class...so showing us how to use it with a Form not exactly helpful.
    All I did was the same thing it's just I made a canvas, and implemented the CommandListener, then swapped their form for my canvas.
    It freaking worked like a charm. I mean I didn't really use that alert stuff...as it wasn't necessary, but it's a nice demo to learn from.
    Part 2: The Escape Key!
    The first and only problem I noticed when porting over to the blackberry was the lack of certain keys
    that I truly enjoy and need. I guess blackberry decided to just not implement them
    into the MIDlet canvas class?
    I mean they did a great job at figuring out how to map the entire qwerty keyboard, but when it comes to the Escape Key
    good luck!
    So after tearing my hair out I found a solution...which i'm guessing everyone else also found but i'm posting this
    cuz well..what if you're tearing your hair out right now...calm down take a deep breaths this is currently working on the BB 9000
    jde emulator.
    First of all I know this sucks but if you want to use that lovely escape key you're going to have to implement the BB KeyListener.
    I know WTF MAN!? "first i code the whole thing using keylistener/commandlistener now I gotta use some stupid BB KEYLISTENER!?...just who does blackberry think they are?"
    well heres the thing, I tore my hair out for like 12 hours straight trying to get around this...but after giving it a rest it's not such a big deal.
    Steps
    1) you have to grab the blackberry net_rim_api, and add it to your wireless toolkit.
    the path is:
    C:\Program Files\Research In Motion\BlackBerry JDE 4.6.0\lib\net_rim_api.jar
    what I did was copied the file and pasted it into
    C:\WTK2.5.1\lib\ext
    once you have that inside your ext folder in your project settings you can enable the external package, this way you can build
    using the RIM API.
    in case you wanta take a glance at that headache it's : http://www.blackberry.com/developers/docs/4.5.0api/index.html
    to enable it simply open up wtk, go to project/settings/External API's and check it off...take note that the wtk 2.5 generally comes with
    Nokia SNAP Mobile API so i'm guessing it's a normal thing to do with MIDlets. Also if you check off Bundle..that's not too good it includes the API
    with your package...which is really only helpful if you're trying to include some of that junk which really isn't necessary as the reason we're doing this in the first
    place is cuz blackberry wanted to be cool and have their own proprietary keys....
    Anyways check that off and continue to step 2.
    Implementing Key Listener with the Canvas Class! :-)
    2) This part is so easy...
    import java.io.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    import net.rim.device.api.system.*;
    public class myCanvas extends Canvas implements CommandListener,KeyListener{
    String thekey = "no key pressed yet";
      public myCanvas() {
    Application.getApplication().addKeyListener(this);
    public void paint(Graphics g){
    g.setColor(255,255,255);
    g.fillRect(0,0,500,500);
    g.setColor(0,0,0);
    g.drawString(thekey,0,0,Graphics.TOP|Graphics.LEFT);
    public boolean keyDown(int keycode, int time)
                    thekey = String.valueOf(keycode);
                    repaint();
                return false;
            public boolean keyRepeat(int keycode, int time)
                 return false;
            public boolean keyStatus(int keycode, int time)
                  return false;
            public boolean keyUp(int keycode, int time)
                   return false;
      public boolean keyChar(char key, int status, int time) {
          if (key == Characters.ESCAPE)
             return false;
    public void commandAction(Command c, Displayable s)
      ///YOU DON'T NEED THIS! I just left it here, in case you wanted to also use the blackberry menu to do stuff...in this case
    //well the command is shown...and it calls the run method of the class you add the command to. My previous example
    // used the command GO, and i made a private class...so this would cause the run method to execute when the user hits enter on go.     
         // if ( c instanceof Runnable )
              //  ((Runnable)c).run();
    }i'm gonne be honest with you, the function public boolean keyChar()
    I don't know if that actually works...I just don't want to recompile without it cuz I just got over this headache..so I left it there.
    According to most people you use that to check if the key == Characters.ESCAPE and if it does then you do some stuff.
    Also you don't need the command listener, I just left it in there because well..if you're like me and you use the blackberry menu, you're pretty much
    going to use the CommandListener on your canvas to check to see if the user hit enter on a menu item.
    The function that matters here, is the same function Midlet coders are used to.
    instead of keyPressed it's simply keyDown
    so basically you're importing the package
    import net.rim.device.api.system.*;
    which allows you to implement blackberry's keyListener which gives you access to all the keys vs. a limited amount of them.
    now blackberry went all out as you can see. You have to have keyDown, keyUp, keyRepeated...it's kinda rediculous.
    but no worries, as long as you make sure that Display.setCurrent(yourcanvas);
    or you use one of those to give the canvas control...you'll be fine.
    It works because in the method for creating myCanvas()
    or whatever canvas you'll be using, it calls Application.getApplication.addKeyListener(this);
    and that little command gives your canvas the ability to listen for blackberry keys such as escape.
    the current code will start displaying the keycodes for each key...and apparently keys such as ESCAPE
    can be labeled properly. I love this because I can map the hang up call key to destroy my midlet, or even the escape key.
    Unfortunately every keycode displayed is in like unicode or some stupid format, so that's my guess as to why the Escape key is not detected by the normal
    canvas keyPressed method.
    Anyways you're done this should work...now if you're having trouble using canvas and you're like "but I don't use canvas" idk man...
    I use canvas...cuz I think programs should look cool. I'm sure this works without the canvas...on a form or something.
    But don't be fooled, you're not limited to KeyListener, you can also use TrackWheelEvent and all kinds of stuff. So just like the choices for CommandListener vs. keyPressed
    Blackberry has other choices as well.
    And they said merging the API's was a bad idea...shucks, how else are we supposed to use the freaking escape key.
    --JavaLover53
    P.S. I marked this as a question cuz I want people to really take a look at this. Make some comments, I love this forum
    and I really feel that this topic is not covered on the internet. A lot of naysayers, and when I found the solution I was like "that's it"
    "that's all I had to do?" "well then wheres the freaking tutorial!
    seriously people had me thinking I had to extend the blackberry UI when this is all I had to do..such an easy task
    that other people claim is ridiculously hard.
    Go ahead make your comments, lemme know if you know something I don't, i'm here to learn! :-)

    good writeup, however i found this only working when you're not running fullscreen

  • Set default Button and provide a KeyEvent to a component with focus !!!

    What is to do ???
    I have following program:
    public class DefaultButton extends Frame implements ActionListener
         private Button close;
         public DefaultButton()
              super("Default-Button");
              setLayout(null);
              setSize(400, 200);
              setLocation(150, 100);
              setBackground(Color.lightGray);
              addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        setVisible(false);
                        dispose();
                        System.exit(0);
              // CloseButton
              close = new Button("Close");
              close.addActionListener(this);
              close.setVisible(true);
              close.setSize(100, 30);
              close.setLocation(290, 160);
              add(close);
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              String cmd = e.getActionCommand();
              if (cmd.equals("Close"))
                   setVisible(false);
                   dispose();
                   System.exit(0);
         public static void main(String [] args)
              DefaultButton wnd = new DefaultButton();
    }If I click on "Close"-button, the window will be closed. But, if the button "Close" has focus, it schold be possibile to close the window with a press on the Enter-Key? How to do it? How can I provide an KeyEvent to button "Close"?
    Tanks for any help.

    Hi pitalica!
    It is possible using KeyListener:
    public class DefaultButton extends Frame implements ActionListener, KeyListener {
    close.addKeyListener(this);
    public void keyPressed(KeyEvent e) {
    if ((e.getSource() instanceof Button)
    && (((Button) e.getSource()).getActionCommand == "Close")) {
    int kc = e.getKeyCode();
    if (kc == KeyEvent.VK_ENTER) {
    performs any action
    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}
    I hope it helps.

  • Max number of characters in a JTextField

    I don't want to alowe more than 4 characters in a JTextField.
    Is where any method in Java corresponding to maxlength for textbox in Visual Basic??
    Or do I have to use KeyListener to check the situation for every key pressed?
    I'll be thankful for any help.

    write your own document & override the insertString() like the one below:
    import javax.swing.text.*;
    public class MyDocument extends PlainDocument {
         public void insertString(int offs, String s, AttributeSet a)
                                                          throws BadLocationException {
              if(getLength() > 4)
              //if(offs > 3)
              //if(getText(0, getLength()).length() > 4)
                   return;
              else
                   super.insertString(offs, s, a);            
    }

  • Non-Blocking call to read the Keyboard

    does anyone know how to make a JAVA program make a non-blocking call to read the keyboard? eg. write a program which generates prime number until a keyboard key is pressed.

    if you use a gui you can use keyListener
    Would work only if your gui elements have focus right now.

  • Global Event Handling

    I am writing a program that needs to detect keystrokes and mouseclicks globally. Right now I am using KeyListener and MouseListener to keep track of all keystrokes and mouseclicks, but that only handles keystrokes and mouseclicks in the window of my application. How can I detect global keystrokes and mouseclicks? I want to be able to open another Windows application (say Notepad) and have my application detect all the keystrokes occuring within that application.
    Thanks

    You will need to research native methods in order to do this. Essentially you will have to have the OS inform your application of these events.

  • KeyEvent on dynamically generated Buttons

    hi,
    I have an app, which builds <n> number of buttons reading from an XML file.
    Below is the code that generates the buttons
         for (int i=0; i<strBtnValue.length; i++) {
            btn[i] = new Button(strBtnValue[1]);
    btn[i].setForeground(getColor(strBtnForeground[i][1]));
    btn[i].setBackground(getColor(strBtnBackground[i][1]));
    btn[i].setBounds(intX_btn, intY_btn, intW_btn, intH_btn);
    intX_btn = intX_btn + 140;
    btn[i].setFont(strBtnFont);
    btn[i].addKeyListener(this);
    add(btn[i]);
    public void keyReleased(KeyEvent e) {
    int keyCode = e.getKeyCode();
    if (keyCode == 68) { // key D is pressed
    System.out.println("Released D");
    }I need to assign 'keyboard D' to a button.  And when 'D' is pressed, i want to get the attributes for that button.  Could anyone shed some light ? Let me if this is not a clear explanation.
    Thanks in advance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    In the future Swing questions should be posted to the Swing forum: http://forum.java.sun.com/forum.jspa?forumID=57
    Your mistake is that you are using KeyListener - this is only valid if you want to listener to the keyboard when the component has focus.
    Instead, you should set a mnemonic: http://java.sun.com/javase/6/docs/api/javax/swing/AbstractButton.html#setMnemonic(int)
    Or work with keyboard bindings: http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html

  • ActionListener not being heard

    Hi. I have a familiar "OK - Cancel" panel on a particular JPanel. I have added an actionListener to the OK and Cancel buttons so that when we click on them it takes the appropriate action.
    However, when I tab into the Ok or cancel button and press the Enter key the actionListener is not getting fired at all. I was under the impression the actionlistener would accomidate for both mouse clicks and manually pressing enter once the button had focus.
    It works perfectly for the mouse-clicks but not for the enter key.
    Any insight?
    Regards,
    Wal

    Hi!
    This is the listener you can use:
    KeyListener EnterButtonListener = new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ENTER)
    if(e.getSource() == button)
    button.doClick(); // or the click-code itself.
    Best Regards
    Javamannen, Sweden

  • Cannot pop up sms editor on Nokia N97

    The Nokia N97 is a Symbian S60 v5 phone like the Nokia 5800 XpressMusic.
    We use the following simple script on the 5800 to pop up the SMS editor, but it does not work on the N97. Nothing pops up - strange.
    on(Release)
        getURL('sms:?body=abc');
    Is this a bug on the Flash Lite implementation on the N97? The phone we used was new.
    Thanks in anticipation.
    jz

    Hi Alessandro,
    Our current solution is that:
    For mobile phones like 5800, n97,n97 mini ...etc. we now use nokia library to popup sms editor. This is not ideal as we have to populate the "To: field" otherwise it does not work. For all others, we use getURL to popup the sms editor and it's a great solution. The n97 was the problem phone as getURL worked for the 5800.
    Our engineers response was as follows:
    "I think what he means is whether I put the getURL code inside on(press) instead of on(release).
    At this time, I check that I use keylistener's keydown/keyup event in our semobile application and use on(release) in testing program.
    I can't remember whether we tested some codes using on(release) before. But it's quite unbelievable that only on(press) works instead of others although we can try it."
    Our applications are at www.stockexpress.com.hk/mobile
    Best regards,
    Roger Durn

  • Hiding and Unhiding an application GUI

    Hello,
    Is there any way to hide and unhide an application gui using KeyListener?
    We have an application that we can start up in "quiet" mode (ie not show the gui) and we would like to be able at some time to press a certain key combination (something like ctrl-s) and have the GUI display itself.
    I guess the first question is whether or not something like this is possible.
    We have a main line that instantiates the Gui class. So the GUI is not a part of the main class. ie in our main we have something like :
    import gui;
    class mainClass {
    public void main(String[] args) {
    boolean quietMode = false;;
    for (int i; i<args.length; i++) {
    if (args.equals("-q") {
    quietMode = true;
    Gui theGui = new GUI();
    theGui.pack();
    if (!quietmode) {
    theGui.setvisible(true);
    ... etc etc
    How would one attach a KeyAdapter or KeyListener, ensure the focus and enable the ctrl-s display gui functionality. Is this at all possible?
    We are running on Linux Red Hat 7.2 using JDK1.3.1_01.
    Thanks for any answers you may be able to provide.

    Sorry to say it is not possible because your listeners are registered in your app not your os
    I guess you have to use jni or something to access your os to read key/mouse inputs

  • Working With Image

    Hi,
    How to write a code by using keylistener to delete the key component in java

    What do you mean by "key component?" What do you mean by "delete?" What does this have to do with Image?

Maybe you are looking for