KeyPressed/KeyTyped/KeyReleased

I have a JDialog (2 JTextFields and 2 JButtons) that needs to respond to the <enter> key the same way that it should respond when the user clicks the 'OK' button on the same dialog (both actions result in running a report that displays in another window). The first time the dialog is opened and the user presses the <enter> key, all appears fine. Subsequent openings of the dialog and pressing the <enter> key produce multiple copies of the same report (i.e. the second time in, 2 reports are created. The third time in, 3 reports are created. etc). This does not happen when the user clicks the 'OK' button on the dialog...it produces one report each time (as it should).
I have key listeners on both JTextFields so that the user can press <enter> at any time while in the dialog to create the report. The key listener (KeyAdapter) method I originally coded was the keyReleased. I check for the <enter> key being pressed, and run code so that it will produce the report. I've attempted to consume the event within all 3 methods of the KeyAdapter, but with no luck.
Is this a good approach? What suggestions do you have to correct this problem?
Thanks,
Van Williams

Fixed my own problem. Decided not to use the key listeners on the text fields. Using JRootPane, decided to set the default button (which is really what I wanted), and this works fine.
Van Williams

Similar Messages

  • Overwriting the keyPressed() and keyReleased()methods within a TextBox

    Dear All,
    I have written a simple predictive text midlet by overwriting the keyPressed() and keyReleased() methods (found in the TextBox class). This is fine and works perfectly when I emulate the midlet on my pc. However, when I transfer the midlet to my mobile, the existing predictive text system takes over and as my midlet acts only as a standard TextBox. Is I turn off prediction, then the TextBox acts as if I had not overwritten those methods! Does anybody know how to stop this from happening?
    Many thanks in advance
    David Fowler

    David,
    I think something is going wrong in your code, 'cause the TextBox doesn't provide the key listener methods that you have overwritten..these methods are declared in the Canvas class..
    May you show some code to let me see what are you program really doing?
    Ricardo

  • KeyPressed and KeyReleased on canvas

    Dear programmers
    I'm nearing the final stages of my remote desktop pet project but have a few small issues. One of them is that I can't seem to capture key events when the cursor is over the canvas. My system is in 2 parts.
    1 - Server which listens to events.
    2 - Client(Applet) which adds a canvas.
    How would I capture key events while the mouse cursor is on the canvas? Below is the code so far.
    public void keyPressed(KeyEvent e)
    int KeyCode = e.getKeyCode();
    pw.println(KEYD + KeyCode);
    where pw is PrintWriter.

    import java.awt.event.*;
    import java.awt.*;
    public class Test extends Frame {
      boolean mouse;
      public Test() {
        Canvas c = new Canvas();
        c.addMouseListener(new MouseAdapter() {
          public void mouseEntered(MouseEvent me) { mouse=true; }
          public void mouseExited(MouseEvent me) { mouse=false; }
        c.addKeyListener(new KeyAdapter() {
          public void keyPressed(KeyEvent ke) {
         if (mouse) System.out.println("key="+ke.getKeyCode());
        add(c);
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent we) { System.exit(0); }
        setSize(100,100);
        show();
      public static void main (String args[]) { new Test(); }
    }

  • Handling KeyEvent (filtering KeyEvents)

    I am writing a code to learn how KeyEvents behaves and how to manipulate and even filtering some events, for example, to filter the normal behaviour of keeping pressed a key that fires a KeyPressed -> KeyTyped -> KeyReleased Events, like pressing the 'a' button, and keeping it pressed, this fires the sequence expressed before as long as the button is keeped pressed.
    From the writing a KeyListener tutorial, (http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html), i've begin to make some tests and changing somethings around the code, but, i am not getting too far as I want to make the 'keeping pressed' behaviour as just one event, the KeyPressed, and only when the user release the key, the KeyReleased Event should be fired.
    In resume, i just want to make any keystroke to be mapped as a modifier key, such as Shift or Control, because i will need a program which only responds with a character to the user, when he releases the key and not just like the KeyTyped Event.
    I am not a programmer, i am just a psychology student who wants to learn about Java programming language and try to apply it to some ideas about how to gather information about the behaviour of people when it's method of interact (virtually) is the keyboard realm.
    Is there anything out there to help me on this trail of learning how to manipulate KeyEvents?
    Thanks in advance, and sorry for the poor english.

    Hi,
    This is a bit of a hack but works nicely. Substitute the keyPressed, KeyReleased and keyTyped methods with the following:
        /** Handle the key typed event from the text field. */
        public void keyTyped(KeyEvent e) {
        //    displayInfo(e, "KEY TYPED: ");
        /** Handle the key pressed event from the text field. */
        public void keyPressed(KeyEvent e) {
            if(key != e.getKeyChar()) {
                displayInfo(e, "KEY PRESSED: ");
                key = e.getKeyChar();
        /** Handle the key released event from the text field. */
        public void keyReleased(KeyEvent e) {
            displayInfo(e, "KEY RELEASED: ");
            key = ' ';
        }and declare a char as a class varible like this:
    // ... import statements here
    public class KeyEventDemo extends JPanel
                              implements KeyListener,
                                         ActionListener {
        JTextArea displayArea;
        JTextField typingArea;
        static final String newline = "\n";
        // This is where you'll put the char.
        char key;
        public KeyEventDemo() {
            super(new BorderLayout());
            // ... the rest of the class

  • Can't get the keys to run anything...

    Yeah, so I've literally spent the past two days trying to figure out how to get the keys to make stuff move in my game. I've already gotten the computer players to move around, implemented a collision detection system of sorts, and written the methods that will facilitate movement in the main person when called.
    Here's my problem. I've been looking at several tutorials, and I see two primary ways of doing this. One, key binding, which I've been persuing more heavily, apparently requires use of a component. As of yesterday I didn't know what a component was, and since I've discovered that this method, in fact, requires an object that is a JComponent, which I don' t have in my program (I have a JFrame, but that's just a component). I was considering just slapping some random one in there, but I don't know how to set the key reading thing to do stuff even when the component is not selected. And I also think it would be sort of stupid to put superfluous stuff like that in my program.
    The other method had tons of parameters and I really had no idea where they would all come from.
    So, any suggestions?

    in your main method or whatever put
    addKeyListener(myKeyHandler())
    // this class has 3 methods in java, keyPressed, keyTyped, keyReleased
    myKeyHandler extends KeyAdapter
    public void keyPressed(KeyEvent e)
    int key = e.getKey//or something like that
    if(key == VK.W)
    up = true;
    repaint();
    else if(key == VK.S)
    down = true;
    repaint();
    // if necessecary
    try{ Thread.sleep(howeveramount)} catch(Exception f)
    paint
    if (up == true)
    yPosition++
    g.draw(thing);
    else if(down == true)
    yPosition--
    g.draw(thing);
    Edited by: nik7_7 on Apr 19, 2008 7:07 PM

  • Snake applet help

    this snake doesnt eat!(i.e. its length doesnt increase and the food doesnt go away when it eats. not to mention it doesnt even get to the food point)
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    /* class SnakeGamez
    Fields
    Thread t
    double speed speed of the snake
    int food food value
    boolean eating returns if snake is eating or not
    Snake s the Snake field
    Graphics g Graphics Object
    Methods
    init- initializes window size, sets thread to null, adds key listener, calls reset() and run()
    reset- resets the SnakeGame Applet
    drawGrid- draws the grid that the snake stays inside of
    keyPressed-
    keyTyped
    keyReleased
    public class SnakeGame extends Applet implements KeyListener, Runnable
    Thread t;
    double speed;
    int food;
    protected Snake s;
    protected Graphics g;
    protected Color c;
    /* method void
    "main" program, that controls the game, calling methods to move the snake.
    parameters:none
    returns:none(void)
    public void run ()
         food = 0;
         boolean eating = false;
         char x = 'a';
         g = getGraphics ();
         int theX;
         int theY;
         theX = (int) (Math.random () * 300) + 5;
         theY = (int) (Math.random () * 400) + 5;
         // sp foodP = new sp (theX, theY);
         sp foodP = new sp (0, 0);
         while (s.alive ())
         if (food == 0)
              do
              theX = (int) (Math.random () * 300) + 5;
              theY = (int) (Math.random () * 400) + 5;
              // theX = (int) (Math.random () * 490) + 5;
              //theY = (int) (Math.random () * 490) + 5;
              foodP = new sp (theX, theY);
              while (s.onSnake (foodP));
              food = (int) (Math.random () * 9) + 1;
         System.out.println (theX + " " + theY + "SN" + s.head.p.x + "SY" + s.head.p.y);
         // g.clearRect (10, 10, 270,360); ONE VALUE IS CORRECT.
         /* problem snake is NOT clear in left side.
         //g.clearRect (10, 10, 270, 350);
         g.clearRect (10, 10, 270, 350);
         if (eating)
              System.out.println ("AM I EER GONNA EAT!@");
              s.grow ();
              food--;
         else
              s.move ();
              g.setColor (Color.red);
              g.drawString ("" + food, theX, theY);
         //System.out.println (s.head.p.x);
         if (food == 0)
              eating = false;
         // if (s.head.p.equals (foodP))
         if (s.head ().equals (foodP))
              eating = true;
              for (int n = 0 ; n < 5 ; n++)
              s.draw (g);
         // else
         //System.out.println(foodP.x + " " + foodP.y + " "+ s.head.p.x + " " + s.head.p.y);
         //g.clearRect (200, 500, 200, 700);
         // g.clearRect (200, 550, 200, 700);
         // g.clearRect (5, 300, 5, 380);
         g.clearRect (1, 375, 700, 390);
         g.drawString ("Snake's Length: " + s.length () + " x=speed z=slow", 9, 385);
         for (int i = 0 ; i < 5 ; i++)
              s.draw (g);
         for (double delay = 0 ; delay < speed ; delay++)
         g.setColor (Color.orange);
         g.drawString ("Snake is dead =( Press 's' to restart.", 50, 50);
    public void init ()
         setSize (300, 400);
         t = null;
         s = new Snake ();
         g = getGraphics ();
         speed = 10000000;
         addKeyListener (this);
         reset ();
         run ();
    public void reset ()
         speed = 10000000;
         s = new Snake ();
         g.clearRect (0, 0, 300, 400);
         drawGrid ();
         if (t != null)
         t.stop ();
         t = new Thread (this);
         t.start ();
    public void drawGrid ()
         g = getGraphics ();
         int Locx = 0;
         int Locy = 0;
         int Locx1 = 650;
         int Locy1 = 0;
         c = Color.green;
         g.setColor (c);
         while (Locx < 300)
         sp x = new sp (Locx, Locy);
         Locx++;
         g.drawRect (Locx * 10, Locy * 10, 9, 9);
         Locx = 0;
         while (Locy < 300)
         sp x = new sp (Locx, Locy);
         Locy++;
         g.drawRect (Locx * 10, Locy * 10, 9, 9);
         Locy = 0;
         while (Locy < 300)
         sp x = new sp (Locx, Locy);
         Locy++;
         g.drawRect (280, Locy * 10, 9, 9);
         Locx = 0;
         while (Locx < 300)
         sp x = new sp (Locx, Locy);
         Locx++;
         g.drawRect (Locx * 10, 360, 9, 9);
         // Locx = 0;
         // Locy1 = 0;
         // while (Locy1 < 700)
         // sp x = new sp (Locx, Locy);
         // Locy++;
         // g.drawRect (Locx * 10, Locy * 10, 9, 9);
    public void keyPressed (KeyEvent e)
         int k = e.getKeyCode ();
         if (k == KeyEvent.VK_DOWN)
         s.changeDirection ('D');
         else if (k == KeyEvent.VK_UP)
         s.changeDirection ('U');
         else if (k == KeyEvent.VK_LEFT)
         s.changeDirection ('L');
         else if (k == KeyEvent.VK_RIGHT)
         s.changeDirection ('R');
    public void keyTyped (KeyEvent e)
         char k = e.getKeyChar ();
         if (k == 's')
         reset ();
         else if (k == 'z')
         speed += 100000;
         else if (k == 'x')
         speed -= 100000;
    public void keyReleased (KeyEvent e)
    } // Snake class
    class SnakeNode
    sp p;
    SnakeNode next;
    public SnakeNode ()
         //IT MUST BE SET TO SOMETHING, BECAUSE 'never empty'? or maybe because always length 5..
         next = null;
         p = null;
    public SnakeNode (sp z)
         p = z;
         if (z.direction == 'D')
         next = new SnakeNode (z.down ());
         else if (z.direction == 'U')
         next = new SnakeNode (z.up ());
         else if (z.direction == 'L')
         next = new SnakeNode (z.left ());
         else if (z.direction == 'R')
         next = new SnakeNode (z.right ());
         next = null;
    /* class sp(SnakePoint Class)
    class sp
    int direction;
    int length;
    int x;
    int y;
    public sp (int x, int y)
         this.x = x;
         this.y = y;
    public int lengthR ()
         return length;
    public sp up ()
         return new sp (x, y - 10);
    public sp down ()
         return new sp (x, y + 10);
    public void plot (Graphics g, Color c)
         g.setColor (c);
         g.fillRect (x, y, 10, 10);
         // g.fillRect (x, y, 9, 9);
         // g.drawRect (x, y, 9, 9);
         // g.fillRect (x, y, 9, 9);
         // g.fillRect (x * 10, y * 10, 9, 9);
         //g.fillRect (100, 100, 9, 9);
    public sp left ()
         return new sp (x - 10, y);
    public sp right ()
         return new sp (x + 10, y);
    public int getX ()
         return x;
    public int getY ()
         return y;
    public boolean equals (sp s)
         return s.x == x && s.y == y;
    class Snake
    SnakeNode tail;
    SnakeNode head;
    char direction;
    int length;
    public Snake ()
         sp q = new sp (100, 100);
         add (q);
         head.p = q;
         q = q.down ();
         add (q);
         q = q.down ();
         add (q);
         q = q.down ();
         add (q);
         q = q.down ();
         add (q);
         q = q.down ();
         direction = 'D';
         length = 5;
    public void draw (Graphics g)
         SnakeNode k = tail;
         while (k != head)
         k.p.plot (g, Color.red);
         k = k.next;
         head.p.plot (g, Color.blue);
    public boolean add (sp s)
         length++;
         SnakeNode newNode = new SnakeNode (s);
         newNode.next = null;
         if (empty ())
         tail = newNode;
         head = newNode;
         else
         head.next = newNode;
         head = newNode;
         return true;
    public void grow ()
         if (direction == 'D')
         add (head.p.down ());
         else if (direction == 'U')
         add (head.p.up ());
         else if (direction == 'L')
         add (head.p.left ());
         else if (direction == 'R')
         add (head.p.right ());
    public sp remove ()
         sp q = new sp (0, 0);
         if (!empty () && tail.next != null)
         q = tail.p;
         tail = tail.next;
         length--;
         return q;
    public void changeDirection (char s)
         direction = s;
    public int length ()
         return length;
    public sp head ()
         return head.p;
    public boolean empty ()
         return tail == null && head == null;
    public boolean onBody (sp q)
         SnakeNode k = tail;
         while (k != null && k != head)
         if (k.p.equals (q))
              return true;
         k = k.next;
         return false;
    public boolean onSnake (sp q)
         SnakeNode k = tail;
         if (q.equals (head.p))
         return true;
         while (k != null && k != head)
         if (k.p.equals (q))
              return true;
         k = k.next;
         return false;
    /* method alive
    returns:boolean, true if snake is within bounds, and head is not on the body
    public boolean alive ()
         if (!(head.p.getX () >= 5 && head.p.getY () >= 5 && head.p.getX () <= 270 && head.p.getY () <= 350))
         return false;
         else
         SnakeNode l = tail;
         while (l != head.next && l.next != null)
              if (l.p.equals (head.p))
              return false;
              if (l.next != null)
              l = l.next;
         return true;
    public void move ()
         grow ();
         remove ();
    }

    this snake doesnt eat!(i.e. its length doesnt
    increase and the food doesnt go away when it eats.
    not to mention it doesnt even get to the food point)
    (whole freakin' application (unformatted to boot) omitted)So what do you expect here? Someone to analyze your stuff for you and fix it? Wrong!

  • KeyTyped events not generated

    I've got a JTextArea. I wanted to allow focus traversal with standard TAB keys, so I provided a KeyListener that consumes TAB events. The problem is, that if I shift-tab to my textArea (it's placed in a JPanel), the first pressed key is ignored.
    After a little investigation it turns out, that for the very first key pressed after the JTextArea has gained focus no keyTyped event is generated - only keyPressed and keyReleased. Why is that? Why does it happen only after shift-tabbing to the JTextArea (tabbing to it does not produce this strange behaviour)?
         textArea.addKeyListener(new KeyAdapter() {
                   @Override
                   public void keyPressed(KeyEvent e) {
                                  if (e.getKeyCode() == KeyEvent.VK_TAB && (e.getModifiers() == 0 || e.getModifiers() == KeyEvent.SHIFT_MASK)) {
                             if (e.getModifiers() == KeyEvent.SHIFT_MASK) {
                                  textArea.transferFocusBackward();
                             } else {
                                  textArea.transferFocus();
                             e.consume();
                   }

    You might have better luck getting a helpful response if you create a Short, Self Contained, Correct (Compilable), Example or SSCCE. This is a small application that you create that is compilable and runnable, and demonstrates your error, but contains no extraneous, unnecessary code that is not associated with your problem. To see more about this and how to create this, please look at this link:
    http://homepage1.nifty.com/algafield/sscce.html
    Remember, this code must be compilable and runnable.
    I tried to create one of my own but could not reproduce your problem:
    import java.awt.GridLayout;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    class SwingFoo1 extends JPanel
        JTextArea[] textAreas = new JTextArea[3];
        SwingFoo1()
            setLayout(new GridLayout(0, 1));
            for (int i = 0; i < textAreas.length; i++)
                JPanel panel = new JPanel();
                JTextArea textArea = new JTextArea(5, 60);
                JScrollPane scrollpane = new JScrollPane(textArea);
                panel.add(scrollpane);
                add(panel);
                textAreas[i] = textArea;
                final int iFinal = i;
                textArea.addKeyListener(new KeyAdapter()
                    @Override
                    public void keyPressed(KeyEvent e)
                        if (e.getKeyCode() == KeyEvent.VK_TAB
                            && (e.getModifiers() == 0 || e.getModifiers() == KeyEvent.SHIFT_MASK))
                            if (e.getModifiers() == KeyEvent.SHIFT_MASK)
                                textAreas[iFinal].transferFocusBackward();
                            else
                                textAreas[iFinal].transferFocus();
                            e.consume();
            JPanel buttonPanel = new JPanel();
            JButton fooButton = new JButton("Foo");
            buttonPanel.add(fooButton);
            add(buttonPanel);
        private static void createAndShowGUI()
            JFrame frame = new JFrame("SwingFoo1 Application");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new SwingFoo1());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }

  • KeyTyped(KeyEvent) consumes CTRL key actions

    hey there,
    using a single CTRL key the method "keyTyped()" will never be called, why? Is there anything, that consumes the event before the method is called? I'd like to do without the tow methods keyPressed() and keyReleased(). Visiting the component sources didn't help.
    thx in advance!
    -hostmonsta

    Hi,
    You can override the processKeyEvent(KeyEvent e)
    method of your control to get the CTRL keystroke.
    protected void processKeyEvent(KeyEvent e)
    super.processKeyEvent(e);
    if(e.getID() == KeyEvent.KEY_PRESSED)
    if(e.getKeyCode() == KeyEvent.VK_CONTROL)
    // do your logic

  • Keypressed() only working with 'cancel' key

    Hi! Good Day! I am trying to make a game using the gameCanvas class, everything is fine except when I try to use the keyPressed() event so that I could evaluate what keys where pressed, unfortunately only the 'Cancel' key works on my program.
    I am using J2ME wireless toolkit to build and run my program. Please help, Ive searched everywhere and all I see is sample code, but when I try to use keyPRessed() it still doesnt work the way its suppose to be. Thank you. Here's my code:
    import javax.microedition.lcdui.*;
    import javax.microedition.lcdui.game.*;
    public class WatchaWordCanvas extends GameCanvas implements Runnable {
      private boolean isPlay;   // Game Loop runs when isPlay is true
      private long delay;       // To give thread consistency
      private int currentX, currentY;  // To hold current position of the 'X'
      private int currentLocation;
      private boolean[] selectedBog = new boolean[16];
      private int staticX, staticY;
      private int bogposX, bogposY;
      private int width;        // To hold screen width
      private int height;       // To hold screen height
      private int[] bogArray = new int[16];
      private String[][] alphaMatrix = new String[4][4];
      private int ldelay, rdelay, udelay, ddelay;
      // Sprites to be used
      private Sprite playerSprite; 
      private Sprite backgroundSprite;
      private Sprite bogCubesSprite1;
      private Sprite[] bogCubesSprite = new Sprite[16];
      private Sprite bogBackGround;
      private Sprite bogTitleGround;
      private Sprite bogWordBar, bogMenuBar;
      private int dCtrA;
      // Layer Manager
      private LayerManager layerManager;
      // Constructor and initialization
      public WatchaWordCanvas() throws Exception {
        super(true);
        width = getWidth();   
        height = getHeight();   
        currentX = 0;
        currentY = 0;
        staticX = 2;
        staticY = (height / 2) - 60;
        delay = 20;
        ldelay = 0;
        rdelay = 0;
        udelay = 0;
        ddelay = 0;
        for (dCtrA=0; dCtrA<16; dCtrA++) {
          selectedBog[dCtrA] = false;
        // Load Images to Sprites
        Image playerImage = Image.createImage("/transparent.png");     
        playerSprite = new Sprite (playerImage,32,32);
        Image bogCubesImage = Image.createImage("/watcha-cubesfilled.png");
        bogCubesSprite1 = new Sprite(bogCubesImage,31,29);
        bogCubesSprite1.setFrame(0);
        Image bogBackImage = Image.createImage("/watcha-background2.png");
        bogBackGround = new Sprite(bogBackImage);
        Image bogTitleImage = Image.createImage("/watcha-title.png");
        bogTitleGround = new Sprite(bogTitleImage);
        Image bogWordImage = Image.createImage("/watcha-wordbar.png");
        bogWordBar = new Sprite(bogWordImage);
        Image bogMenuImage = Image.createImage("/watcha-menubar.png");
        bogMenuBar = new Sprite(bogMenuImage);
        for(dCtrA=0;dCtrA< bogCubesSprite.length;dCtrA++) {
          bogCubesSprite[dCtrA] = new Sprite(bogCubesImage,31,29);
          bogCubesSprite[dCtrA].setFrame(0);
        layerManager = new LayerManager();
        layerManager.append(bogTitleGround);
        layerManager.append(bogWordBar);
        layerManager.append(bogMenuBar);
        for(dCtrA=0;dCtrA< bogCubesSprite.length;dCtrA++) {
          layerManager.append(bogCubesSprite[dCtrA]);
        layerManager.append(bogBackGround);
        //Set the Positions of the Images
        bogTitleGround.setPosition(0,0); 
        bogWordBar.setPosition(2,150);
        bogMenuBar.setPosition(129,staticY - 2);
        bogCubesSprite[0].setPosition(staticX, staticY);
        bogCubesSprite[1].setPosition(staticX, staticY + 31);
        bogCubesSprite[2].setPosition(staticX, staticY + 62);
        bogCubesSprite[3].setPosition(staticX, staticY + 93);
        bogCubesSprite[4].setPosition(staticX + 31, staticY);
        bogCubesSprite[5].setPosition(staticX + 31, staticY + 31);
        bogCubesSprite[6].setPosition(staticX + 31, staticY + 62);
        bogCubesSprite[7].setPosition(staticX + 31, staticY + 93);
        bogCubesSprite[8].setPosition(staticX + 62, staticY);
        bogCubesSprite[9].setPosition(staticX + 62, staticY + 31);
        bogCubesSprite[10].setPosition(staticX + 62, staticY + 62);
        bogCubesSprite[11].setPosition(staticX + 62, staticY + 93);
        bogCubesSprite[12].setPosition(staticX + 93, staticY);
        bogCubesSprite[13].setPosition(staticX + 93, staticY + 31);
        bogCubesSprite[14].setPosition(staticX + 93, staticY + 62);
        bogCubesSprite[15].setPosition(staticX + 93, staticY + 93);
      // Automatically start thread for game loop
      public void start() {
        isPlay = true;
        Thread t = new Thread(this);
        t.start();
        SetCurrent();
      public void stop() { isPlay = false; }
      // Main Game Loop
      public void run() {
        Graphics g = getGraphics();
        while (isPlay == true) {
          input();
          drawScreen(g);
          try { Thread.sleep(delay); }
          catch (InterruptedException ie) {}
      public void input() {
        int keyStates = getKeyStates();
        //Left
        if ((keyStates & LEFT_PRESSED) !=0) {
          if (ldelay==0) {
            ldelay++;
            if (currentX > 0 ) { currentX--; }
            //SetCurrent();
        else {
          ldelay = 0;
        // Right
        if ((keyStates & RIGHT_PRESSED) !=0 ) {
          if (rdelay==0) {
            rdelay++;
            if (currentX < 3) { currentX++; }
            //SetCurrent();
        else {
          rdelay =0;
        // Up
        if ((keyStates & UP_PRESSED) != 0) {
          if (udelay==0) {
            udelay++;
            if (currentY > 0 )  { currentY--; }
            //SetCurrent();
        else {
          udelay = 0;
        // Down
        if ((keyStates & DOWN_PRESSED) !=0) {
          if (ddelay==0) {
            ddelay++;
            if (currentY < 3) { currentY++; }
            //SetCurrent();
        else {
          ddelay = 0;
      // Method to Display Graphics
      private void drawScreen(Graphics g) {
        //g.setColor(0x00C000);
        g.setColor(0xffffff);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(0x0000ff);  
        SetCurrent();
        // updating player sprite position
        //playerSprite.setPosition(currentX,currentY); 
        // display all layers
        //layerManager.paint(g,0,0);       
        //layerManager.setViewWindow(55,20,140,140);  
        layerManager.paint(g,0,0);
            bogCubesSprite[0].setPosition(staticX, staticY);
        flushGraphics();
      //Method to highlight cubes
      public void SetCurrent() {
        //some codes for my program
    }Thanks in advance

    Instead of the thread - Implement the keyPressed() and keyReleased() methods to keep track of events.
    Regards,
    Muthu Veerappan

  • Problem with my keyReleased method in KeyListener

    Hey all, I heard this was the place for these kinds of questions.
    OK so a bit ago I created my own class KeyEventListener that implements KeyListener.
    I just recently got it to work and it does in fact get input from the keyboard.
    private class KeyEventListener implements KeyListener
          boolean right=false;
          public void keyPressed(KeyEvent e)
             if(!right)
             System.out.println("Pressed");
             //right=true;
          public void keyReleased(KeyEvent e)
             //right=false;
             System.out.println("Released");
          }So anyway, for testing reasons I added those System.out.println().
    Anyway, here is where I noticed the problem, when a key is held down, this is the output:
    Pressed
    Released
    Pressed
    Released
    Pressed
    Released
    Pressed
    Released
    Pressed
    Released
    Pressed
    Released
    Pressed
    ReleasedSo apparently when a key is held down the method keyPressed and keyReleased are called over and over again.
    I would have expected the keyPressed method to be called multiple times but not the keyReleased to be called.
    Which makes this quite the problem. I only want one thing to happen when the key is pressed and one thing to happen when the key is released.
    So how can I do this, normally I would just use a boolean set to false when a key is pressed and then set back to true once it is released but since released is always called I can't do this.
    Any help is greatly appreciated.
    (PS: I am working in Ubuntu)

    This is just the way it works in linux. You can check here for some thoughts on how to address it.

  • Problem with backspace on JFrame

    Hello,
    I have a problem on a JFrame. Indeed, I add a keyListener to the frame, but the "Bakcspace" don't work. There is anything when a I press on Backspace (with KeyTyped, KeyReleased and KeyPressed). All other keys are working.
    Thanks.

    the solution of the problem is :
    Version note: This page reflects the focus API introduced in released 1.4. As of that release, the focus subsystem consumes focus traversal keys, such as Tab and Shift Tab. If you need to prevent the focus traversal keys from being consumed, you can call
    component.setFocusTraversalKeysEnabled(false)
    on the component that is firing the key events. Your program must then handle focus traversal on its own. Alternatively, you can use a KeyEventDispatcher to pre-listen to all key events. The focus page (in the Creating a GUI with JFC/Swing trail) has detailed information on the focus subsystem.

  • Can someone pls help me with this code

    The method createScreen() creates the first screen wherein the user makes a selection if he wants all the data ,in a range or single data.The problem comes in when the user makes a selection of single.that then displays the singleScreen() method.Then the user has to input a key data like date or invoice no on the basis of which all the information for that set of data is selected.Now if the user inputs a wrong key that does not exist for the first time the program says invalid entry of data,after u click ok on the option pane it prompts him to enter the data again.But since then whenever the user inputs wrong data the program says wrong data but after displaying the singlescreen again does not wait for input from the user it again flashes the option pane with the invalid entry message.and this goes on doubling everytime the user inputs wrong data.the second wrong entry of data flashes the error message twice,the third wrong entry flashes the option pane message 4 times and so on.What actually happens is it does not wait at the singlescreen() for user to input data ,it straight goes into displaying the JOptionPane message for wrong data entry so we have to click the optiion pane twice,four times and so on.
    Can someone pls help me with this!!!!!!!!!
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import java.util.*;
    public class MainMenu extends JFrame implements ActionListener,ItemListener{
    //class     
         FileReaderDemo1 fd=new FileReaderDemo1();
         FileReaderDemo1 fr;
         Swing1Win sw;
    //primary
         int monthkey=1,counter=0;
         boolean flag=false,splitflag=false;
         String selection,monthselection,dateselection="01",yearselection="00",s,searchcriteria="By Date",datekey,smonthkey,invoiceno;
    //arrays
         String singlesearcharray[];
         String[] monthlist={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"};
         String[] datelist=new String[31];
         String[] yearlist=new String[100];
         String[] searchlist={"By Date","By Invoiceno"};
    //collection
         Hashtable allinvoicesdata=new Hashtable();
         Vector data=new Vector();
         Enumeration keydata;
    //components
         JButton next=new JButton("NEXT>>");
         JComboBox month,date,year,search;
         JLabel bydate,byinvno,trial;
         JTextField yeartext,invtext;
         JPanel panel1,panel2,panel3,panel4;
         JRadioButton single,range,all;
         ButtonGroup group;
         JButton select=new JButton("SELECT");
    //frame and layout declarations
         JFrame jf;
         Container con;
         GridBagLayout gridbag=new GridBagLayout();
         GridBagConstraints gc=new GridBagConstraints();
    //constructor
         MainMenu(){
              jf=new JFrame();
              con=getContentPane();
              con.setLayout(null);
              fr=new FileReaderDemo1();
              createScreen();
              setSize(500,250);
              setLocation(250,250);
              setVisible(true);
    //This is thefirst screen displayed
         public void createScreen(){
              group=new ButtonGroup();
              single=new JRadioButton("SINGLE");
              range=new JRadioButton("RANGE");
              all=new JRadioButton("ALL");
              search=new JComboBox(searchlist);
              group.add(single);
              group.add(range);
              group.add(all);
              single.setBounds(100,50,100,20);
              search.setBounds(200,50,100,20);
              range.setBounds(100,90,100,20);
              all.setBounds(100,130,100,20);
              select.setBounds(200,200,100,20);
              con.add(single);
              con.add(search);
              con.add(range);
              con.add(all);
              con.add(select);
              search.setEnabled(false);
              single.addItemListener(this);
              search.addActionListener(new MyActionListener());     
              range.addItemListener(this);
              all.addItemListener(this);
              select.addActionListener(this);
         public class MyActionListener implements ActionListener{
              public void actionPerformed(ActionEvent a){
                   JComboBox cb=(JComboBox)a.getSource();
                   if(a.getSource().equals(month))
                        monthkey=((cb.getSelectedIndex())+1);
                   if(a.getSource().equals(date)){
                        dateselection=(String)cb.getSelectedItem();
                   if(a.getSource().equals(year))
                        yearselection=(String)cb.getSelectedItem();
                   if(a.getSource().equals(search)){
                        searchcriteria=(String)cb.getSelectedItem();
         public void itemStateChanged(ItemEvent ie){
              if(ie.getItem()==single){
                   selection="single";     
                   search.setEnabled(true);
              else if (ie.getItem()==all){
                   selection="all";
                   search.setEnabled(false);
              else if (ie.getItem()==range){
                   search.setEnabled(false);
         public void actionPerformed(ActionEvent ae){          
              if(ae.getSource().equals(select))
                        if(selection.equals("single")){
                             singleScreen();
                        if(selection.equals("all"))
                             sw=new Swing1Win();
              if(ae.getSource().equals(next)){
                   if(monthkey<9)
                        smonthkey="0"+monthkey;
                   System.out.println(smonthkey+"/"+dateselection+"/"+yearselection+"it prints this");
                   allinvoicesdata=fr.read(searchcriteria);
                   if (searchcriteria.equals("By Date")){
                        System.out.println("it goes in this");
                        singleinvoice(smonthkey+"/"+dateselection+"/"+yearselection);
                   else if (searchcriteria.equals("By Invoiceno")){
                        invoiceno=invtext.getText();
                        singleinvoice(invoiceno);
                   if (flag == false){
                        System.out.println("flag is false");
                        singleScreen();
                   else{
                   System.out.println("its in here");
                   singlesearcharray=new String[data.size()];
                   data.copyInto(singlesearcharray);
                   sw=new Swing1Win(singlesearcharray);
         public void singleinvoice(String searchdata){
              keydata=allinvoicesdata.keys();
              while(keydata.hasMoreElements()){
                        s=(String)keydata.nextElement();
                        if(s.equals(searchdata)){
                             System.out.println(s);
                             flag=true;
                             break;
              if (flag==true){
                   System.out.println("vector found");
                   System.exit(0);
                   data= ((Vector)(allinvoicesdata.get(s)));
              else{
                   JOptionPane.showMessageDialog(jf,"Invalid entry of date : choose again");     
         public void singleScreen(){
              System.out.println("its at the start");
              con.removeAll();
              SwingUtilities.updateComponentTreeUI(con);
              con.setLayout(null);
              counter=0;
              panel2=new JPanel(gridbag);
              bydate=new JLabel("By Date : ");
              byinvno=new JLabel("By Invoice No : ");
              dateComboBox();
              invtext=new JTextField(6);
              gc.gridx=0;
              gc.gridy=0;
              gc.gridwidth=1;
              gridbag.setConstraints(month,gc);
              panel2.add(month);
              gc.gridx=1;
              gc.gridy=0;
              gridbag.setConstraints(date,gc);
              panel2.add(date);
              gc.gridx=2;
              gc.gridy=0;
              gc.gridwidth=1;
              gridbag.setConstraints(year,gc);
              panel2.add(year);
              bydate.setBounds(100,30,60,20);
              con.add(bydate);
              panel2.setBounds(170,30,200,30);
              con.add(panel2);
              byinvno.setBounds(100,70,100,20);
              invtext.setBounds(200,70,50,20);
              con.add(byinvno);
              con.add(invtext);
              next.setBounds(300,200,100,20);
              con.add(next);
              if (searchcriteria.equals("By Invoiceno")){
                   month.setEnabled(false);
                   date.setEnabled(false);
                   year.setEnabled(false);
              else if(searchcriteria.equals("By Date")){
                   byinvno.setEnabled(false);
                   invtext.setEnabled(false);
              monthkey=1;
              dateselection="01";
              yearselection="00";
              month.addActionListener(new MyActionListener());
              date.addActionListener(new MyActionListener());
              year.addActionListener(new MyActionListener());
              next.addActionListener(this);
              invtext.addKeyListener(new KeyAdapter(){
                   public void keyTyped(KeyEvent ke){
                        char c=ke.getKeyChar();
                        if ((c == KeyEvent.VK_BACK_SPACE) ||(c == KeyEvent.VK_DELETE)){
                             System.out.println(counter+"before");
                             counter--;               
                             System.out.println(counter+"after");
                        else
                             counter++;
                        if(counter>6){
                             System.out.println(counter);
                             counter--;
                             ke.consume();
                        else                    
                        if(!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))){
                             getToolkit().beep();
                             counter--;     
                             JOptionPane.showMessageDialog(null,"please enter numerical value");
                             ke.consume();
              System.out.println("its at the end");
         public void dateComboBox(){          
              for (int counter=0,day=01;day<=31;counter++,day++)
                   if(day<=9)
                        datelist[counter]="0"+String.valueOf(day);
                   else
                        datelist[counter]=String.valueOf(day);
              for(int counter=0,yr=00;yr<=99;yr++,counter++)
                   if(yr<=9)
                        yearlist[counter]="0"+String.valueOf(yr);
                   else
                        yearlist[counter]=String.valueOf(yr);
              month=new JComboBox(monthlist);
              date=new JComboBox(datelist);
              year=new JComboBox(yearlist);
         public static void main(String[] args){
              MainMenu mm=new MainMenu();
         public class WindowHandler extends WindowAdapter{
              public void windowClosing(WindowEvent we){
                   jf.dispose();
                   System.exit(0);
    }     

    Hi,
    I had a similar problem with a message dialog. Don't know if it is a bug, I was in a hurry and had no time to search the bug database... I found a solution by using keyPressed() and keyReleased() instead of keyTyped():
       private boolean pressed = false;
       public void keyPressed(KeyEvent e) {
          pressed = true;
       public void keyReleased(KeyEvent e) {
          if (!pressed) {
             e.consume();
             return;
          // Here you can test whatever key you want
       //...I don't know if it will help you, but it worked for me.
    Regards.

  • Need some help in jtextfield

    (repost from Programming Forum)
    Hello
    I want to create a jtextfield that only allows user to key in numerics and with fixed character length (means only a fixed length of characters can be entered).
    I have viewed this post:
    http://forum.java.sun.com/thread.jspa?threadID=536977&messageID=2597211
    and one of the reply said that the numeric part can be done with key listener, but I just don`t know how to do this, even after viewing the API.
    Hope that anyone could help me on this.
    Regards.

    camickr:
    Thanks, I`m now starting to study how to use
    JFormattedTextField. I hope it won`t be complicated.
    javabinge:
    I`ve tested your code, and the part inside keyTyped
    really needs to move to other parts, as getKeyCode()
    in keyTyped only returns VK_UNDEFINED, which is 0;
    And after moving the code the KeyPressed and
    keyReleased, only numeric keys can be entered, even
    Directional Key, Backspace and Delete won`t work
    lol
    t thank you for the code anyway, as it does help me A
    LOT.oh shoot, sorry for the mixup... just add an else if for other keys...
    ie.
    if( !event.getKeyCode()==KeyEvent.VK_LEFT)
    event.consume();
    actually if you put the condition for numerics in the keyTyped, it should work... because directionals and delete/backspace are not keytypes... they should be captured in keypress
    another thing to look at would be input verifier and the document

  • Listening for any key to be pressed?

    I'm writing a small text-based program and when Task #1 finishes,
    it prompts for the user to press any key.
    If any key is pressed, the program proceeds to Task #2 and when it finishes the user needs to press any key again. And so on...
    So how can I listen if any key has been pressed or not?
    Can somebody give me some pointers to some examples dealing with this and which class I should look at?
    Any help would be appreciated.

    your class needs to implement KeyListener, and define 3 methods
    keyPressed
    keyTyped
    and
    keyReleased.
    you will also need some counter to know when to do task 1, task 2 etc.
    so it would look like:
    public class Whatever extends Something implements KeyListener {
         private static int counter = 1;
         public static void main(String[] args) {
         public static void task1() {
              some code
              counter++;
         public static void task2() {
              some code
              counter++;
         public void keyTyped(KeyEvent e) {
              switch(counter) {
                   case 1: task1(); break;
                   case 2: task2(); break;
         public void keyPressed(KeyEvent e) {
         public void KeyReleased(KeyEvent e) {
    }hope this helps!
    Tom

  • Problem with fullscreen

    Hi,
    I am creating a JFrame with a JPanel. On clicking the Panel, I am invoking the fullscreen window. Now, I would like to know who is having the focus the JPanel, the JFrame or the JWindow.
    I am calling JPanel.requestFocus(), but the keyPressed or keyReleased of JPanel is not being called on pressing the key in the fullscreen window. Neither it comes in the keypressed or keyReleased event of JWindow.
    How to make the keyPressed or keyReleased event of JPanel or JWindow get called ?
    Also when i run this application in solaris, two windows are shown, one for the fullscreen window and one for the main window. But in Windows only one window is shown in fullscreen mode.
    import javax.swing.JFrame;
    import java.awt.BorderLayout;
    import javax.swing.JPanel;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JButton;
    import javax.swing.JWindow;
    class ExFrame
    extends JFrame implements KeyListener {
    JWindow window;
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel jPanel1 = new JPanel();
    JButton jButton1 = new JButton();
    JPanel jPanel2 = new JPanel();
    public ExFrame() {
    this.getContentPane().setLayout(borderLayout1);
    jPanel2.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent ke) {
    System.out.println("jPanel2 Pressed");
    public void keyReleased(KeyEvent ke) {
    System.out.println("Released");
    jPanel2.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    if (window == null || !window.isVisible()) {
    jPanel2.requestFocus();
    if (window == null) {
    window = new JWindow(ExFrame.this);
    Dimension size = Toolkit.getDefaultToolkit().
    getScreenSize();
    window.setSize(size);
    window.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent ke) {
    System.out.println("Pressed");
    if (ke.getKeyCode() == KeyEvent.VK_ESCAPE) {
    ExFrame.this.getContentPane().add(
    jPanel2,
    java.awt.BorderLayout.CENTER);
    public void keyReleased(KeyEvent ke) {
    System.out.println("Released");
    remove(jPanel2);
    window.getContentPane().add(jPanel2);
    window.setVisible(true);
    window.toFront();
    jPanel2.requestFocus();
    window.requestFocusInWindow();
    addKeyListener(this);
    jPanel2.setBackground(Color.blue);
    this.getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);
    public void keyReleased(KeyEvent ke) {
    System.out.println("Frame Released");
    public void keyPressed(KeyEvent ke) {
    System.out.println("Frame Pressed");
    if (ke.getKeyCode() == KeyEvent.VK_ESCAPE) {
    System.exit(0);
    public void keyTyped(KeyEvent ke) {
    System.out.println("Frame Typed");
    public static void main(String args[]) {
    ExFrame frame = new ExFrame();
    frame.pack();
    frame.setVisible(true);
    }

    yeah, its part of a workaround for switching between windowed and fullscreen.
    It isn't necessary to return to the original displayMode, simply setFullscreenWindow(null) will return you to the original desktops resolution.
    I'll warn you now, don't even attempt switching fullscreen<->windowed mode multiple times, it will crash. It should be fixed in 1.5 though.

Maybe you are looking for