KeyListener Q:

Here is my code:
package Pong;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
* @author Michael Dean
public class Pong extends JPanel {
    private int xPos;
    private int yPos;
    private int xPosTwo;
    private int yPosTwo;
    private int xHeight;
    private int xWidth;
    public Pong() {
        xPos = 10;
        yPos = 150;
        xPosTwo = 350;
        yPosTwo = 150;
        xHeight = 20;
        xWidth = 60;
    public void yUp(int pos) {
        if (yPos <= 10) {
        } else {
            yPos -= pos;
    public void yDown(int pos) {
        if (yPos >= 290) {
        } else {
            yPos += pos;
    public void yUpTwo(int pos) {
        if (yPosTwo <= 10) {
        } else {
            yPosTwo -= pos;
    public void yDownTwo(int pos) {
        if (yPosTwo >= 290) {
        } else {
            yPosTwo += pos;
    @Override
    public void paintComponent(Graphics g) {
        Graphics2D g1 = (Graphics2D) g;
        super.paintComponent(g);
        g1.setColor(Color.RED);
        g1.fillRect(xPos, yPos, xHeight, xWidth);
        g1.setColor(Color.BLUE);
        g1.fillRect(xPosTwo, yPosTwo, xHeight, xWidth);
        g1.setColor(Color.WHITE);
        g1.fillOval(190, 175, 20, 20);
package PongGUI;
import Pong.Pong;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PongGUI extends JFrame implements KeyListener {
    Pong canvas = new Pong();
    public static void main(String[] args) {
        new PongGUI();
    public PongGUI() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container c = getContentPane();
        c.add(canvas);
        setSize(395, 395);
        addKeyListener(this);
        setVisible(true);
        setResizable(false);
        canvas.setBackground(Color.BLACK);
    public void keyTyped(KeyEvent e) {
        e.consume();
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_S) {
            canvas.yDown(10); //down
            canvas.repaint();
        if (key == KeyEvent.VK_W) {
            canvas.yUp(10); //up
            canvas.repaint();
        if (key == KeyEvent.VK_O) {
            canvas.yUpTwo(10); //up
            canvas.repaint();
        if (key == KeyEvent.VK_L) {
            canvas.yDownTwo(10); //down
            canvas.repaint();
        } else {
            e.consume();
    public void keyReleased(KeyEvent e) {
        e.consume();
}My question is how i would make my two paddels (this is a simple pong game or in the making) move simultaneously (one paddel up+down same time other paddel up+down), if anyone can give me coded examples, i have been told that KeyBinding will fix this problem but i cannot figure out how to implement it, any help will be great.
Edited by: MichaelDean on Oct 9, 2008 1:43 PM

h1. Please do not cross-post.
[KeyListener query|http://forums.sun.com/thread.jspa?threadID=5338324]
This will frustrate anyone who tries to help you only to find out later that the same answer was given hours ago in a cross-posted thread. For this reason, many volunteers here and at the other sites refuse to help repeat offenders.
If you don't understand what we are talking about with key bindings in your previous post, then ask, but do it in that post.

Similar Messages

  • Problem using KeyListener in a JFrame

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

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

  • Trouble with focus, swing & keyListener

    can anybody out there help me with this problem, I got stuck with:
    I create a JDialog in a JFrame & would like to add Keylistener to the JDialog as soon as it opens..........but the it doesn't seem to be working....

    Oops! As bbhangale pointed out, my previous post is incorrect. It should read as follows:
    dialog.getRootPane().getInputMap...
    dialog.getRootPane().getActionMap...Actually, I've created MyDialog, an abstract sub-class of JDialog. In it, I over-ride the createRootPane() method and delcare the abstract onDialogClose() method. Here's what that looks like:
    public abstract class MyDialog extends JDialog
       // Implement MyDialog wrappers for all the JDialog constructors
       public MyDialog()
          super();
        * Overriding this method to register an action so the 'Esc' key will dismiss
        * the dialog.
        * @return a <code>JRootPane</code> with the appropiate action registered
       protected JRootPane createRootPane()
          JRootPane rootPane = new JRootPane();
          rootPane.getInputMap( JComponent.WHEN_IN_FOCUSED_WINDOW ).
             put( KeyStroke.getKeyStroke( KeyEvent.VK_ESCAPE, 0 ), "escPressed" );
          rootPane.getActionMap().
             put( "escPressed", new AbstractAction( "escPressed" )
             public void actionPerformed( ActionEvent actionEvent )
                onDialogClose();
          return rootPane;
        * This method gets called when the user attemps to close the JDialog via the
        * 'Esc' key.  It is up to the sub-class to implement this method and handle
        * the situation appropriately.
       protected abstract void onDialogClose();
    }Then, anytime I need a dialog, I sub-class MyDialog and implement onDialogClose() to do whatever I want it to do when the user presses 'Esc'.
    I swear I've been using it for quite some time now and it works beautifully!
    Jamie

  • KeyListener..for beginners..please help me

    hi, im new to java..i think that this thing is simple to you guys..im trying to make a program where there is a ball bouncing around the screen..theres 3 walls one on the left one on the right and the other on top..there should be a moving catcher at the bottom..which should be controlled by the keyboard..
    i already made the catcher..my only problem is..i dont know how to make it move..
    by the way..i'm using threading..
    it would be nice if you can post even a simple example of threading with keylistener even just left and right so i would know how to apply it..
    i hope that someone there would help beginners like me, it would really be a big help..
    thank you very much!
    -dennis

    Hi Madhuama, I'll try to give you a hand with this. First off, what OS is running on your notebook, what game are you attempting to play, and how is it not working? Is it not installing?
    Thanks,
    Fenian Frank
    I work on behalf of HP

  • How to add a KeyListener to a JInternalFrame

    1). I have Main Window which is an Application window and has a menu. When I click on a menu option,
    a user interface which is a JInternalFrame type, with JTextFields in it, is loaded.
    2). In the first JTextField(e.g. Employee Number), I have a KeyListener added to the JInternalFrame.
    3). When I enter an Employee number in the JTextField and press the Key F10, I have to fetch the details about the Employee
    (his first name, middle name, last name etc.) from the database and display these details in the corresponding
    JTextFields in the user interface.
    PROBLEM:
    I am able to add a KeyListener to the JInternalFrame but it does not work the way I need it to.
    The moment F10 key is pressed, the JInternalFrame looses focus, and the focus goes to the Main Window and does not execute
    the code for the keyPressed event that is there in the listener.
    How do I overcome this issue??
    The code that I am using is below
    public class TD {
    public void invoke(){
    cFrame = new JInternalFrame("TD Form",
    false, //resizable
    true, //closable
    true, //maximizable
    true);//iconifiable
    // More code here..................
    //Destroy the TD Window.
    cFrame.addInternalFrameListener(new InternalFrameAdapter() {
         public void internalFrameClosing(InternalFrameEvent evt){
                   cancelSteps();
    }); // end of InternalFrameListener.
    cFrame.addKeyListener(new KeyTD(this)); // Adding the KeyListener here to the JInternalFrame
    cFrame.setVisible(true);
    cFrame.setSize(800,450);
    cFrame.setLocation(10,10);
    } // end of the constructor.
    // Inner class that implements the KeyListener
    class KeyTD implements KeyListener {
    private int msg =JOptionPane.INFORMATION_MESSAGE;
    private String title = "KeyPress Event Message";
    Container cornbut;
    TD objTD;
    private int UTNum;
    public KeyTD(TD objTD){
              this.objTD = objTD;
    public void keyPressed(KeyEvent ke){
    int key1 = ke.getKeyCode();
    switch(key1){
    case KeyEvent.VK_F9:
    tD_F9();
    break;
    case KeyEvent.VK_F10:
    UTNum = getNum(); // Reads the content of the JTextField and gets the Integer value
    if (UTNum > 0){
                        tD_F10();
    }else{
    JOptionPane.showMessageDialog(cornbut," Please enter the Number. ",title,msg);
    break;
    }//end of keyPressed method
    public void keyReleased(KeyEvent ke){
    public void keyTyped(KeyEvent ke){
    public void tD_F9(){
    //sets focus to the Text Field where the key listener has been added
    }//end of tD_F9 method
    public void tD_F10(){
    String str = String.valueOf(UTNum);
    Objdbdef.fetchTaskDefiner(str,"", "","" ,"" ,"" ,"" ,"" ,"" ,"" ,"" ,"" ,"" );
    if(//there are records in the database then){                       
    // If there are records matching the number from the JTextField the display statements are here.........
    }else{
    JOptionPane.showMessageDialog(cornbut,"There are no records found for the specified criteria.",title,msg);
    }//end of td_F10 method
    }// end of KeyTD class

    As a rule of thumb, I never use KeyListeners, unless you want to listen to many different key strokes.
    Instead, use ActionMap/InputMap. You can attach an action to, say your desktop, that
    is activated when F1 is pressed WHEN_ANCESTOR_OF_FOCUSED_COMPONENT or
    WHEN_IN_FOCUSED_WINDOW

  • A sort of KeyListener without a GUI Component?

    a sort of KeyListener without a GUI Component? ( or any trick that will do)?
    please be patient with my question
    I can't express myself very well but it's very important.
    Please help me I need an example how to implement
    a way to detect some combination of keystrokes in java without
    any GUI ( without AWT or Swing frames ...)
    just the console (DOS or Linux shell window) or with a minimzed
    java frame (awt or swing...) you know, MINIMIZED= not in focus.
    in other words if the user press ctrl + alt +shift ...or some
    other combination... ANYTIME ,and the java program is running in the
    background, is there a way to detect that,
    ... my problem if I use a frame (AWT or SWING) the windows must
    be in focus and NOT MINIMIZED..
    if I use
    someObject.addKeylistener(someComponent);
    then the "someComponent" must be in focus, am I right?
    What I'm coding is a program that if you highlight ANY text in
    ANY OS window, a java window (frame) should pop up and match the
    selected text in a dictionary file and brings me the meaning
    ( or a person's phone number , or
    a book author ...etc.)
    MY CHALLENGE IS WITHOUT PRESSING (Ctrl+C) to copy and paste
    ...etc. and WITHOUT MONITORING THE OS's CLIPBOARD ...I just want to
    have the feature that the user simply highlight a text in ANY
    window anywhere then press Ctrl+shift or some other combination,
    then MY JAVA PROGRAM IS TRIGGERED and it should EMULATE SOME
    KEYSTROKES OF Ctrl+C and then paste the clipboard
    somewhere in my program...with all that AUTOMATION BEING in the background.
    remember that my whole program ALL THE TIME MUST BE MINIMIZED AND
    NOT IN FOCUS
    or just running in the background (using javaw)..
    is there any trick ? pleeeeeeze!!!
    i'm not trying to write a sort of the spying so-called "key-logger"
    purely in java but it's a very similar challenge.
    please reply if you have questions
    I you could please answer me , then guys this would be very
    valuable technique that I need urgently. Thanks!

    DO NOT CROSS POST especially since this has nothing to do with game development at all. I can understand if it was in Java programming and New to Java but even then pick a forum and post it to that one and that one only.

  • KeyListener anomoly: delay in firing KeyEvent

    Hello,
    I've implemented a KeyListener that's exhibiting some anomolies. I'm using it in a video game. I'm using it to control the main character's movement. It determines his movement based on strokes of the arrow keys. I've programmed it so that only one key has an effect at a time. That is, so long as (say) the up arrow was pressed first and held down, the character moves up, and no other key has an effect. Other keys only have an effect if the up arrow is released.
    The anomoly comes about when two keys are held down (only one of them determining the movement of the character - which ever was first), and then the first is released. When the first is released (but the second is still held down), the character freezes for about a second, and only after that second does he move in the direction of the second key which is still held down.
    It's this second-long delay which is the anomoly. I'm guessing it results from the fact that the KeyEvent is not being fired constantly or immediately after the release of the first key. Even though the second key is held down, it takes a second to fire the KeyEvent after the first key is released (though it seems to fire immediately upon depressing the key).
    I'm wondering if there's a way to get rid of the delay or at least shorten it so it's not noticeable.
    Here's my KeyListener code:
    import java.awt.event.*;
    public class InputProcessor implements KeyListener {
        // key codes
        public static final int      LEFT  = 37;
        public static final int      UP    = 38;
        public static final int      RIGHT = 39;
        public static final int      DOWN  = 40;
        private boolean      left_arrow_down  = false;
        private boolean      right_arrow_down = false;
        private boolean      up_arrow_down    = false;
        private boolean      down_arrow_down  = false;
        // flag to mark when a key (any key) is pressed
        private boolean     key_pressed      = false;
        public InputProcessor() {}
        public void keyPressed (KeyEvent KE) {
         if (key_pressed) return; // all other keys disabled if one key is down
         switch (KE.getKeyCode()) {
             case LEFT:
              left_arrow_down true;
              key_pressed = true;
              break;
             case RIGHT:
              right_arrow_down = true;
              key_pressed = true;
              break;
             case UP:
              up_arrow_down = true;
              key_pressed = true;
              break;
             case DOWN:
              down_arrow_down = true;
              key_pressed = true;
              break;
        public void keyReleased (KeyEvent KE) {
         switch (KE.getKeyCode()) {
             case LEFT:
              left_arrow_down = false;
              break;
             case RIGHT:
              right_arrow_down = false;
              break;
             case UP:
              up_arrow_down = false;
              break;
             case DOWN:
              down_arrow_down = false;
              break;
         // only set key_pressed to false if all keys have been released
         if (!left_arrow_down &&
           !right_arrow_down &&
           !up_arrow_down &&
           !down_arrow_down)
             key_pressed = false;
        public void keyTyped (KeyEvent KE) {}
        public boolean isLeftArrowDown()  {return left_arrow_down;}
        public boolean isUpArrowDown()    {return up_arrow_down;}
        public boolean isRightArrowDown() {return right_arrow_down;}
        public boolean isDownArrowDown()  {return down_arrow_down;}
        public static void main (String[] args) {
         InputProcessor IP = new InputProcessor();
    }I'm wondering if there might be a command I can execute at the end of the keyReleased() method, something like this:
        public void keyReleased (KeyEvent KE) {
         switch (KE.getKeyCode()) {
             case LEFT:
              left_arrow_down = false;
              break;
             case RIGHT:
              right_arrow_down = false;
              break;
             case UP:
              up_arrow_down = false;
              break;
             case DOWN:
              down_arrow_down = false;
              break;
         // only set key_pressed to false if all keys have been released
         if (!left_arrow_down &&
           !right_arrow_down &&
           !up_arrow_down &&
           !down_arrow_down)
             key_pressed = false;
         checkForKeyPressed();
        }Let me know if you'd like a SSCCE.
    Thanks

    It's this second-long delay which is the anomoly. I'm guessing it results from the fact that the KeyEvent is not being fired constantly or immediately after the release of the first key.That's the usual key-repeat behavior on most OSs.
    I'm wondering if there's a way to get rid of the delay Probably by setting booleans in the keyPressed(...) / keyReleased(...) and polling those booleans at equal intervals using a Timer.
    db

  • Some problems with fullscreen, keylistener and bufferstrategy :-)

    Hi.
    I have a few questions.
    I worked a long time trying to make my game run smoothly but I just couldn't get it perfect. I thought it had something to do with the load of graphics I use, but it wasn't the case. Here is what I did:
    public class Game extends Frame implements Runnable, KeyListener {
        int [] controls = new int[256];
        final static int FrameRate = 60;
        final int MiliFrameLength = 1000/FrameRate;
        private long startTime;
        private int frameCount;
        public Game()
            GraphicsDev gd = new GraphicsDev(); // Class that handles the graphics device
            int ref = gd.getDisplayM().getRefreshRate();
            if(fullscreen==1) {
                setUndecorated(true);
                gd.getGraphicsDev().setFullScreenWindow(this);
                gd.getGraphicsDev().setDisplayMode(new DisplayMode(screenWidthX,screenWidthY,24,ref));
            } else if (fullscreen==0) {
                setSize(screenWidthX,screenWidthY);
            addKeyListener(this);
            show();
            createBufferStrategy(2);
            buffer = getBufferStrategy();
            startTime = System.currentTimeMillis();
            frameCount = 0;
            Thread t = new Thread(this);
            t.start();
            update();
        public void update() {
            while(rungame)  {
                Graphics2D gr2D = (Graphics2D)buffer.getDrawGraphics();
                if(controls[40] == 1) moveup(1);
                if(controls[38] == 1) movedown(1);
                if(controls[37] == 1) moveleft(1);
                if(controls[39] == 1) moveright(1);
                paintGraphics(gr2D);
                gr2D.dispose();
                buffer.show();
                frameCount++;
                while((System.currentTimeMillis()-startTime)/MiliFrameLength <frameCount)
                { Thread.yield(); }
        public void keyPressed(KeyEvent ke) {
             controls[ke.getKeyCode()&0xFF] = 1;
        public void keyReleased(KeyEvent ke) {
             controls[ke.getKeyCode()&0xFF] = 0;
          public void keyTyped(KeyEvent ke){}
    }The original code is of cause much bigger, so this is just to show what happens. It's pretty straight forward.
    My problem is that the game only runs completely smooth when it is in fullscreen and v-synched. This means that I have to have a framerate at 60 (same as the refreshrate). It looks great, but my keyboard input can't keep up with this speed. About every 10 sec the game hangs for a while. If I set the framerate or refreshrate lower it doesn�t run smoothly.
    My questions are:
    1: Is it possible to make the keyboard work with a framerate/refreshrate of 60+
    2: Is it possible to use v-synched in window mode?
    3: If yes � How do I do this? ;-)
    Maybe I'm taking a totally wrong approach to this, but everyone seems to have different solution to making a game to run smooth, and right now I'm very confused (was first yesterday I found out about the v-synch).

    I've seen this code before. You're following a standard rendering template right? I've never used the
    while((System.currentTimeMillis()-startTime)/MiliFrameLength <frameCount)
                { Thread.yield(); } method for syncing framerate but here's another suggestion which
    is what I use and my rendering is as smooth as silk even at a monitor refresh rate (and framerate)
    of 85 fps (however, like you, I only go to 60 fps) long framerate = 60;  //i.e. 60 fps
       public final void run(){
          long start_Time = 0;
          long elapsed_Time = 0;
          final Thread t = Thread.currentThread();
          while(t == thread){
             //start_Time = . . .
             render();
             relocate_Sprites();
             sort_Sprites_for_Z_Buffer();
             //elapsed_Time = . . .
             try{
                if(elapsed_Time < 1000/framerate)
                   Thread.sleep(1000/framerate-elapsed_Time);
                else
                   Thread.sleep(3); // without this line, you may starve the gc
             catch(InterruptedException e){
       }This system works perfectly even with 40 Sprites, one of which is like 1050 x 640 in dimensions
    (background which scrolls a bit). My system is not particularly fast:
    -AMD Athlon 1.2 GHz
    -384 MB RAM
    -nVidia GeForce 2 400 MX at 32 MB (this piece is practically extinct now)

  • KeyListener no longer working in JPanel

    Hi,
    I have implemented a graphics interface with JPanel with mouse action and movement captured. Everything works fine until I added KeyListener implementation.
    No matter what I do, I could not enable the key event.
    The top window is a JFrame which contains several components and one of them is a JPanel. I wanted to capture key event inside that JPanel.
    JFrameC a = new JFrameC();
    JPanelC b = new JPanelC(a);
    And inside JPanelC, I have statement as
    a.addKeyListener(this);
    addKeyListener(this);
    But still no key event.
    If I simply change JPanelC class from JPanel to Panel (only extends statement), key event appears as it supposes to be.
    What's wrong with JPanel? I thought it should behave similar to Panel with more better features.
    What should I do to enable key event in JPanel?
    Please help.

    I tried the following simple program which is similar to my complicated implementation and it worked. I am confused.
    <pre>
    //KeyFrame.java
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.*;
    public class KeyFrame extends JFrame {
    public KeyFrame(String s) {
    super(s);
    KeyEventDemo ked = new KeyEventDemo(this);
    getContentPane().add(ked);
    pack();
    show();
    setSize(500, 500);
    validate();
    public static void main(String [] args) {
    KeyFrame kf = new KeyFrame("");
    // KeyEventDemo.java
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.*;
    public class KeyEventDemo extends JPanel
    //implements KeyListener, ActionListener {
    implements KeyListener {
    public KeyEventDemo(Component c) {
    super();
    c.addKeyListener(this);
    //addKeyListener(this);
    /** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e) {
    System.err.println("KEY TYPED: ");
    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
    System.err.println("KEY PRESSED: ");
    /** Handle the key released event from the text field. */
    public void keyReleased(KeyEvent e) {
    System.err.println("KEY RELEASED: ");
    </pre>

  • Cannot get KeyListener to work with JAI ScrollImagePanel

    I am trying to display a TIF image and use the page up and page down keys to show page 1 and page 2 of the image. I started with an example for the JAI documentation.
    The problem is that I can't get the key event listener to "see" keystokes.
    I think ScrollImagePanel() is doing its own event listening and I don't know how to get at it.
    Here is the code:
    // http://java.sun.com/products/java-media/jai/forDevelopers/samples/MultiPageRead.java
    A single page of a multi-page TIFF file may loaded most easily by using the page
    parameter with the "TIFF" operator which is documented in the class comments of
    javax.media.jai.operator.TIFFDescriptor. This example shows a
    means of loading a single page of a multi-page TIFF file using the ancillary codec
    classes directly.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import java.io.IOException;
    import java.awt.image.RenderedImage;
    import java.awt.image.renderable.ParameterBlock;
    import javax.media.jai.*;
    import javax.media.jai.widget.*;
    import com.sun.media.jai.codec.*;
    public class MultiPageRead4 extends Frame
                implements KeyListener {                              //1
        ScrollingImagePanel panel;
        File file = null;
        ImageDecoder dec = null;
        RenderedImage op = null;
        // side to load, 0=front and 1=back
        static int imageToLoad = 0;
        /** The key code to flip between back and front images */
        private static final int FLIP_IMAGE_KEY1 = KeyEvent.VK_PAGE_UP;
        private static final int FLIP_IMAGE_KEY2 = KeyEvent.VK_PAGE_DOWN;
        /** Short cut key to exit the application */
        private static final int EXIT_KEY = KeyEvent.VK_ESCAPE;
        public MultiPageRead4(String filename) throws IOException {  //2
            super("Multi page TIFF Reader");
            // won't work here either
            // addKeyListener(this);
            addWindowListener(new WindowAdapter() {                  //3
               public void windowClosing(WindowEvent we) {           //4
               System.exit(0);
               }                                                     //4
            });                                                      //3
            if(file == null) {                                       //3
                file = new File(filename);
                SeekableStream s = new FileSeekableStream(file);
                TIFFDecodeParam param = null;
                dec = ImageCodec.createImageDecoder("tiff", s, param);
                System.out.println("Number of images in this TIFF: " +
                                   dec.getNumPages());
                // Which of the multiple images in the TIFF file do we want to load
                // 0 refers to the first, 1 to the second and so on.
                // int imageToLoad = 1;
                }                                                    //3
            // display side of tiff indicated by imageToLoad which is initialized to 0
            // and set by page up / page down
            displaySide();
            }                                                         //2
        // Methods required by the KeyListener interface.
         * Process a key being pressed. Does nothing as we wait for the
         * release before moving.
         * @param evt The event that caused this method to be called
        public void keyPressed(KeyEvent evt)
             System.out.println("Key pressed.");   // debug -- see if it works
            // do nothing
         * Process a key being type (press and release). Does nothing as this is
         * always dodgy about when we get the event. Better to look for the
         * release.
         * @param evt The event that caused this method to be called
        public void keyTyped(KeyEvent evt)
             System.out.println("Key typed.");    // debug -- see if it works
            // do nothing
         * Process a key being pressed. Does nothing as we wait for the
         * release before moving.
         * @param evt The event that caused this method to be called
        public void keyReleased(KeyEvent evt)
        {                                                              //2
            System.out.println("Key released.");  // debug -- see if it works
            switch(evt.getKeyCode())
            {                                                         //3
                case EXIT_KEY:
                    System.exit(0);
                    break;
                case FLIP_IMAGE_KEY1:
                   if(imageToLoad == 1) {                             //4
                      imageToLoad = 0;
                      displaySide();
                      break;
                   }                                                  //4
                case FLIP_IMAGE_KEY2:
                   if(imageToLoad == 0) {                             //4
                      imageToLoad = 1;
                      displaySide();
                      break;
                   }                                                  //4
            }                                                         //3
        }                                                             //2
        public void displaySide() {                                   //2
            try {
                op = new NullOpImage(dec.decodeAsRenderedImage(imageToLoad),
                                null,
                                OpImage.OP_IO_BOUND,
                                null);
                }  catch (java.io.IOException ioe) {
                      System.out.println(ioe);
        * Create a standard bilinear interpolation object to be
        * used with the �scale� operator.
           Interpolation interp = Interpolation.getInstance(
                 Interpolation.INTERP_BILINEAR);
        * Stores the required input source and parameters in a
        * ParameterBlock to be sent to the operation registry,
        * and eventually to the �scale� operator.
           ParameterBlock params = new ParameterBlock();
        // params.addSource(image1);
           params.addSource(op);
           params.add(0.70F); // x scale factor
           params.add(0.70F); // y scale factor
           params.add(0.0F); // x translate
           params.add(0.0F); // y translate
           params.add(interp); // interpolation method
        /* Create an operator to scale image1. */
           RenderedOp image2 = JAI.create("scale", params);
        /* Get the width and height of image2 + 3% */
           int width = (int)(image2.getWidth() * 1.03);
           int height = (int)(image2.getHeight() * 1.03);
        /* Attach image2 to a scrolling panel to be displayed. */
           panel = new ScrollingImagePanel(
              image2, width, height);
           panel.addKeyListener(this);
           // Display the original in a 800x800 scrolling window
           // panel = new ScrollingImagePanel(op, 1000, 600);
           add(panel);
           pack();
           show();
                                                                      //2
        public static void main(String [] args) {
            String filename = "034363331.TIF";
            try {
                MultiPageRead4 window = new MultiPageRead4(filename);
                }  catch (java.io.IOException ioe) {
                      System.out.println(ioe);
            System.out.println("finished.");
    // http://java.sun.com/products/java-media/jai/forDevelopers/samples/MultiPageRead.javaI can't get the KeyListener to act (or send the debug messages to System.out.println()).
    If "add( panel );" is removed and the comment before " keyListener(this); " in the constructor the key listening logic works -- of course no image is displayed.
    Thanks for any help.
    Bill Blalock

    Thanks for exanding your explanation. I am not yet skilled enough in Java to follow you completely but I am getting the idea.
    I would appreciate a code snippet using my example so I can better understand. In the mean time I found one way to make it work.
    In the example I eventually found that this change ..
           show();
           panel.requestFocus();enabled the key listener. Bringing the window, even clicking on the panel, didn't give it focus. I understand that the window has to have the focus in order for the key listener to function (different from the mouse listender). I don't understand why the application did not have "focus" even though it was on top and active.
    Oh well, lots to learn.
    Thanks for your suggestion!

  • Adding a KeyListener

    hello all,
    i was doing this homework, and i came upon a point a cant really do. well here is the code:
    package homework;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Draw1 extends JFrame implements MouseMotionListener
    private JRadioButton boldRadio,plainRadio,italicRadio;
    private JTextField textField;
    private Font boldFont, plainFont, italicFont;
    private JComboBox box1;
    private String CB[] = {"Red","Green","Text"};
    private Color ovalColor= Color.RED;
    private String X="";
    public Draw1()
        this.addMouseMotionListener(this);
        Container c=this.getContentPane();
        JPanel p= new JPanel(new FlowLayout());
        boldFont=new Font("Serif" ,Font.BOLD,14);
        plainFont=new Font("Serif" ,Font.PLAIN,14);
        italicFont=new Font("Serif" ,Font.ITALIC,14);
        textField= new JTextField();
        textField.setFont( boldFont );
        box1 = new JComboBox(CB);
        box1.setMaximumRowCount(1);
        box1.addItemListener(
            new ItemListener(){
          public void itemStateChanged(ItemEvent event2){
            if(event2.getStateChange() == ItemEvent.SELECTED)
              if(box1.getSelectedIndex() == 0)
                ovalColor= Color.RED;
              else if(box1.getSelectedIndex() == 1)
                ovalColor= Color.GREEN;
              //else if(box1.getSelectedIndex() == 2)
        boldRadio=new JRadioButton("Bold",true);
        plainRadio=new JRadioButton("Plain",false);
        italicRadio=new JRadioButton("Italic",false);
        RadioButtonHandler handler = new RadioButtonHandler();
        boldRadio.addItemListener(handler);
        plainRadio.addItemListener(handler);
        italicRadio.addItemListener(handler);
        ButtonGroup radioGroup=new ButtonGroup();
        radioGroup.add(boldRadio);
        radioGroup.add(plainRadio);
        radioGroup.add(italicRadio);
        p.add(box1);
        p.add(boldRadio);
        p.add(plainRadio);
        p.add(italicRadio);
        c.add(p,BorderLayout.NORTH);
        c.add(textField,BorderLayout.SOUTH);
        c.setBackground(Color.white);
        this.setSize(300,300);
        this.setVisible(true);
      public static void main(String[] args)
        Draw1 draw11 = new Draw1();
      public void mouseDragged(MouseEvent e)
        Graphics g=this.getGraphics();
        g.setColor(ovalColor);
        g.fillOval(e.getX(),e.getY(),20,20);
      public void mouseMoved(MouseEvent e)
        //TODO: implement this java.awt.event.MouseMotionListener method;
      private class RadioButtonHandler implements ItemListener {
        public void itemStateChanged( ItemEvent event )
            if ( event.getSource() == boldRadio )
               textField.setFont( boldFont );
            else if ( event.getSource() == plainRadio )
               textField.setFont( plainFont );
            else if ( event.getSource() == italicRadio )
               textField.setFont( italicFont );
    }what i need is to add a keylistener, that would be activated when i select "text" from the combobox, and when this listener is active, anything i type should go into the textfield. even if i dont click the textfield.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class test extends JFrame implements MouseMotionListener {
      FieldKeyListener fieldKeyListener = new FieldKeyListener();
      private JRadioButton boldRadio,plainRadio,italicRadio;
      private JTextField textField;
      private Font boldFont, plainFont, italicFont;
      private JComboBox box1;
      private String CB[] = {"Red","Green","Text"};
      private Color ovalColor= Color.RED;
      private String X="";
      private boolean keyListenerIsActive = false;
      int count = 0;
      public test() {
        this.addMouseMotionListener(this);
        Container c=this.getContentPane();
        JPanel p= new JPanel(new FlowLayout());
        boldFont=new Font("Serif" ,Font.BOLD,14);
        plainFont=new Font("Serif" ,Font.PLAIN,14);
        italicFont=new Font("Serif" ,Font.ITALIC,14);
        textField= new JTextField();
        textField.setFont( boldFont );
        textField.addKeyListener(fieldKeyListener);
        box1 = new JComboBox(CB);
        box1.setMaximumRowCount(1);
        box1.addItemListener(new ItemListener(){
          public void itemStateChanged(ItemEvent event2){
            //System.out.println("stateChange" +
            //                    event2.getStateChange());
            if(event2.getStateChange() == ItemEvent.SELECTED)
              if(box1.getSelectedIndex() == 0) {
                ovalColor= Color.RED;
                keyListenerIsActive = false;
              else if(box1.getSelectedIndex() == 1) {
                ovalColor= Color.GREEN;
                keyListenerIsActive = false;
              else if(box1.getSelectedIndex() == 2) {
                // toggle the key listener control boolean
                keyListenerIsActive = !keyListenerIsActive;
                textField.requestFocus(true);
                count = 0;
              System.out.println("keyListenerIsActive = " +
                                  keyListenerIsActive);
        boldRadio=new JRadioButton("Bold",true);
        plainRadio=new JRadioButton("Plain",false);
        italicRadio=new JRadioButton("Italic",false);
        RadioButtonHandler handler = new RadioButtonHandler();
        boldRadio.addItemListener(handler);
        plainRadio.addItemListener(handler);
        italicRadio.addItemListener(handler);
        ButtonGroup radioGroup=new ButtonGroup();
        radioGroup.add(boldRadio);
        radioGroup.add(plainRadio);
        radioGroup.add(italicRadio);
        p.add(box1);
        p.add(boldRadio);
        p.add(plainRadio);
        p.add(italicRadio);
        c.add(p,BorderLayout.NORTH);
        c.add(textField,BorderLayout.SOUTH);
        c.setBackground(Color.white);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocation(400,200);
        this.setSize(300,300);
        this.setVisible(true);
      public void mouseDragged(MouseEvent e)
        Graphics g=this.getGraphics();
        g.setColor(ovalColor);
        g.fillOval(e.getX(),e.getY(),20,20);
      public void mouseMoved(MouseEvent e)
        //TODO: implement this java.awt.event.MouseMotionListener method;
      private class RadioButtonHandler implements ItemListener {
        public void itemStateChanged( ItemEvent event )
          if ( event.getSource() == boldRadio )
            textField.setFont( boldFont );
          else if ( event.getSource() == plainRadio )
            textField.setFont( plainFont );
          else if ( event.getSource() == italicRadio )
            textField.setFont( italicFont );
      class FieldKeyListener implements KeyListener {
        public void keyPressed(KeyEvent e) {
          if(!keyListenerIsActive)
            return;
          System.out.println("keyPressed " + count++);
        public void keyReleased(KeyEvent e) { }
        public void keyTyped(KeyEvent e) { }
      public static void main(String[] args) {
        new test();
    }

  • Command line program: can it implement keyListener??

    Hello,
    before I take the trouble to learn keyListener implementation, I am wondering if my program could even implement it. It is just a small game that just plays in the command window. I would like it to respond to the user pressing up, down, left and right keys. Is this possible with a keyListener or is this only possible in a 'windowed' application?
    And if you cannot register keys this way from the command line, then how would I make my program interactive. Do you know a link to an API description that explains how to set the program up to give a prompt?
    Thank you very much!
    -Mike.

    guess not...

  • JTextField and keyListener

    I'm trying to create an easy way of inputting data in a JTextField. I have a column of textfields, each requiring fixed-length data-input, and the idea is that the user types series of two digits continuously, without having to press ENTER or TAB between them to go to the next textfield. For this I have created a keyListener, in which the length of the textfield is checked. Strangely enough, the length of the textfield always seems to be lagging one character. For instance, I have entered a "1" (which de keyListener registers without fail), but when I check the length of the textfield in the keyListener, it returns 0, and if you do a system-output of the textfield getText, you get an empty string. If I next enter a "2", the length of the textfield is 1 according to the listener, the system-output shows "1", and so on. I am doing anything wrong?

    Well, my point was to post the code that you tested. People make stupid mistakes like using:
    public void KeyReleased(KeyEvent e)
    Note: the capital "K". If you don't post the code you use then we can't help. Myself and others do not have a problem using the keyReleased() method.
    Here's is some working code. It enables/disables some buttons based on whether text is entered in the "Find" text field:
    http://www.discoverteenergy.com/files/FindReplace.java

  • KeyListener not working In Internet Explorer

    I made a small game
    Play it here
    It works fine in Firefox but the KeyListener doesn't work in Internet Explorer.
    I include the applet with this code:
    <!--[if !IE]>-->
    <object classid="java:Shotgun.class"
            type="application/x-java-applet"
            id="ShotgunApplet" >
    <!--<![endif]-->
    <object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
            id="ShotgunAppletIE" >
             <param name="code" value="Shotgun" />
    </object>
    <!--[if !IE]>-->
    </object>
    <!--<![endif]-->But also tried this:
    <applet id='ShotgunApplet' code='Shotgun.class'></applet>
    The full source code is available from here
    Thanks in advance,
    Frederik Vanderstraeten

    --- Solved ---
    Had to remove the e.consume(); in mousePressed()

  • KeyListener- HELP HELP HELP

    I writing a calculator and I use both JButton & keyboard as inputs. The ActionListener with the JButtons is ok, but I have problem with keyboard:
    I have and object 'keylistener' of a class that implements KeyListener and I addKeyListener(keylistener) for all the JButton. But when i start the application, nothing happens when I press anykey, the KeyListener only works after I use mouse to lick to any JButton, and then I can use the keyboard.
    I have many JButton and I group them into JPanels. I tried to addKeyListener(keylistener) for all the JPanels but it did not work, too.
    I think my problem is that no JButton is focused at the beginning. But I don't know how to set a button focused. I tried with requestFocus... methods but they did not help.
    What I have to do now? Please help!!!
    Thank you very much!

    KeyListener is seldom the answer for input tasks. Instead use key binding (InputMap/ActionMap):
    http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html
    Demo:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ButtonExample2 extends AbstractAction implements Runnable {
        public void run() { //build GUI in EDT
            Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_NUM_LOCK, true);
            JPanel panel = new JPanel(new GridLayout(3,3));
            InputMap im = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = panel.getActionMap();
            for(int i=1; i<10; ++i) {
                String text = String.valueOf(i);
                JButton btn = new JButton(text);
                btn.addActionListener(this);
                panel.add(btn);
                //set up action
                String key = "press" + text;
                im.put(KeyStroke.getKeyStroke(text), key); //main keyboard
                im.put(KeyStroke.getKeyStroke("NUMPAD" + text), key); //numpad
                am.put(key, this);
            JFrame f = new JFrame("ButtonExample2");
            f.setContentPane(panel);
            f.pack();
            f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        public void actionPerformed(ActionEvent evt) {
            System.out.println("Pressed: " + evt.getActionCommand());
        public static void main(String[] args) {
            EventQueue.invokeLater(new ButtonExample2());
    }

  • SWF in PDF - keyListener

    All:
    I have a SWF with a keyListener that I am using to toggle the visibility of a movie clip. This works great when I play the SWF in the FlashPlayer.exe.
    When the SWF is placed into a PDF, the mouse events all work great, but the keyListener no longer works.
    Any ideas as to why this might be?
    Matt

    Probably Acrobat had other plans for the key :-)
    No, honestly:
    Try out a rare key like ~ and see if that works
    a second possibility would be: the stage of the swf has no focus or the movieclip you focused has disappeared from stage (so the Event can not bubble up)  If you click on a movieclip to make it disappear, that disappeared moviclip has still the focus, and so naturally keyboardevents won`t work.
    set the EventHandler explicitly to the stage
    stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
    and after clicking on something that gets removed add the following code to your mousehandler (to regain that Overall-focus)
    stage.focus = stage;

Maybe you are looking for

  • Calendar no longer syncing with MacBook Pro

    I have an iCloud account and since moving over to ML, my Calendar on the Mac has been spotty at best. My iPhone syncs with my iCloud account and vice-versa but not so the Mac. I have tried logging out and back in, restarting, etc. Nothing. I have had

  • Itunes wont recognize my 4th gen ipod touch but computer will

    iTunes refuses to recognize my 4th gen. iPod touch. Both are up to date with software and ive restarted my computer, ipod, and itunes multiple times and done everything ive found online. the computer recognizes it and says its working properly, but i

  • CS4 Install errors in Windows 7 - 'ColorProfilesRollback' issue

    I have tried to install CS$ Design Premium about 8 times!  Keep getting, "error as UninstallColorProfilesRollback and referred me to kb403891".   I have tried Solution 4 times.  Does not help.  Finally clicked, "continue" installation, and it appears

  • Custom refiners not translated on Search Page

    Hi, I have created a product catalog site. On the category page i have added some custom refiners, all using the excelent tutorial: http://blogs.technet.com/b/tothesharepoint/archive/2013/06/20/stage-15-add-refiners-for-faceted-navigation-to-a-publis

  • Re: screen

    Hi,     what is the difference between call screen and leave to screen. rgds p.kp