Implementing a key listener

Hi,
I am trying to create a pong type game, however it currently only displays a ball bouncing around the screen and a paddle in the center. So I'm trying to allow the user to move the paddle using left and right keys but it won't work. Any suggestions will be great:-
I have four classes (Pong, Input, Ball, Paddle extends Input).
The code for the Input class is:
class CInput
     private int x;
     public boolean keyDown(Event e, int key)
          switch(key)
               case Event.LEFT:
                    x = x - 2;
               break;
               case Event.RIGHT:
                    x = x + 2;
               break;
          return true;
     public boolean keyUp(Event e, int key)
          switch(key)
               case Event.LEFT:
                    x = x - 2;
               break;
               case Event.RIGHT:
                    x = x + 2;
               break;
          return true;
}The paddle class has an update method that uses x to position the paddle. Can anyone see any obvious problems??

Don't use those methods. They are deprecated. Read this:
How to write a KeyListener

Similar Messages

  • Wrong line in key listener

    Hello
    I m writing a key listener to change label 1 to blue when the one key is pressed and change to grey when another key is pressed. Here is my code for it so far.
    if (evt.getKeyChar() == '1') {
    process(evt.getKeyChar(lbl1.background = 51,255,255));
    else if (evt.getKeyChar() != '1'){
    process(evt.getKeyChar(lbl1.background = 240,240,240));
    The second line starting with process to change the label colour does not function correctly but the first one does which gets the character. The label is a swing label but would it be best to change the label to a awt label to get the colour change to work using java.awt.colour? Also could I take out the .background part and just have lbl1= 51,255,255,255. Thanks ahead for any help with the second line.
    Nick

    NUFCjavaworker wrote:
    Cheers for the help however it has made another problem. The shorter version worked the best so that is what I used. I implemented it like this:
    public class MyKeyListener extends KeyAdapter {
    public void keyPressed(KeyEvent evt) {
    lbl1.setBackground(evt.getKeyChar() == '1' ? Color.BLUE : Color.GRAY);
    lbl2.setBackground(evt.getKeyChar() == '2' ? Color.BLUE : Color.GRAY);
    lbl3.setBackground(evt.getKeyChar() == '3' ? Color.BLUE : Color.GRAY);
    lbl4.setBackground(evt.getKeyChar() == '4' ? Color.BLUE : Color.GRAY);
    lbl5.setBackground(evt.getKeyChar() == '5' ? Color.BLUE : Color.GRAY);
    It went on like that until I had cover all the characters and all the labels, I wanted to cover. Here is the problem that occured. The code that is generated when you create a java desktop application using the latest version of netbeans now has errors in it. Do I have to import any other java events or items that will solve this problem.
    NickErrors you say?

  • How to debug this key listener

    how would I figure out what this key listener is actually doing, if anything?
    piece1 is a new piece object that has a center at certain part on a matrix, with its width being at startPlaceX.
    What I think should happened here is that when the user presses the left arrow key, it calls moveXLeft, which in turn, decrements the spot on the matrix that the current piece is.
    In otherwords, how can I tell that the keyListener is doing anything? I have a function in my actionListener
      public void startAnimation()
           if (animationTimer == null)
              animationTimer = new Timer(ANIMATION_DELAY, new TimerHandler());
              animationTimer.start();
           else
              if (!animationTimer.isRunning())
                   animationTimer.restart();
        public class TimerHandler implements ActionListener
          public void actionPerformed(ActionEvent actionEvent)
                     piece1.moveDown(board);
                 piece1.drawIt(board, true);
                         repaint();
         public void moveDown(int[][]board)
              //startPlaceY++;
                   startPlaceY++;that works (IE, every given interval, it moves the specified piece down by 1)
    here is the code in question
         public void moveXLeft(int [][]temp)
              startPlaceX--;
              //startPlaceY+= change;
        public class KeyHandler implements KeyListener
             public void keyPressed(KeyEvent event)
                 switch (event.getKeyCode())
                      case KeyEvent.VK_LEFT:
                           piece1.moveXLeft(board);
                           //x -= size;
                           break;
                      case KeyEvent.VK_RIGHT:
                           piece1.moveXRight(-1);
                           //x += size;
                           break;
                 repaint();
             public void keyReleased(KeyEvent event) {}
             public void keyTyped(KeyEvent event) {}
        }if you need any more info, please say so.
    Edited by: thenextbesthang on Dec 16, 2007 12:33 PM
    Edited by: thenextbesthang on Dec 16, 2007 12:33 PM

    heres the whole of my code (right now)
    import java.awt.* ;
    import java.awt.event.* ;
    import javax.swing.* ;
    import java.awt.font.* ;
    import java.awt.geom.* ;
    public class project3{
    public static void main(String[] args)
            JFrame window = new JFrame();
             window.setTitle("Tetris");
        commenceGame begin = new commenceGame();
             begin.init();         
             begin.startAnimation();
             window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         
             window.getContentPane().add(begin);
             window.pack(); 
             window.setVisible( true );
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Pieces{
         public int x;
         public int y;
         public int cross[][] =  {{1,1,1},
                   {0,1,0}};
         private int leftL[][] =  {{2,2,2},
                         {2,0,0}};
         private int rightL[][] = {{3,3,3},
                                            {0,0,3}};
         private int leftS[][] =  {{0,4,4},
                        {4,4,0}};
         private int rightS[][] = {{5,5,0},
                        {0,5,5}};
         private int square[][] = {{6,6},
                        {6,6}};
         private int tetris[][]=    {{7,7,7,7}};
         private int blankSquare[][] ={{0}};
         public int startPlaceY;
         public int startPlaceX;
         public int shape;
         public int replacement_board[][];
         public Pieces()
              x = 0;
              y = 1;
              startPlaceX = 4;
              startPlaceY = 0;     
              shape = (int)(Math.random()*7);
              replacement_board = new int[20][10];          
         public int[][] drawIt(int[][]temp2_board, boolean por)
              //1
              //temp2_board = replacement_board;
              makeTetris(temp2_board);     
              //if(por) makeCross(temp2_board);//2
         //     temp2_board = replacement_board;
         //     else    reMakeCross(replacement_board);
    /*          switch(shape)
                case 0:
                       makeCross(temp2_board);           
                     break;
                case 1:
                       makeLeftL(temp2_board);           
                     break;      
                case 2:
                       makeRightL(temp2_board);           
                     break; 
                case 3:
                       makeLeftS(temp2_board);           
                     break;      
                case 4:
                       makeRightS(temp2_board);           
                     break; 
                case 5:
                       makeSquare(temp2_board);           
                     break;      
                case 6:
                        makeTetris(temp2_board);      
                     break;               
              return temp2_board;
         public int[][] makeCross(int[][]temp)
               replacement_board= temp;
              for(int i=0;i<temp.length;i++)
                   for(int j = 0;j<temp[0].length;j++)
                        temp[i][j] = 0;
              int color;                    
            for(int i = 0;i<2;i++)
                 for(int j = 0;j<3;j++)
                      color = cross[i][j];
                      temp[startPlaceX+i][startPlaceY+j] = color;
            return(temp);
         //this method is designed to take the initial condition and create the new matrix
         public int[][] makeLeftL(int[][]temp)
              for(int i=0;i<temp.length;i++)
                   for(int j = 0;j<temp[0].length;j++)
                        temp[i][j] = 0;
              int color;                    
            for(int i = 0;i<2;i++)
                 for(int j = 0;j<3;j++)
                      color = leftL[i][j];
                      temp[startPlaceX+i][startPlaceY+j] = color;
            return temp;
         public int[][] makeRightL(int[][]temp)
              for(int i=0;i<temp.length;i++)
                   for(int j = 0;j<temp[0].length;j++)
                        temp[i][j] = 0;
              int color;                    
            for(int i = 0;i<2;i++)
                 for(int j = 0;j<3;j++)
                      color = rightL[i][j];
                      temp[startPlaceX+i][startPlaceY+j] = color;
            return temp;
         public int[][] makeLeftS(int[][]temp)
              for(int i=0;i<temp.length;i++)
                   for(int j = 0;j<temp[0].length;j++)
                        temp[i][j] = 0;
              int color;                    
            for(int i = 0;i<2;i++)
                 for(int j = 0;j<3;j++)
                           color = leftS[i][j];
                      temp[startPlaceX+i][startPlaceY+j] = color;
            return temp;
         public int[][] makeRightS(int[][]temp)
              for(int i=0;i<temp.length;i++)
                   for(int j = 0;j<temp[0].length;j++)
                        temp[i][j] = 0;
              int color;                    
            for(int i = 0;i<2;i++)
                 for(int j = 0;j<3;j++)
                      color = rightS[i][j];
                      temp[startPlaceX+i][startPlaceY+j] = color;
            return temp;     
         public int[][] makeSquare(int[][]temp)
              for(int i=0;i<temp.length;i++)
                   for(int j = 0;j<temp[0].length;j++)
                        temp[i][j] = 0;
              int color;                    
            for(int i = 0;i<2;i++)
                 for(int j = 0;j<2;j++)
                      color = square[i][j];
                      temp[startPlaceX+i][startPlaceY+j] = color;
            return temp;
         public int[][] makeTetris(int[][]temp)
              for(int i=0;i<temp.length;i++)
                   for(int j = 0;j<temp[0].length;j++)
                        temp[i][j] = 0;
              int color;                    
            for(int i = 0;i<4;i++)
                 for(int j = 0;j<1;j++)
                      color = tetris[j];
              temp[startPlaceX+i][startPlaceY+j] = color;
    return temp;
         public int[][] makeBlankSquare(int[][]temp, boolean check)
              int color;                    
    for(int i = 0;i<1;i++)
         for(int j = 0;j<1;j++)
              if(check) color = blankSquare[i][j];
              else color = 0;
              temp[startPlaceX+i][startPlaceY+j] = color;
    return temp;
         public void moveDown(int[][]board)
              //startPlaceY++;
                   startPlaceY++;
              replacement_board = board;
              System.out.println(startPlaceY);
              //temp[startPlaceX+i][startPlaceY+j] = color;
                   replacement_board = board;
                   if(board[startPlaceY][startPlaceX] &&
                   board[startPlaceY+1][startPlaceX] &&
                   board[startPlaceY-1][startPlaceX] &&
                   board[startPlaceY][startPlaceX+1] &&
                   board[i][j]==1) board[i][j]=0;
                   for(int i=0;i<board.length;i++)
                        for(int j = 0;j<board[0].length;j++)
                             System.out.print(board[i][j] + " ");
                        System.out.println();
                   System.out.println();
                   //System.out.println(startPlaceY);
                   //makeCross(board);
                   //return replacement_board;               
         public void moveXLeft(int [][]temp)
              startPlaceX--;
              //startPlaceY+= change;
         public void moveXRight(int [][]temp)
              startPlaceX++;
              makeCross(replacement_board);
              //startPlaceY+= change;
         public int[][] killLiving(int[][]temp)
              for(int i = 0;i<temp.length;i++)
                   for(int j = 0;j<temp[0].length;j++)
                        if(temp[i][j]!= 0)
                             temp[i][j] = -1;
         return temp;
    }          import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class commenceGame extends JPanel
         public int x;//starting x location of block
         public int y;//starting y location of block
         public int width;//width of block
         public int height;//height of block
         public int board[][];
         /*{{-1,-1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
                                       {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},     
                                       {-1,-1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1}};//game play board*/
         public int temp_storage_board[][];
         public int xBoard;//width of board matrix
         public int yBoard;//height of board matrix
         public Timer animationTimer;
         public int ANIMATION_DELAY;
         Pieces piece1;//the piece that gets modified
         Pieces piece2;//the piece that is the result of the modification
         public commenceGame()
              xBoard = 10;
              yBoard = 20;
              width = 20;
              height = 20;
              x = 5;
              y = 0;          
              board = new int[yBoard][xBoard];
              //this is the board where pieces appear
              temp_storage_board = new int[yBoard][xBoard];//this is the main board          
              piece1 = new Pieces();
              piece1.drawIt(board, true);
         //     piece2 = new Pieces();
         //     piece2.drawIt(board, false);
              ANIMATION_DELAY = 500;
    public void init()
              JPanel panel = new beginGame();
              add(panel);
    public class beginGame extends JPanel
              public beginGame()
                   setPreferredSize(new Dimension(400,800));
                   setBackground(Color.white);               
    public void paintComponent(Graphics g)
                   super.paintComponent(g);
                   Graphics2D g2 = (Graphics2D)g;
                   temp_storage_board = board;
              for (int i = 0 ; i < yBoard; i++)
                        for (int j = 0 ; j < xBoard; j++)
                                  if(temp_storage_board[i][j] == 1) drawCross(g2, i, j);
                                  else if(temp_storage_board[i][j] == 2) drawLeftL(g2, i, j);
                                  else if(temp_storage_board[i][j] == 3) drawRightL(g2, i, j);
                                  else if(temp_storage_board[i][j] == 4) drawLeftS(g2, i, j);
                                  else if(temp_storage_board[i][j] == 5) drawRightS(g2, i, j);
                                  else if(temp_storage_board[i][j] == 6) drawSquare(g2, i, j);
                                  else if(temp_storage_board[i][j] == 7) drawTetris(g2, i, j);
                                  else if(temp_storage_board[i][j] == -1) drawDeadSquare(g2, i, j);                               
              public void drawCross(Graphics2D g2, int x, int y)     
                   // piece1.makeCross(board, true);
                   g2.setColor(Color.red);
                   g2.fillRect(x*width,y*height,width,height);
                   g2.setColor(Color.black);
                   g2.drawRect(x*width,y*height,width,height);
              //else if (board[i][x] == 2)
              public void drawLeftL(Graphics2D g2, int x, int y)                    
                   // piece1.makeLeftL(board, true);
                   g2.setColor(Color.red);
                   g2.fillRect(x*width,y*height,width,height);
                   g2.setColor(Color.black);
                   g2.drawRect(x*width,y*height,width,height);
                   //else if (board[i][x] == 3)
              public void drawRightL(Graphics2D g2, int x, int y)
                   // piece1.makeRightL(board, true);
                   g2.setColor(Color.cyan);
                   g2.fillRect(x*width,y*height,width,height);
                   g2.setColor(Color.black);
                   g2.drawRect(x*width,y*height,width,height);
                   //else if (board[i][x] == 4)
              public void drawLeftS(Graphics2D g2, int x, int y)
                   // piece1.makeLeftS(board, true);
                   g2.setColor(Color.orange);
                   g2.fillRect(x*width,y*height,width,height);
                   g2.setColor(Color.black);
                   g2.drawRect(x*width,y*height,width,height);
                   //else if (board[i][x] == 5)
              public void drawRightS(Graphics2D g2, int x, int y)
                   // piece1.makeRightS(board, true);
                   g2.setColor(Color.yellow);
                   g2.fillRect(x*width,y*height,width,height);
                   g2.setColor(Color.black);
                   g2.drawRect(x*width,y*height,width,height);
                   //else if (board[i][x] == 6)
              public void drawSquare(Graphics2D g2, int x, int y)
                   // piece1.makeSquare(board, true);
                   g2.setColor(Color.blue);
                   g2.fillRect(x*width,y*height,width,height);
                   g2.setColor(Color.black);
                   g2.drawRect(x*width,y*height,width,height);
                   //else if (board[i][x] == 7)
              public void drawTetris(Graphics2D g2, int x, int y)
                   // piece1.makeTetris(board, true);
                   g2.setColor(Color.green);
                   g2.fillRect(x*width,y*height,width,height);
                   g2.setColor(Color.black);
                   g2.drawRect(x*width,y*height,width,height);
              //     else if (board[i][x] == 0)
              public void drawBlankSquare(Graphics2D g2, int x, int y)
                   // piece1.makeBlankSquare(board, true);
                   g2.setColor(Color.white);
                   g2.fillRect(x*width,y*height,width,height);
                   //else if (board[i][x] == -1)
              public void drawDeadSquare(Graphics2D g2, int x, int y)
                   // piece1.makeDeadSquare(board, true);
                   g2.setColor(Color.gray);
                   g2.fillRect(x*width,y*height,width,height);
    public void startAnimation()
    if (animationTimer == null)
    animationTimer = new Timer(ANIMATION_DELAY, new TimerHandler());
    animationTimer.start();
    else
    if (!animationTimer.isRunning())
    animationTimer.restart();
    public class TimerHandler implements ActionListener
    public void actionPerformed(ActionEvent actionEvent)
              // System.out.println("aP");
              piece1.moveDown(board);
         //     piece1.moveXLeft(board);
              piece1.drawIt(board, true);
              repaint();
              if (piece1.startPlaceY> 10)
                   piece1.killLiving(board);
         //y += size;
         //if (y > height) y = 10;
    public class KeyHandler implements KeyListener
         public void keyPressed(KeyEvent event)
         switch (event.getKeyCode())
              case KeyEvent.VK_LEFT:
                   piece1.moveXLeft(board);
                   //x -= size;
                   break;
              case KeyEvent.VK_RIGHT:
                   piece1.moveXRight(board);
                   //x += size;
                   break;
         repaint();
         public void keyReleased(KeyEvent event) {}
         public void keyTyped(KeyEvent event) {}
    Basically, what this does is creates an applet, picks a random piece, and makes the piece fall down until it reaches the end (at which point it can't fall down any further)
    As I mentioned before, the method: public class TimerHandler implements ActionListener
    public void actionPerformed(ActionEvent actionEvent)
              // System.out.println("aP");
              piece1.moveDown(board);works, because the thing DOES fall down.
    However, when I try to replicate that with the keyListener, using essentially the same process, it doesn't work.
    I'll look up what yall said                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

  • Global key listener

    Hi,
    I currently implemented a keylistener using extending key adapter which uses keypressed to listen on what key is pressed.
    It works good. However, when ever I click on a Swing input control like Jtextfield the "hotkey" is no longer functional. But it still works if i click on non-input controls like jlabels.
    is there a better way in creating a hotkey function in java which overrides, so is still functional even if I click on a Jtextfield ?
    Thanks

    Have you tried using KeyBindings instead of a key listener or adapter?
    for instance
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.InputMap;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    public class FuSwing
        private static final String CONTROL_U = "Ctrl-U";
        private JPanel mainPanel = new JPanel();
        public FuSwing()
            mainPanel.setPreferredSize(new Dimension(400, 400));
            mainPanel.add(new JButton("Foo"));
            JTextField field = new JTextField(12);
            mainPanel.add(field);
            putAction(mainPanel, KeyEvent.VK_U, CONTROL_U, ActionEvent.CTRL_MASK);
            //removeAction(field, KeyEvent.VK_U, CONTROL_U, ActionEvent.CTRL_MASK);
        private void putAction(JComponent comp, int keystroke, String keyString, int mask)
            KeyStroke ks = KeyStroke.getKeyStroke(keystroke, mask);
            comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks, keyString);
            comp.getActionMap().put(keyString, new KeyAction(keyString));
        private void removeAction(JComponent comp, int keystroke, String keyString, int mask)
            KeyStroke ks = KeyStroke.getKeyStroke(keystroke, mask);
            InputMap im = comp.getInputMap(JComponent.WHEN_FOCUSED);
            im.put(ks, "none");
        private class KeyAction extends AbstractAction
            private String keyStr = "";
            public KeyAction(String keyStr)
                this.keyStr = keyStr;
            @Override
            public void actionPerformed(ActionEvent e)
                if (keyStr.equals(CONTROL_U))
                    System.out.println("Control U pressed");
        public JPanel getMainPanel()
            return mainPanel;
        private static void createAndShowUI()
            JFrame frame = new JFrame("FuSwing");
            frame.getContentPane().add(new FuSwing().getMainPanel());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

  • LISTENING FOR BACKSPACE WITH A KEY LISTENER

    I have a key listener and I want to know how I find out if backspace has been pressed.
    Thanks

    I created a JTextField and added it to a JPanel which was added to the contentPane.
    When I add my key listener to a JTextField or the the JFrame, the code suggested above works fine. (JKD1.3, Windows 98)
    When I add the key listener to the JPanel it doesn't work.

  • How can I add the key listener to JFrame

    Hi,
    How can I add the Key Listener to the JFrame? I want to show the Windows default popup which comes after right clicking on the frame's header. I want to add the key board support for the same

    1. Make sure that key events are enabled on your component. (AWTMulticaster.enableEvents(...)
    2. add the keylistener

  • Tab and Key Listener

    I have put a key listener in a JTextField, but when I hit the tab key it does not generate a keyPressed event. Currently tab does nothing not even cycle through GUI components. Can you help me figure ouy how to get it to recognize the tab key.
    P.S. The code that is inside the tab block works as I tried it with other keys so that is not the error.

    I would search the forums for jtextfield and tab in the title
    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2Btitle%3Ajtextfield+%2Btitle%3Atab&col=javaforums

  • How can we implement product key feature while installing AIR application?

    How can we implement product key feature while installing AIR application?

    Hello,
    Could you try using /Q or /QS parameter?
    http://msdn.microsoft.com/en-us/library/ms144259(v=sql.110).aspx
    Hope this helps.
    Regards,
    Alberto Morillo
    SQLCoffee.com

  • Air Native Extension - Java Key Listener

    Hello all,
    Firstly I'd like to thank you for creating an excellent and helpful community. I have an issue I have been stuck on for around 2 weeks now.
    I am creating an android native extension to listen to key input from a proprietary remote control device. GameInput does not recognise it as a game controller so we have to create a native extension to get the input. I have it working fully except for one issue; if the game loses context (eg the user gets a phone call or the game goes into the background for any other reason) I do not get any other input.
    The way I am doing it is to attach an onKeyListener to the currently focused View (an AirWindowSurfaceView). This works perfectly, but when the context is lost I'm assuming the AirWindowSurfaceView changes and I cannot find a way to get a reference to the new one. Here is my key listener setup code (from the native Java):
    public void updateListeners()
        if(_view != null)
          _view.setOnKeyListener(null); //remove from the old view
          _view.setOnGenericMotionListener(null);
        _context.dispatchStatusEventAsync(_view.toString(), "view"); //send the current view details
        _view = _context.getActivity().getCurrentFocus();  //set the new view
        _context.dispatchStatusEventAsync(_view.toString(), "view");
       if(_onKeyListener == null)
           _onKeyListener = new NativeGamepadKeyListener(_context, this); //create new key listener
       if(_onGenericMotionListener == null)
           _onGenericMotionListener = new NativeGamepadMotionListener(_context, this); //create a new motion listener
       _view.setOnKeyListener(_onKeyListener);          //set on the new view
       _view.setOnGenericMotionListener(_onGenericMotionListener);
    This updateListeners function is called when I get a focus change event on the current view (attached in a similar way) but this doesn't seem to keep it up to date with the current View.
    Please note I'm a newbie at making extensions like these and might be going about it totally the wrong way - if I am and you have any suggestions as to the best way to use an onKeyListener in a native extension I'd love to hear it.
    Thanks in advance for your help!

    I am not able to solve this yet. Is anybody else facing this this problem.

  • Remove the key listener from JTable problem please help

    Hi
    I�m trying to remove the key listener from my table, it doesn�t work,
    I�m pressing the enter key it still goes to the next row from the table,
    hear is my code
    KeyListener[] mls = (KeyListener[])(table.getListeners(KeyListener.class));
    for(int i = 0; i < mls.length; i++ )
    table.removeKeyListener(mls);
    Please help thanks

    Hm ...
    that should indeed remove all the KeyListeners from your table - the question is only, when does this happen?- Where in your code do you remove the KeyListeners?- I am quite sure, you remove them successfully, but after your have removed them, one or more KeyListeners are added to the table.
    greetings Marsian

  • JTable TAB key listener

    Hi all:
    I'm trying to write a filterable jtable. User can input the filter rule in the table header and the table displays the filtered data at the same time when the user inputs letters. The table filter works fine. But when I try to add "TAB" key listener, I find that I can't track the "TAB" key. I use a customerized cell renderer to display the filterable table header, a customerized cell editor to edit the filterable table header. The cell editor is created like this:
    JTextField textField = new JTextField("");
    DefaultCellEditor cellEditor = new DefaultCellEditor(textField);
    And I add a KeyListener to the textField. The KeyListener can track other keys like "Shift", "Alt", "Ctrl", but it can't track "TAB". It's weird. I also add the KeyListener to JTableHeader, JTable, but when I edit something in the JTextField, I still can't catch the "TAB" key. Have any ideas? Thank you for your time.

    by default the Tab is used (and consumed) by
    focusManager to move focus between components. If you
    want to get it in a component you have to signal the
    manager to keep it's hands off. How to do so depends
    on the jdk version. Focus handling changed
    considerably between 1.3 and 1.4: Prior to 1.4 you
    have to subclass the component in question to return
    true on isManagingFocus(), since 1.4 you have to set
    the comp's focusTraversalKeys to make the manager take
    those instead of the default keys.
    Greetings
    JeanetteThanks Jeanette, it works. I use the Component.setFocusTraversalKeysEnabled(false) to disable all traversal keys of JTextField and add a KeyEventDispatcher to the KeyboardFocusManager. It finally works. Users can use "TAB" keyStroke and "Shift-TAB" keyStroke to traverse in the filterable table header now. Thank you for your great help and the $$ are yours.

  • Implementing shortcut keys ion JSF pages Jdev 11g

    How we can implement shortcut keys ion JSF pages Jdev 11g ?
    We are doing a Oracle Forms to Java migration and our users are getting use to use function keys.
    how we can map a commit action on the form to "CTRL + F7 key" (for example)
    Thanks.

    Hi,
    This is not possible directly. With JSF technology you are limited with browser capabilities which are HTML + Javascript. So you cannot communicate directly with i.e. commit function only with i.e. HTML form action or AJAX based javascript function...
    regards,
    Branislav

  • Key listener problem while using jdk1.4

    Hello All ,
    i have a panel which is having two JTextFields and two JButtons .
    I have added the key listener for the panel and trap the Esc button pressed and on this event i am making the panel invisible
    This stuff was working prefectly fine with jdk1.3 but it is not working with the jdk1.4
    any reasons ..
    please reply ..
    thanks
    ssk_p

    Use JFrame instead of Panel and compliled by jdk1.4.
    There are some changes for jdk1.4. A application compiled by jdk1.3 might not work properply for jdk1.4, especially for key listener.

  • JNA: key listener + JFrame

    Hello,
    I'm trying to write a simple application where I have a keyboard listener in the background and JFrame. Practically, I use the following code to create the listener:
    public class KeyHook {
    private static volatile boolean quit;
    private static HHOOK hhk;
    private static LowLevelKeyboardProc keyboardHook;
    public static void main(String[] args) {
    final User32 lib = User32.INSTANCE;
    HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
    keyboardHook = new LowLevelKeyboardProc() {
    public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
    if (nCode >= 0) {
    switch(wParam.intValue()) {
    case WinUser.WM_KEYUP:
    case WinUser.WM_KEYDOWN:
    case WinUser.WM_SYSKEYUP:
    case WinUser.WM_SYSKEYDOWN:
    System.err.println("in callback, key=" + info.vkCode);
    if (info.vkCode == 81) {
    quit = true;
    return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
    hhk = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHook, hMod, 0);
    System.out.println("Keyboard hook installed, type anywhere, 'q' to quit");
    new Thread() {
    public void run() {
    while (!quit) {
    try { Thread.sleep(10); } catch(Exception e) { }
    System.err.println("unhook and exit");
    lib.UnhookWindowsHookEx(hhk);
    System.exit(0);
    }.start();
    // This bit never returns from GetMessage
    int result;
    MSG msg = new MSG();
    while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
    if (result == -1) {
    System.err.println("error in get message");
    break;
    else {
    System.err.println("got message");
    lib.TranslateMessage(msg);
    lib.DispatchMessage(msg);
    lib.UnhookWindowsHookEx(hhk);
    My requirement is to create the listener as the first and after it JFrame. The problem is that I don't know how to create JFrame because of GetMessage. Now, GetMessage blocks the current thread so I can't create JFrame after it. On the other hand, I can't put it in a new Thread because then, the listener doesn't work. I hope you understand the issue :) Any ideas how to solve it?
    Thanks in advance!

    Ok, this is what should be done to solve the problem:
    We throw out this fragment:
    new Thread() {
    public void run() {
    while (!quit) {
    try { Thread.sleep(10); } catch(Exception e) { }
    System.err.println("unhook and exit");
    lib.UnhookWindowsHookEx(hhk);
    System.exit(0);
    }.start();
    and next, we enclose code from the main method in:
    new Thread(new Runnable() {
    }).start();
    Then, we are free to type in the main method e.g. :
    startListening(); // key listener
    JFrame frame = new JFrame();
    SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
    frame.setVisible(true);
    });

  • SetFocus messes up key listener

    I have a textfield attached to a movieclip attached to a
    movieclip on the stage. I have an object set to listen for key
    events, and that object defines an onKeyDown function. If I run the
    movie and click on the textfield manually, a cursor appears in the
    textfield, and when I enter text the onKeyDown function executes.
    If instead I use Selection.setFocus(myTextfield), the cursor
    does not appear, but I can still type text in the textfield.
    However, this apparently makes a big difference, because now the
    onKeyDown function in the key-listener object does not execute. Is
    there a way to programmatically set focus and still have key
    listeners work? What is the difference between the
    Selection.setFocus kind of focus and the other kind of focus when a
    cursor appears?

    create an array. it's quick and easy if you work cleverly.
    create an empty array and push your ascii keypress codes into
    it. then test your project and keypress the numbers and letters in
    the order you want them to be listed in your array.
    when you're finished trace your array (in order), copy the
    output panel and in the authoring environment paste your ascii
    array.

Maybe you are looking for