About keylistener

i have a JFrame which i add a keylistener to it. After which i add a JPanel to the JFrame which contains JButton in it, the keylistener does not work anymore. The JButton needs to add keylistener in order for it to works.
whats wrong with the keylistener? do i have to add keylistener to all component i have which allow user input?
thanks in advance.

Adding a Keylistener to a JFrame or infact to any container is not the best, since this hidden under several layers of components which will intercept the input before it ever reaches the JFrame.
Hence the best place to add a keylistener would be on the component that you expect input on. Also, this component must be focussed for this to work.
Alternatively, using a KeyMap - ActionMap pair is better option
ICE

Similar Messages

  • Strange Problem about KeyListener, and FocusListener

    Hi,Please help me with this problem.
    I create a JTable and setCellEditor by using my customerized TextField
    The problem is: when I edit JTable Cell, the value can not be changed and I can not get Key Event and Focus Event.
    here is my source:
    //create normal JTable instance,and then initlize it
    private void initTable(Vector folders)
    TableColumn tempcol = getColumnModel().getColumn(0);
    tempcol.setCellEditor(new DefaultCellEditor(new MyTextField()));
    for(int i=0;i<folders.size();i++)
    mddDataSource ds=(mddDataSource) folders.get(i);
    String name = ds.getDataSourceName();
    layers.add(name);
    for(int i=0;i<layers.size();i++){
    Vector temp = new Vector();
    temp.add(layers.get(i));
    temp.add(layers.get(i));
    dtm.addRow(temp);
    // My Text Field cell
    class MyTextField extends JTextField implements FocusListener, KeyListener
    MyTextField()
    setOpaque (false);
    addKeyListener(this);
    addFocusListener(this);
    MyTextField(String text)
    setOpaque (false);
    addKeyListener(this);
    addFocusListener(this);
    public void focusGained(FocusEvent e) {
    System.out.println("get Focus");
    public void focusLost(FocusEvent e) {
    instance.setValue(getText());
    public void keyTyped(KeyEvent e){
    instance.setValue(getText());
    public void keyPressed(KeyEvent e){
    System.out.println("get Key ");
    public void keyReleased(KeyEvent e){
    instance.setValue(getText());
    If there are some good sample, please tell me the link or give me some suggestion.
    Thanks in advanced

    Thanks for your help.
    The problem still exist. It does not commit the value that I input.
    Maybe I should say it clearly.
    I have create JPanel include three JPanel:
    Left Panel and right upper-panel and right borrom panel.
    The JTable instance is on right-upper Panel.
    If I edit one of row at JTable and then click JTable other row,the value can be commited. if I edit one of row and then push one Button on
    the right-bottom button to see the editting cell value.It does not commit value.
    when I use debug style, and set breakpoint the
    foucsGained or KeyTyped,
    It never stopes at there,So I assume that the Editing cell never get focus.
    Is there a bug at Java if we move focus on other Panel, that JTable can not detect the Focus lost or focus gained event?
    Thanks

  • JMF and keylistener

    I guys, i'm new in jmf (fobs)world. I have coding a simple video player. My question is:
    is it possible to stop/play/pause the video whit keyboard? I'm thinking about keylistener but while the video is playing i can't I am not able to access the function to stop the video flow (is JMF blocking?).
    thanks in advance and sorry for my bad English
    regards.
    emanuele

    post your JMF question on that forum:
    http://forum.java.sun.com/forum.jspa?forumID=28

  • Swing?help me...

    1 how I build a link to url?
    I want to build a link in the panel.when click this link,open a
    IE window to the url,how?
    2 how I build a combined shortcut keys?
    yes,now I have a textfiled,I hope when a user press"ALT+S",the
    words pressed can be send out.I can use keycode to link this
    operation with "enter","s",but how can i do it with a combined
    shortcut keys?
    3 how I set up a textArea display image and text?
    like msn messenger,I want to build a display interface not only
    show text,but also show image.I also hope the text's size and
    color can differ from each other.could a textArea do it?how?
    4 scroller auto scroll downward?
    there is a scrollpane contains a textarea,i hope when many message
    included in the textarea and scrolling happens,the scroller always
    scroll downward,how can i do it?
    thanks a lot,hope your help...

    First of all you need to read several topics.
    1. You can set the link text as text of some component and listen for clicks (MouseListener, MouseEvent)
    For browsers read [url http://www.javaworld.com/javaworld/javatips/jw-javatip66.html]this.
    2. Read about KeyListener, KeyEvent and maybe also about ActionMap/InputMap and how they can be used to assign KeyStrokes to components
    3. JEditorPane can render HTML
    4. You can set the scroll position programatically (JScrollPane has a vertical JScrollBar that you can manipulate)
    Maybe read some [url http://www.angelfire.com/dc/shish/answers.html]stuff on asking questions also...
    Hope that helps
    Mike

  • Showing user input in a JFrame

    i need to be able to take user-given values and display them in a JFrame. i'm testing the input of a sudoku puzzle. i have a sudokuComponent and a sudokuViewer.
    i'm confused as to where to place my code that will do the process of taking user input (via Scanner class) and testing it for certain conditions.
    i dont think figuring out the testing conditions should be hard, i'm just having trouble with getting the input read in correctly and a way of getting it displayed on the JFrame which displays the sudoku puzzle with the values so far.
    i was given a tip that said i needed to use the method repaint() of JFrame to see the updates.
    SUDOKUCOMPONENT
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.geom.Line2D;
    import javax.swing.JPanel;
    import javax.swing.JComponent;
    import java.util.Scanner;
    public class SudokuComponent extends JComponent
         public void paintComponent(Graphics g)
              //recover graphics2s
              Graphics2D g2 = (Graphics2D) g;
              //Construct the Sudoku square
              Rectangle box = new Rectangle(20, 20, 270, 270);
              g2.draw(box);
              g2.draw(new Line2D.Double(20, 110, 290, 110)); //horizontal
              g2.draw(new Line2D.Double(20, 200, 290, 200));
              g2.draw(new Line2D.Double(110, 20, 110, 290)); //vertical
              g2.draw(new Line2D.Double(200, 20, 200, 290));
    }SUDOKUVIEWER
    import javax.swing.JFrame;
    import java.util.Scanner;
    public class SudokuViewer
       public static void main(String[] args)
          JFrame frame = new JFrame();
          final int FRAME_WIDTH = 350;
          final int FRAME_HEIGHT = 350;
          frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
          frame.setTitle("Sudoku Viewer");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          SudokuComponent component = new SudokuComponent();
          frame.add(component);
          frame.setVisible(true);
    }

    I have improved your application to show how it can be programmed.
    For more information you can see about
    KeyListener:
    http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html
    MouseListener:
    http://java.sun.com/docs/books/tutorial/uiswing/events/mouselistener.html
    and of course use repaint() when you want to update your component
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.geom.Line2D;
    import java.util.LinkedList;
    import java.util.List;
    import javax.swing.JComponent;
    public class SudokuComponent extends JComponent {
        SudokuElement currentElement = new SudokuElement();
        List<SudokuElement> elementList = new LinkedList<SudokuElement>();
        public SudokuComponent(){
            addMouseListener(new MyMouseListener());
            setFocusable(true);
            addKeyListener(new MyKeyListener());
        public void paintComponent(Graphics g) {
            //public void paint(Graphics g) {
            //recover graphics2s
            Graphics2D g2 = (Graphics2D) g;
            //Construct the Sudoku square
            Rectangle box = new Rectangle(20, 20, 270, 270);
            g2.draw(box);
            g2.draw(new Line2D.Double(20, 110, 290, 110)); //horizontal
            g2.draw(new Line2D.Double(20, 200, 290, 200));
            g2.draw(new Line2D.Double(110, 20, 110, 290)); //vertical
            g2.draw(new Line2D.Double(200, 20, 200, 290));
            // show place where user can type a digit
            g2.draw(new Line2D.Double(currentElement.x - 10, currentElement.y, currentElement.x + 10, currentElement.y));
            // show all typed digits
            for(SudokuElement elem : elementList ){
               g2.drawString(elem.digit + "", elem.x, elem.y);
        class SudokuElement {
            int digit;
            int x;
            int y;
            SudokuElement getCopy(){
                SudokuElement elem = new SudokuElement();
                elem.x = x;
                elem.y = y;
                elem.digit= digit;
                return elem;
        class MyMouseListener extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                System.out.println("mouse clicked: x = "  + e.getX() + " y = " + e.getY());
                currentElement.x = e.getX();  // It is better to use local coordinats 0 .. 9
                currentElement.y = e.getY();
                repaint(); 
        class MyKeyListener extends KeyAdapter {
            public void keyTyped(KeyEvent e) {
                char ch = e.getKeyChar();
                System.out.println("char typed= " + ch);
                if( Character.isDigit(ch) ){  // Filter only digits
                    currentElement.digit = Character.digit(ch, 10);
                    elementList.add(currentElement.getCopy());
                    repaint();
    }

  • How to enable only copy

    Hi,
    I want users to be only able to copy from my textpane, I started reading about keylistener and carretlistener and got confused, I would thank some guidance to the right way.
    Noa

    never mind
    I wasn't concentrated -
    setEditable(false);
    setEnabled(true);

  • 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);
    }

  • 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

  • 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)

  • 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!

  • JButton keeps JFrame from succesfully implementing KeyListener?!

    Look at this code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame implements KeyListener
         private JButton myButton;
         public Test()
              Container c = getContentPane();
              c.setLayout( new FlowLayout() );
              myButton = new JButton();
              myButton.setEnabled( true );
              c.add( myButton );
              addKeyListener( this );
              setSize( 100, 100 );
              show();
         public void keyPressed( KeyEvent e )
                System.out.println( "keyPressed" );
         public void keyReleased( KeyEvent e )
              System.out.println( "keyReleased" );
         public void keyTyped( KeyEvent e )
              System.out.println( "keyTyped" );
         public static void main( String args[] )
              Test window = new Test();
    }When you execute this program, the JFrame does not resolve keystrokes. It should though, because it implements KeyListener and overrides all required methods. But here is the strange thing: Try changing
    myButton.setEnabled( true );to
    myButton.setEnabled( false );Now the JFrame is able to respond to keystrokes by executing the proper methods! But what use is a button if it is not enabled. I need my buttons in the JFrame, but I also need the JFrame to respond to the keystrokes.
    Anyone know about this problem and how to solve it??
    Thank you!

    ?? Say you want to make a small game. A square is drawn onto the frame. The user presses the up button on the keybord and the square 'moves' up (it is repainted at a different coordinate). But the user also needs to be able to (re)start the game and exit through the use of JButtons. That is the purpose and the problem is stated in my first post...
    Anyone else has an idea?
    thx

  • Keylistener in MIDP?

    I am writing a MIDlet for cell phones/Blackberries. I want to be able to intercept the escape button (specifically on the Blackberry) and prompt the user to save/don't save/cancel. Unfortunately, there is no Keylistener in MIDP as far as I know. There are Blackberry specific APIs that fulfill this need, but I don't want to make the MIDlet specific to a Blackberry, so I can't use them.
    Has anyone found a way to implement a Keylistener in MIDP? I was reading something about kAWT that sounded possible, but I really don't know much about it. Can anyone help me? Is there an easy way to write my own Keylistener?
    Any help would be greatly appreciated.

    The only way to "implement a KeyListener" in MIDP 1.0, is to have a Canvas subclass as the active displayable, and implement the method keyPressed() (in the Canvas subclass). Otherwise you're stuck with the high level UI with all it's querks...
    But anyway, to capture the escape button you'll need to use some platform specific code, since there is no keycode defined for special keys in MIDP 1.0.
    shmoove

  • Strange problem with Java KeyListener

    Hi everyone,
    I basically have a JFrame which implements KeyListener .
    Initially it recognizes when a key is pressed and typed, etc. But after I click a button on the frame, it stops recognizing any further keyEvents.
    Any thoughts?
    Thanks!

    Taking your advice, I used key bindings with the following code:
    InputMap im = new InputMap();
               im.put(KeyStroke.getKeyStroke("control F"), "pressed");
               im.setParent(this.getInputMap(JComponent.WHEN_FOCUSED));
                  this.setInputMap(JComponent.WHEN_FOCUSED, im);
                  this.getActionMap().put("pressed",
                          new AbstractAction("pressed") {
                              public void actionPerformed(ActionEvent evt) {
                                  System.out.println("pressed");
                      );For now, it still only triggers when the JPanel is in focus. I'm not sure how to go about implementing it so that the keys trigger regardless of whether the JPanel is focused.

  • Confused about painting in Java2D

    HI, I'm trying to get a simple app - note I don't want to do this in an Applet - that displays some text on screen and then exits when a key is pressed. I don't know how to get it to paint if I just call paint() from the class constructor it complains about the parameter.
    paint(java.awt.Graphics) cannot be applied to ()
    If I try to call paint from the calling class I get the same problem.
    Do I need a JPanel and if so, what for? Where should I use paint() and not paintComponent() or vice versa and what's the difference? I've seen pieces of code which draw without a JPanel or JFrame but I don't know how those work. Here's what I've got so far:
    public class Controller
        public CallingClass
         Intro intro = new Intro();
        public static void main(String[] args)
         Controller callingClass = new CallingClass;
    import java.awt.*;
    import java.awt.Color;
    public class Intro
        public  Intro()
         paint();
        public void paint(Graphics g)
            setBackgrond(Color.black);
            g.setColor(Color.green);
            g.drawString("Blah",512,20);
            g.drawString("Blah",20,60);
            g.drawString("Blah",20,80);
            g.drawString("Blah",20,120);
            g.drawString("Blah",20,140);
            g.drawString("Blah",20,160);
            g.drawString("Blah",20,180);
            g.drawString("Press F  to start or q to quit",20,200);
        public void keyDown(Event e, int key)
            switch(key)
                case 'F':
                    //MainClass mainClass = new MainClass();   //ignore this
                    break;
                case 'Q':
                    System.exit(0);
                    break;
    }I know I sound like a noob but I'm having trouble finding this sort of information.

    I just used the keyDown()
    method so I wouldn't have to override the methods for
    the KeyListener interface.Well you should still use a KeyListener.
    I followed BinaryDigit's
    advice, but I'm still confused, do I need both a
    JFrame and JPanel to draw to the screen?You should have your Intro class extend JPanel (and override paintComponent(), not paint()). You should then use that JPanel as the content pane in a JFrame. And remember to call repaint(), not paint() or paintComponent().

Maybe you are looking for

  • What is the best way to restore the entire contents of Mac HD?

    After installing Snow Leopard my iMovie 6 project went haywire. As I found that others had the same problem, I backed up Mac HD with TM, and then re-installed Leopard using the erase procedure. After that I couldn't access my TM backups via TM, so I

  • Suspending transactions

              Hi. I'm running WL 6.1 sp1, connecting to an oracle db. There are several places           in my application where information, including exception error messages, is being           logged to the db. The problem is that when an exception o

  • IPhoto 08 and Deleting Files

    I recently upgraded from iLife 06 to ILife 08 and having major problems with new version of *IPhoto 08.* First and foremost, messages began showing that my startup disk is almost full and to delete unwanted files. I'm assuming this is happening becau

  • I can't help thinking i should know the answer to this...

    How do I initiallise a long string across more than one line in the editor? (CVI 5.0.1).

  • How to get PL/SQL output in Excelsheet & preserve trailing zero for VARCHAR

    Hi All, I am trying to get the PL/SQL procedure out put to Excel sheet, I have wrote below code and it worked fine. CREATE OR REPLACE PROCEDURE plsql_to_excel_demo IS CURSOR cur_stock_details IS SELECT * FROM stocks; outfile UTL_FILE.file_type; l_chr