KeyListener implementation

I am trying to implement a key listener for the first time, and having trouble. Can you please look at the following code snippet and tell me what's wrong?
void meth1()throws Exception{
this.addKeyListener(new KeyListener (){
public void keyPressed(KeyEvent e){
this_keyPressed(e);
public void keyReleased(KeyEvent e) {
this_keyReleased(e);
public void keyTyped(KeyEvent e) {
this_keyTyped(e);
}//end meth1
public void this_keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_F7)
System.out.println("HelloWorld!!");
public void this_keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_F7)
System.out.println("key released!");
public void this_keyTyped(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_F7)
System.out.println("key typed!");
Thanks....

What are you adding the KeyListener to? i.e., which class are you extending with the class you have posted a section from?

Similar Messages

  • KeyListener implementation problems

    Hi,
    I'm working on a project for my Java class and I'm starting with a simple program and implementing each new part as I go along because I need to learn most of it by myself, the teacher is an idiot. Anyways, the program is a tetris game and I need it to be able to identify when the user presses the directional keys for movement and rotation. I know I need to implement a KeyListener, but when I set it up, I get this error:
    .\tetris.java:28: game_panel is not abstract and does not override abstract method keyPressed(java.awt.event.KeyEvent) in java.awt.event.KeyListener class game_panel extends JPanel implements KeyListener
    ^
    Here is the class where I implemented the KeyListener:
    class game_panel extends JPanel implements KeyListener
         public game_panel()
              setPreferredSize(new Dimension(300,600));
              setBackground(Color.black);
              setFocusable(true);
              addKeyListener(this);
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              g.drawRect(0,0, getSize().width - 1, getSize().height - 1);
         public void keyReleased(KeyEvent e)
              if(e.getKeyCode()==KeyEvent.VK_RIGHT)
                   System.out.println("Right key pressed");
    }Its pretty basic, but I don't think I'm missing any parts. The game_panel class is instantiated here:
    public class tetris extends JApplet
         public void init()
              setLayout(new FlowLayout());
              JPanel panel = new game_panel();
              JPanel panel2 = new control_panel();
              add(panel);
              add(panel2);
    }Any ideas? It could be something simple, I have no clue what is wrong? Thanks ahead of time.

    KeyListener is an Interface. When you implement an interface, you must define all methods that are in the interface.
    Link:
    http://java.sun.com/j2se/1.5.0/docs/api/java/awt/event/KeyListener.html
    KeyListener contains 3 methods you must define bodies for.
    It looks like you have defined 1 of them so far.
         public void keyReleased(KeyEvent e)Now you need the other two.

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

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

  • JSplitPane Active Side and KeyListener

    I have a JSplitPane as my root in a JFrame. The left side is a JTabbedPane and the right is a custom JPanel. The JPanel has its own KeyListener implemented; however key strokes are going to the left JTabbedPane. If i switch the two sides, putting the custom JPanel on the left, the keystrokes work as desired. This is not the most desirable fix though. Does anyone know how to change the "active" side of the JSplitPane?

    The JPanel has its own KeyListener implemented; however key strokes are going to the left JTabbedPane.I find this hard to believe. I'm guessing your have a programming bug and since you didn't post any code I don't know how we can help you.
    Post your [url http://www.physci.org/codes/sscce.jsp]Simple Executable Demo Code so we can see this unwanted behaviour.

  • Help with simple shooter game

    I am doing a school project and no one seems to know how to use graphics, sound, and most importantly KEY AND MOUSE EVENTS.
    Anyways I can't get my events for the mouse and keyboard to work correctly, so if anyone knows what is wrong or has some suggestions I would really appreciate it. Here is the code:
    the program is called from an application just so you know... this is the application:
    public class AnimateTest
    public static void main (String[] args)
    Animate pic = new Animate (10);
    //and this is the proram itself
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.MouseListener.*;
    import java.awt.event.MouseAdapter.*;
    import java.awt.event.MouseEvent.*;
    import java.awt.event.KeyAdapter.*;
    import java.awt.event.KeyListener.*;
    import java.awt.event.KeyEvent.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.applet.AudioClip;
    public class Animate extends Frame //implements KeyListener//implements MouseListener
    // The image of the background.
    protected Image background;
    // The gun images.
    protected Image gun1, gun2, gun3, gun4, gun5, gun6, gun7, gun8, gun9, gun10;
    //the status bar images
    protected Image hpbox;
    protected Image scorebox;
    //declares the blood explosion image
    protected Image blood;
    //declares the window icon
    protected Image icon;
    // The canvas where the images are drawn.
    protected AnimatePictureCanvas canvas;
    // The number of guns.
    protected int numGuns;
    // Flag to indicate when to quit.
    protected boolean quitting = false;
    //declares the cursor so it can be set to a targeting reticle
    Cursor reticle;
    //declares a variable which designates which gun is in use
    int i = 0;
    //the user's health points
    int hp = 100;
    //enemy arrays
    boolean alive [];
    boolean onScreen [];
    //enemy integers
    int currentDude = 3;
    int liveCount = 10;
    int screenCount = 0;
    //damage variables
    int damage = 0;
    int moreHits;
    int chance;
    //the x and y coordinates of the enemies
    int ex1 = 175;
    int ex2 = 345;
    int ex3 = 520;
    int ex4 = 25;
    int ex5 = 240;
    int ex6 = 370;
    int ex7 = 470;
    int ex8 = 626;
    int ex9 = 260;
    int ex10 = 120;
    int ey1 = 228;
    int ey2 = 190;
    int ey3 = 115;
    int ey4 = 210;
    int ey5 = 35;
    int ey6 = 330;
    int ey7 = 202;
    int ey8 = 192;
    int ey9 = 210;
    int ey10 = 140;
    //blood variables
    int splat = 0;
    int bloodx = -100;
    int bloody = -100;
    // The constructor. Create the Frame, make it visible, load the
    // images, and when the images are loaded, call the animate method
    // to move the images around the window.
    public Animate (int numGuns)
    super ("Stupid Shooting Game"); // Create a Frame.
    //sets the window icon
    icon = getToolkit ().getImage ("icon.jpg");
    prepareImage (icon, this);
    setIconImage (icon);
    this.numGuns = numGuns;
    //initialize the arrays for the enemies
    alive = new boolean [10];
    for (int z = 0 ; z <= 9 ; z++)
    alive [z] = true;
    onScreen = new boolean [10];
    onScreen [0] = true;
    onScreen [1] = true;
    onScreen [2] = true;
    onScreen [3] = false;
    onScreen [4] = false;
    onScreen [5] = false;
    onScreen [6] = false;
    onScreen [7] = false;
    onScreen [8] = false;
    onScreen [9] = false;
    //initialize the cursor to make the mouse a targeting reticle
    reticle = new Cursor (Cursor.CROSSHAIR_CURSOR);
    setCursor (reticle);
    // Place the loading message in the window.
    Label loadingMessageLabel = new Label ("Loading images...");
    add ("North", loadingMessageLabel);
    // Display the window.
    pack ();
    setVisible (true);
    // Create the Images and add them to the tracker.
    MediaTracker tracker = new MediaTracker (this);
    background = getToolkit ().getImage ("midtown1.jpg");
    tracker.addImage (background, 0);
    //prepares the gun images for the image tracker
    gun1 = getToolkit ().getImage ("ggun1.jpg");
    tracker.addImage (gun1, 1);
    gun2 = getToolkit ().getImage ("ggun2.jpg");
    tracker.addImage (gun2, 2);
    gun3 = getToolkit ().getImage ("ggun3.jpg");
    tracker.addImage (gun3, 3);
    gun4 = getToolkit ().getImage ("ggun4.jpg");
    tracker.addImage (gun4, 4);
    gun5 = getToolkit ().getImage ("ggun5.jpg");
    tracker.addImage (gun5, 5);
    gun6 = getToolkit ().getImage ("ggun6.jpg");
    tracker.addImage (gun6, 6);
    gun7 = getToolkit ().getImage ("ggun7.jpg");
    tracker.addImage (gun7, 7);
    gun8 = getToolkit ().getImage ("ggun8.jpg");
    tracker.addImage (gun8, 8);
    gun9 = getToolkit ().getImage ("ggun9.jpg");
    tracker.addImage (gun9, 9);
    gun10 = getToolkit ().getImage ("ggun0.jpg");
    tracker.addImage (gun10, 10);
    //prepares the status bar images for the tracker
    hpbox = getToolkit ().getImage ("hpbox.jpg");
    tracker.addImage (hpbox, 11);
    scorebox = getToolkit ().getImage ("scorebox.jpg");
    tracker.addImage (scorebox, 12);
    //prepares the blood image
    blood = getToolkit ().getImage ("splash.jpg");
    tracker.addImage (blood, 13);
    // Load the images.
    try
    tracker.waitForAll ();
    catch (InterruptedException e)
    // This exception will not happen in our program, but
    // Java requires that we handle it anyway.
    System.out.println ("Wait interrupted.");
    if (tracker.isErrorAny ())
    loadingMessageLabel.setText ("Image loading failed!");
    else
    // All the images are now loaded. Remove the loading label.
    remove (loadingMessageLabel);
    // Create and place the canvas.
    canvas = new AnimatePictureCanvas (background);
    canvas.setSize (background.getWidth (null),
    background.getHeight (null));
    add ("Center", canvas);
    pack (); // Resize the Frame to fit the canvas.
    validate (); // Force the Frame to be redrawn.
    animate ();
    } // Animate constructor
    // Move the bouncers over the background.
    public void animate ()
    // Create the offscreen bitmap.
    int bgWidth = background.getWidth (null);
    int bgHeight = background.getHeight (null);
    Image offscreen = this.createImage (bgWidth, bgHeight);
    // Get the width and height of the guns.
    int gun1Width = gun1.getWidth (null);
    int gun1Height = gun1.getHeight (null);
    int gun2Width = gun2.getWidth (null);
    int gun2Height = gun2.getHeight (null);
    int gun3Width = gun3.getWidth (null);
    int gun3Height = gun3.getHeight (null);
    int gun4Width = gun4.getWidth (null);
    int gun4Height = gun4.getHeight (null);
    int gun5Width = gun5.getWidth (null);
    int gun5Height = gun5.getHeight (null);
    int gun6Width = gun6.getWidth (null);
    int gun6Height = gun6.getHeight (null);
    int gun7Width = gun7.getWidth (null);
    int gun7Height = gun7.getHeight (null);
    int gun8Width = gun8.getWidth (null);
    int gun8Height = gun8.getHeight (null);
    int gun9Width = gun9.getWidth (null);
    int gun9Height = gun9.getHeight (null);
    int gun10Width = gun10.getWidth (null);
    int gun10Height = gun10.getHeight (null);
    //finds the width and height of the status bar images
    int hpboxWidth = hpbox.getWidth (null);
    int hpboxHeight = hpbox.getHeight (null);
    int scoreboxWidth = scorebox.getWidth (null);
    int scoreboxHeight = scorebox.getHeight (null);
    // Create the arrays containining the location and
    // direction of the bouncers.
    int locX;
    int locY;
    // Initialize the gun Image's location
    locX = (bgWidth - gun1Width);
    locY = (bgHeight - gun1Height);
    // Get the graphics contexts for both the offscreen image and
    // the canvas.
    Graphics offscreenG = offscreen.getGraphics ();
    Graphics canvasG = canvas.getGraphics ();
    while (!quitting)
    //sets the mouse listener to check for shots being fired
    addMouseListener (new MouseAdapter ()
    public void mouseClicked (MouseEvent e)
    int xClick = e.getX ();
    int yClick = e.getY ();
    System.out.println (" " + xClick + " " + yClick);
    delay (1000000);
    fire (xClick, yClick);
    //sets the keylistener to check for a change in the current gun
    // addKeyListener (new KeyAdapter ()
    // public void keyTyped (KeyEvent e)
    // if (e.getKeyChar () == 'f')
    // i += 1;
    // if (i == 10)
    // i = 0;
    // if (e.getKeyChar () == 'd')
    // i -= 1;
    // if (i == -1)
    // i = 9;
    // Draw the background image to the offscreen bitmap, erasing
    // everything that is already there.
    offscreenG.drawImage (background, 0, 0, null);
    //draw the status bar at the bottom of the screen
    offscreenG.setColor (Color.black);
    offscreenG.fillRect (0, bgHeight - gun1Height, bgWidth, bgHeight);
    // Draw each bouncer to the offscreen image. Move each of
    // the bouncers, changing their direction when they encounter
    // an edge.
    offscreenG.drawImage (gun1, locX, locY, null);
    //draws the status bar
    offscreenG.drawImage (hpbox, 15, bgHeight - gun1Height + 10, null);
    offscreenG.drawImage (scorebox, hpboxWidth + 15 + 20, bgHeight - gun1Height + 25, null);
    //draws blood if a target is hit
    if (splat == 1)
    offscreenG.drawImage (blood, bloodx, bloody, null);
    delay (10000000);
    splat = 0;
    if (hp == 0)
    //drawString "you lose"
    break;
    else
    //determines the number of enemies still alive
    liveCount = 10;
    for (int a = 0 ; a <= 9 ; a++)
    if (alive [a] == true)
    else
    liveCount -= 1;
    if (liveCount == 0)
    //drawString "you win... get ready for LVL 2!!!"
    break;
    //determines the number of enemies onscreen and adds more if necessary
    screenCount = 0;
    for (int b = 0 ; b <= 9 ; b++)
    if (onScreen == true)
    screenCount += 1;
    if (screenCount < 3 && liveCount > 3)
    onScreen [currentDude] = true;
    if (currentDude == 9)
    else
    currentDude += 1;
    damage = 0;
    moreHits = 12 / screenCount;
    chance = (int) (Math.random () * moreHits) + 1;
    if (chance == moreHits)
    damage = 10;
    //sets the default color to white so things can be seen on the background
    offscreenG.setColor (Color.white);
    //checks all the enemies to see if they are alive and onscreen,
    //drawing them accordingly
    if (alive [0] == true && onScreen [0] == true)
    offscreenG.fillOval (ex1, ey1, 18, 18);
    if (alive [1] == true && onScreen [1] == true)
    offscreenG.fillOval (ex2, ey2, 13, 13);
    if (alive [2] == true && onScreen [2] == true)
    offscreenG.fillOval (ex3, ey3, 9, 9);
    if (alive [3] == true && onScreen [3] == true)
    offscreenG.fillOval (ex4, ey4, 15, 15);
    if (alive [4] == true && onScreen [4] == true)
    offscreenG.fillOval (ex5, ey5, 11, 11);
    if (alive [5] == true && onScreen [5] == true)
    offscreenG.fillOval (ex6, ey6, 30, 30);
    if (alive [6] == true && onScreen [6] == true)
    offscreenG.fillOval (ex7, ey7, 10, 10);
    if (alive [7] == true && onScreen [7] == true)
    offscreenG.fillOval (ex8, ey8, 10, 10);
    if (alive [8] == true && onScreen [8] == true)
    offscreenG.fillOval (ex9, ey9, 7, 7);
    if (alive [9] == true && onScreen [9] == true)
    offscreenG.fillOval (ex10, ey10, 10, 10);
    // Finally, draw the offscreen image to the canvas.
    canvasG.drawImage (offscreen, 0, 0, null);
    } // animate method
    public void delay (int d)
    for (int x = 1 ; x <= d ; d++)
    public void fire (int x, int y)
    splat = 1;
    bloodx = x;
    bloody = y;
    //play a sound
    //show bloody explosion
    //check to see if a stick man is alive and onscreen
    // Called by the system when an event occurs. Handle the
    // window's close box being pressed by halting the program.
    public boolean handleEvent (Event evt)
    if (evt.id == Event.WINDOW_DESTROY)
    quitting = true; // Set the flag so the animate loop will exit.
    setVisible (false); // Hide the window.
    System.exit (0);
    return true;
    return super.handleEvent (evt);
    } // handleEvent method
    } /* Animate */
    // The "AnimatePictureCanvas" class.
    // This class draws the image passed into its constructor, although it needs
    // only do so when the screen needs repainting.
    class AnimatePictureCanvas extends Canvas
    Image background; // The parent Frame containing all the image info.
    public AnimatePictureCanvas (Image background)
    this.background = background;
    } // AnimatePictureCanvas constructor
    // The paint method is called whenever the canvas needs to be redrawn.
    public void paint (Graphics g)
    g.setColor (Color.black);
    setBackground (Color.black);
    g.drawImage (background, 0, 0, null);
    } // paint method
    } /* AnimatePictureCanvas class */

    I wrote this a while ago so that i would not have to create events for every applet i created, instead I just extended this code. Since applet itself extends panel, you can just drop it anywhere you want (eg in a frame) and use its methpods. Otherwise you can change the code so that you extend frame/Jframe/...
    * EventApplet.java
    * Created on October 7, 2001, 10:55 PM
    package com.moss.util;
    import java.applet.Applet;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ContainerAdapter;
    import java.awt.event.ContainerEvent;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    /** Library that provides a set of handlers for most events.
    * @author  [Black Flag]
    * @version 1.0
    public class EventApplet extends Applet
        /** deals with component events
        public final void setComponentListeners()
            addComponentListener(new ComponentAdapter()
                public void componentResized(ComponentEvent evt)
                    formComponentResized(evt);
                public void componentMoved(ComponentEvent evt)
                    formComponentMoved(evt);
                public void componentShown(ComponentEvent evt)
                    formComponentShown(evt);
                public void componentHidden(ComponentEvent evt)
                    formComponentHidden(evt);
        /** Deals with container events
        public final void setContainerListeners()
            addContainerListener(new ContainerAdapter()
                public void componentAdded(ContainerEvent evt)
                    formComponentAdded(evt);
                public void componentRemoved(ContainerEvent evt)
                    formComponentRemoved(evt);
        /** Deals with focus events
        public final void setFocusListeners()
            addFocusListener(new FocusAdapter()
                public void focusGained(FocusEvent evt)
                    formFocusGained(evt);
                public void focusLost(FocusEvent evt)
                    formFocusLost(evt);
        /** Deals with key events
        public final void setKeyListeners()
            addKeyListener(new KeyAdapter()
                public void keyTyped(KeyEvent evt)
                    formKeyTyped(evt);
                public void keyPressed(KeyEvent evt)
                    formKeyPressed(evt);
                public void keyReleased(KeyEvent evt)
                    formKeyReleased(evt);
        /** Deals with mouse events
        public final void setMouseListeners()
            addMouseListener(new MouseAdapter()
                public void mousePressed(MouseEvent evt)
                    formMousePressed(evt);
                public void mouseReleased(MouseEvent evt)
                    formMouseReleased(evt);
                public void mouseClicked(MouseEvent evt)
                    formMouseClicked(evt);
                public void mouseExited(MouseEvent evt)
                    formMouseExited(evt);
                public void mouseEntered(MouseEvent evt)
                    formMouseEntered(evt);
        /** Deals with mouse motion events
        public final void setMouseMotionListeners()
            addMouseMotionListener(new MouseMotionAdapter()
                public void mouseMoved(MouseEvent evt)
                    formMouseMoved(evt);
                public void mouseDragged(MouseEvent evt)
                    formMouseDragged(evt);
        /** Override to provide this event
         * @param evt The event
        public void formComponentResized(ComponentEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentMoved(ComponentEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentShown(ComponentEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentHidden(ComponentEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentAdded(ContainerEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentRemoved(ContainerEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formFocusGained(FocusEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formFocusLost(FocusEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formKeyTyped(KeyEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formKeyPressed(KeyEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formKeyReleased(KeyEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMousePressed(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseReleased(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseClicked(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseExited(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseEntered(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseMoved(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseDragged(MouseEvent evt)
    }You will probably want to declare those last methods abstract. i didn't because i just couldn't be arsed.
    have fun.

  • Anyone have/know of a method that would format a textbox?

    Hi all,
    I'm currently trying to make a java tax program. It's not finished, obviously. I'm using ready to program. Here is what I want to do. I want to take the amount in the subtotal box, and as the user is typing, after the key is pressed, the program will check to see if it is an actual number, and if there are strings in it, the computer will automatically knock them out and leave a number. Now, this is supposed to be a currency amount... Any suggestions? Here is my code:
    // The "JavaTax" class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.text.DecimalFormat;
    public class JavaTax extends JFrame
        private Container contents;
        private JLabel amount, total, gsttotal, psttotal, hsttotal, qsttotal;
        private JTextField amountBox, totalBox, gsttotalBox, psttotalBox, hsttotalBox, qsttotalBox;
        private JPanel totals, selection;
        private JButton calc;
        private JCheckBox gst, hst, pst, qst;
        private JComboBox pstProvinces, hstProvinces;
        private String provincesPST[] = new String [5];
        private String provincesHST[] = new String [3];
        private double QSTRATE = 7.5;
        double subTotal = 0;
        public JavaTax ()
            super ("Java Tax");
            contents = getContentPane ();
            contents.setLayout (new BorderLayout ());
            provincesPST [0] = "British Columbia (7%)";
            provincesPST [1] = "Saskatchewan (5%)";
            provincesPST [2] = "Manitoba (7%)";
            provincesPST [3] = "Ontario (8%)";
            provincesPST [4] = "Prince Edward Island (10%)";
            provincesHST [0] = "New Brunswick (13%)";
            provincesHST [1] = "Newfoundland (13%)";
            provincesHST [2] = "Nova Scotia (13%)";
            hsttotal = new JLabel ("HST Total:", JLabel.RIGHT);
            qsttotal = new JLabel ("QST Total:", JLabel.RIGHT);
            gsttotal = new JLabel ("GST Total:", JLabel.RIGHT);
            psttotal = new JLabel ("PST Total:", JLabel.RIGHT);
            total = new JLabel ("Total:", JLabel.RIGHT);
            amount = new JLabel ("Amount:", JLabel.RIGHT);
            psttotalBox = new JTextField ("", 10);
            psttotalBox.setEditable (false);
            hsttotalBox = new JTextField ("", 10);
            hsttotalBox.setEditable (false);
            gsttotalBox = new JTextField ("", 10);
            gsttotalBox.setEditable (false);
            qsttotalBox = new JTextField ("", 10);
            qsttotalBox.setEditable (false);
            totalBox = new JTextField ("", 10);
            amountBox = new JTextField ("", 10);
            calc = new JButton ("Calculate");
            gst = new JCheckBox ("GST");
            pst = new JCheckBox ("PST");
            hst = new JCheckBox ("HST");
            qst = new JCheckBox ("QST");
            pstProvinces = new JComboBox (provincesPST);
            hstProvinces = new JComboBox (provincesHST);
            //HST only in NB, Newfoundland and NS (all 13%)
            //QST only in Quebec (7.5%)
            // sample = new JLabel (new ImageIcon("file.jpg"))
            hsttotal.setForeground (Color.BLACK);
            psttotal.setForeground (Color.BLACK);
            gsttotal.setForeground (Color.BLACK);
            total.setForeground (Color.BLACK);
            amount.setForeground (Color.BLACK);
            hsttotal.setOpaque (true);
            gsttotal.setOpaque (true);
            psttotal.setOpaque (true);
            total.setOpaque (true);
            amount.setOpaque (true);
            totals = new JPanel ();
            totals.setLayout (new GridLayout (6, 2, 2, 10));
            contents.add (totals, BorderLayout.WEST);
            totals.add (amount);
            totals.add (amountBox);
            totals.add (gsttotal);
            totals.add (gsttotalBox);
            totals.add (psttotal);
            totals.add (psttotalBox);
            totals.add (hsttotal);
            totals.add (hsttotalBox);
            totals.add (qsttotal);
            totals.add (qsttotalBox);
            totals.add (total);
            totals.add (totalBox);
            selection = new JPanel (new GridLayout (7, 1, 2, 10));
            contents.add (selection, BorderLayout.EAST);
            selection.add (gst);
            selection.add (pst);
            selection.add (pstProvinces);
            selection.add (hst);
            selection.add (hstProvinces);
            selection.add (qst);
            selection.add (calc);
            setSize (500, 350);
            setVisible (true);
            NormalTaxHandler nth = new NormalTaxHandler ();
            SpecialTaxHandler sth = new SpecialTaxHandler ();
            TextFieldHandler tfh = new TextFieldHandler ();
            gst.addItemListener (nth);
            pst.addItemListener (nth);
            hst.addItemListener (sth);
            qst.addItemListener (sth);
            amountBox.addKeyListener (tfh);
        public static void main (String[] args)
            JavaTax guey = new JavaTax ();
            guey.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        } // main method
        public class TextFieldHandler implements KeyListener
            //implementation of KeyListener methods
            public void keyPressed (KeyEvent e)
            public void keyReleased (KeyEvent e)
                check (e);
            public void keyTyped (KeyEvent e)
            public void check (KeyEvent e)
                try
                    subTotal = Double.parseDouble (amountBox.getText ());
                    DecimalFormat df = new DecimalFormat ("#.##");
                    //subTotal =
                    //subTotal = subTotal * 100;
                    //subTotal = ((int)subTotal)/100;
                    amountBox.setText (String.valueOf (df.format (subTotal)));
                    subTotal = Double.parseDouble (amountBox.getText ());
                catch (NumberFormatException nfe)
                    DecimalFormat df = new DecimalFormat ("#.##");
                    amountBox.setText (String.valueOf (df.format (subTotal)));
                    subTotal = Double.parseDouble (amountBox.getText ());
                subTotal = Double.parseDouble (amount);
                subTotal = subTotal * 100;
                subTotal = (int) subTotal / 100;
        private class NormalTaxHandler implements ItemListener
            public void itemStateChanged (ItemEvent ie)
                JCheckBox source = (JCheckBox) ie.getSource ();
                // If the object is selected . . .
                if (ie.getStateChange () == ItemEvent.SELECTED)
                    qst.setVisible (false);
                    hst.setVisible (false);
                    hstProvinces.setVisible (false);
                else
                    if (pst.isSelected () == false && gst.isSelected () == false)
                        qst.setVisible (true);
                        hst.setVisible (true);
                        hstProvinces.setVisible (true);
        private class SpecialTaxHandler implements ItemListener
            public void itemStateChanged (ItemEvent ie)
                JCheckBox source = (JCheckBox) ie.getSource ();
                if (ie.getStateChange () == ItemEvent.SELECTED)
                    gst.setVisible (false);
                    pst.setVisible (false);
                    pstProvinces.setVisible (false);
                    if (qst.isSelected () == true && hst.isSelected () == false)
                        hst.setVisible (false);
                        hstProvinces.setVisible (false);
                    else if (hst.isSelected () == true && qst.isSelected () == false)
                        qst.setVisible (false);
                else
                    if (hst.isSelected () == false || qst.isSelected () == false)
                        gst.setVisible (true);
                        pst.setVisible (true);
                        pstProvinces.setVisible (true);
                        hst.setVisible (true);
                        qst.setVisible (true);
                        hstProvinces.setVisible (true);
         * Create a MaskFormatter for FormattedTextFields
        protected MaskFormatter createFormatter (String s)
            MaskFormatter formatter = null;
            try
                formatter = new MaskFormatter (s);
            } // try
            catch (java.text.ParseException exc)
            } // catch
            return formatter;
        } // MaskFormatter method
    } // GUI class

    You can use Integer.parseInt(String) (or Double.parseDouble(String), etc.) to check if the String represents a number.
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
    If it doesn't, you can use Character.isDigit(char) to check each char, and substring them out if they aren't digits. Then parse it again.
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html#isDigit(char)

  • Mouse Event Listeners with Full Screen JMF

    I am trying to call the mouseClicked function from JMFs addMouseListner API in order to stop a media file when a user clicks the mouse button (or a key) like in a screensaver
    I am able to access the function just before the player is started but once the media file begins to play I am not?
    Here is the code I am using for the player and listener:
    public static void main(String[] argv) {
    JMF myFrame = new JMF("Java Media Framework Project");
    myFrame.setUndecorated(true);
    myFrame.show();
    Dimension screenDim =Toolkit.getDefaultToolkit().getScreenSize();
    myFrame.setSize(screenDim.width, screenDim.height);
    myFrame.setResizable(false);
    myFrame.addMouseListener(
    new MouseAdapter(){
    public void mouseClicked(MouseEvent e) {
    System.out.println("Mouse was clicked");
    System.exit(0);
    myFrame.play();
    Are there any other methods to get around this? Is it possible to embed a JMF application in a window that I can then monitor mouse events from??

    I passed the player object to a Listener class and I can get it to work ok with keyboard controls so Im sure the thread is not being blocked...but my problem still exists in being able to monitor mouse events within the JMF display while the media is being played at full screen. (i.e. in order to stop the media)
    Maybe I can use the ControllerListener within the JMF player to monitor mouse events? Any ideas on how I do this?
    Is it possible to layer the display with a transparent window from which I can monitor mouse events from?
    You mentioned asynchronical playback...I am looking into this idea, are there any examples of this on the web I can look at?
    Thanks for your speedy reply also!!
    Regards,
    Joe
    public static void main(String[] argv) {
    JMF myFrame = new JMF("Java Media Framework Project");
    myFrame.setUndecorated(true);
    myFrame.show();
    Dimension screenDim =Toolkit.getDefaultToolkit().getScreenSize();
    myFrame.setSize(screenDim.width, screenDim.height);
    myFrame.setResizable(false);
    myFrame.new Listener(myFrame);
    myFrame.play();
    public class Listener implements KeyListener,
    MouseListener,
    MouseMotionListener,
    WindowListener {
    private JMF owner;
    Listener(JMF w) {
    owner = w;
    owner.addMouseListener(this);
    owner.addKeyListener(this);
    owner.addMouseMotionListener(this);
    //owner.addWindowListener(this);
    private void stop() { owner.stop(); }
    //---------- KeyListener Implementation ------------------
    public void keyPressed (KeyEvent evt) { stop(); System.out.println("key pressed");}
    public void keyReleased(KeyEvent evt) { stop(); }
    public void keyTyped (KeyEvent evt) { stop(); }
    //---------- MouseListener Implementation ----------------
    public void mouseClicked (MouseEvent e) { stop(); System.out.println("Mouse clicked");}
    public void mousePressed (MouseEvent e) { stop(); }
    public void mouseReleased(MouseEvent e) { stop(); }
    public void mouseEntered (MouseEvent e) { }
    public void mouseExited (MouseEvent e) { }
    //---------- MouseMotionListener Implementation ----------
    public void mouseDragged(MouseEvent e) { }
    public void mouseMoved (MouseEvent e) {
    if (oldMouse == null)
    oldMouse = new Point(e.getX(), e.getY());
    else if (e.getX() != oldMouse.x
    || e.getY() != oldMouse.y)
    stop();
    Point oldMouse;
    //---------- WindowListener Implementation ---------------
    public void windowOpened (WindowEvent e) { stop(); }
    public void windowClosing (WindowEvent e) { stop(); }
    public void windowClosed (WindowEvent e) { stop(); }
    public void windowIconified (WindowEvent e) { stop(); }
    public void windowDeiconified(WindowEvent e) { stop(); }
    public void windowActivated (WindowEvent e) { stop(); }
    public void windowDeactivated(WindowEvent e) { stop(); }
    }

  • Problem in enabling numkeypad as mouse cursor

    Robot robot=new Roobot();
    robot.keyPress(KeyEvent.VK_ALT);
    robot.keyPress(KeyEvent.VK_ SHIFT);
    robot.keyPress(KeyEvent.VK_NUM_LOCK);
    robot.keyPress(KeyEvent.VK_NUMPAD2);
    This code is used for moving the mouse cursor but it is not working.
    It is under the robot class.
    pls tell me about the solution to move the mouse cursor?

    Here is one that will move your cursor according to the arrow keys you press
    PLEASE NOTE: I use Solaris 10 x64 and Java 1.6.0_07 and the key bindings are not correct so you'll have to change them to what your system uses.
    import java.awt.AWTException;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.InputEvent;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.MouseInfo;
    import java.awt.Point;
    import java.awt.Robot;
    import java.awt.Toolkit;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    public class JClick {
      int iPress = 0;
      int ixMax = 0;
      int iyMax = 0;
      Robot r;
      public JClick(){
        buildJClickUI();
        try{
          r = new Robot();
        }catch(AWTException ae){
          System.out.println(ae.toString());
        Timer t = new Timer(20, new ActionListen()); //Controls the cursor movement rate across the screen
        t.start();
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        ixMax = d.width;
        iyMax = d.height;
      public void buildJClickUI(){
        JFrame f = new JFrame("JClick 1.0");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setPreferredSize(new Dimension(200, 67));
        JPanel p = new JPanel();
        JButton b = new JButton("Close");
        b.addMouseListener(new MouseListen());
        b.addKeyListener(new KeyListen());
        p.add(b);
        f.add(p);
        f.pack();
        f.setVisible(true);
      public void robotMouse(){
        int x = 0;
        int y = 0;
        Point p = MouseInfo.getPointerInfo().getLocation();
        switch (iPress){
          case  KeyEvent.VK_LEFT:      x = p.x - 1;
                                     if(x < 0) x = 0;
                                     r.mouseMove(x, p.y);
                                     break;
          case  KeyEvent.VK_RIGHT:    x = p.x + 1;
                                     if(x > ixMax) x = ixMax;
                                     r.mouseMove(x, p.y);
                                     break;
          case    KeyEvent.VK_DOWN: y = p.y + 1;
                                     if(y > iyMax) y = iyMax;
                                     r.mouseMove(p.x, y);
                                     break;
          case    KeyEvent.VK_UP:  y = p.y - 1;
                                     if(y < 0) y = 0;
                                     r.mouseMove(p.x, y);
                                     break;
          case KeyEvent.VK_SPACE:    iPress = KeyEvent.VK_SPACE;
                                     r.mousePress(InputEvent.BUTTON1_MASK);
                                     try{
                                       Thread.sleep(50);
                                     }catch(InterruptedException e){
                                       System.out.println(e.toString());
                                     r.mouseRelease(InputEvent.BUTTON1_MASK);
                                     break;
          default: break;
      public static void main(String[] args) {
        JClick c = new JClick();
      class KeyListen implements KeyListener{ //rem class that is in focus gets events
        KeyListen(){
        public void keyPressed(KeyEvent e){
          switch (e.getKeyCode()){
            case  KeyEvent.VK_UP:
            case KeyEvent.VK_ALT:      iPress = KeyEvent.VK_UP;
                                       break;
            case  KeyEvent.VK_DOWN:
            case KeyEvent.VK_SHIFT:    iPress = KeyEvent.VK_DOWN;
                                       break;
            case    KeyEvent.VK_RIGHT:
            case KeyEvent.VK_NUM_LOCK: iPress = KeyEvent.VK_RIGHT;
                                       break;
            case    KeyEvent.VK_LEFT:
            case KeyEvent.VK_NUMPAD2:  iPress = KeyEvent.VK_LEFT;
                                       break;
            case KeyEvent.VK_SPACE:    iPress = KeyEvent.VK_SPACE;
                                       break;
            default: break;
          if(iPress>0) robotMouse();
        public void keyReleased(KeyEvent e){
          iPress = 0;
        public void keyTyped(KeyEvent e){
      class MouseListen implements MouseListener{
        MouseListen(){
        public void mouseClicked(MouseEvent e){
          JButton b = (JButton)e.getComponent();
          if(b.getText().equals("Close")) System.exit(0);
        public void mouseEntered(MouseEvent e){
        public void mouseExited(MouseEvent e){
        public void mousePressed(MouseEvent e){
        public void mouseReleased(MouseEvent e){
      class ActionListen implements ActionListener{
        ActionListen(){
        public void actionPerformed(ActionEvent e){
          if(iPress > 0) robotMouse();
    }

  • SAX parsing and loops problem

    Hi!
    I currently have an XML file which looks like this:
    <jel>
    <admin creation="Fri Nov 09 17:14:55 GMT 2007" xsdversion="1.0.0" version="1.0.0"/>
    &#8722;
         <jelclass superclass="Object" visibility="public" package="" superclassfulltype="java.lang.Object" fulltype="Player" type="Player">
    &#8722;
         <implements>
    <interface fulltype="java.awt.event.ActionListener" type="ActionListener"/>
    <interface fulltype="java.awt.event.KeyListener" type="KeyListener"/>
    </implements>
    &#8722;
         <methods>
    &#8722;
         <constructor visibility="public" name="Player">
    &#8722;
         <params>
    <param name="newProtocol" fulltype="NewProtocol" type="NewProtocol"/>
    <param name="x" fulltype="int" type="int"/>
    <param name="y" fulltype="int" type="int"/>
    </params>
    </constructor>
    &#8722;
         <method visibility="public" name="actionPerformed" fulltype="void" type="void">
    &#8722;
         <params>
    <param name="e" fulltype="java.awt.event.ActionEvent" type="ActionEvent"/>
    </params>
    </method>
    &#8722;
         <method visibility="public" name="keyPressed" fulltype="void" type="void">
    &#8722;
         <params>
    <param name="e" fulltype="java.awt.event.KeyEvent" type="KeyEvent"/>
    </params>
    </method>
    &#8722;
         <method visibility="public" name="keyReleased" fulltype="void" type="void">
    &#8722;
         <params>
    <param name="e" fulltype="java.awt.event.KeyEvent" type="KeyEvent"/>
    </params>
    </method>
    &#8722;
         <method visibility="public" name="keyTyped" fulltype="void" type="void">
    &#8722;
         <params>
    <param name="e" fulltype="java.awt.event.KeyEvent" type="KeyEvent"/>
    </params>
    </method>
    <method visibility="public" name="getX" fulltype="int" type="int"/>
    &#8722;
         <method visibility="public" name="setX" fulltype="void" type="void">
    &#8722;
         <params>
    <param name="x" fulltype="int" type="int"/>
    </params>
    </method>
    <method visibility="public" name="getY" fulltype="int" type="int"/>
    &#8722;
         <method visibility="public" name="setY" fulltype="void" type="void">
    &#8722;
         <params>
    <param name="y" fulltype="int" type="int"/>
    </params>
    </method>
    </methods>
    </jelclass>And I have SAX parsing code that looks like this:
    public class SaxParser{
          private HashSet <String>packageSet = new HashSet<String>();
          private ArrayList <String> classList = new ArrayList<String>();
          private ArrayList <String> packageList = new ArrayList<String>();
          private ArrayList <String> methodList = new ArrayList<String>();
          private Object[] packageNames;
          private HashMap <String, ArrayList> h = new HashMap <String, ArrayList>();
          public SaxParser()throws Exception{
              String fname = "eclipse/jel.xml";
             DefaultHandler handler = new DefaultHandler()
                 private int numberOfClasses = 0;
             public void startElement(String namespaceURI,String localName, String qname, Attributes attrs)
                  if(qname.equals("jelclass")) {
                       numberOfClasses ++;
                  for(int i = 0; i< attrs.getLength();i++){
                        if(attrs.getQName(i).equals("type")){
                             classList.add(attrs.getValue(i));
                             if(attrs.getQName(i).equals("package")){
                                  packageList.add(attrs.getValue(i));
                                  packageSet.add(attrs.getValue(i));
                  for(int i = 0; i< attrs.getLength();i++){
                       for(int j = 0; j < classList.size(); j++){
              if(attrs.getQName(i).equals("type") && attrs.getValue(i).equals(classList.get(j))){
                  if(qname.equals("method")){
                        if(attrs.getQName(i).equals("name")){
                                    h.put(classList.get(i), methodList.add(attrs.getValue(i));
                   packageNames = new String[packageSet.size()];
                  packageNames = packageSet.toArray();
             public void endElement(String namespaceURI,String localName, String qname){}};
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();
            saxParser.parse(new File(fname), handler);
         public int getPackageNumber(){
              return packageSet.size();
         public Object[] getPackageNames(){
              return packageNames;
         public ArrayList getPackageList(){
              return packageList;
         public ArrayList getClassList(){
              return classList;
         public ArrayList getMethodList(){
              return methodList;
          public static void main(String[] args)throws Exception{
               new SaxParser();
    }I am currently pulling out the package names, pulling out the classnames and then mapping these in a separate class - this works because the class and package names are declared in the same line, so if a package name appears in the package list 7 times, i know this package has 7 classes, and therefore i count the first 7 classes out of an array of all the classes and know that these are the right 7 for that package. However, the methods are a bit different:
    What I would like to do is to: for every class make a hashmap which maps the class name onto an arraylist of the methods, but i think i'm getting confused with my for loops. Or even just keep a tally of how many methods each class has, then I can work it out as i did with the packages -> classes.
    Does anyone know where im going wrong, or have any ideas at all?
    Thank you for your time,
    beccy
    :)

    I don't know if stacks are specifically mentioned in any SAX documentation.
    Basically, SAX sends you a stream of XML elements (open and close tags, characters, etc.), but it doesn't know anything about the underlying XML structure. You have to add that part (usually -- sometimes when writing a SAX application, you don't really care about the XML structure). XML structure is a tree.
    If you've ever written a recursive function that spans a tree, you'll have an idea what to do. You can use a stack to keep track of where you are in the tree. For example, if you open tag A, then you're "in" the A element for subsequent content in that document; if you then open tag B, you're in the B element; but when you close the B tag, you need the stack to tell you that now you're back in the A element.
    You may not need stacks, but it's likely. Find a good tutorial about SAX that mentions stacks and you'll be fine.
    Edited by: paulcw on Nov 14, 2007 4:09 PM

  • KeyEvent.consume() doesn't work

    I have JFormattedTextField subclassed and implement a KeyListener to avoid typing invalid characters. so i implemented:
         * Implements KeyListener.
        public void keyPressed(KeyEvent event) {
            System.out.println("keyPressed: "+event);
            //verify:
            int keyCode = event.getKeyCode();
            switch (keyCode) {
            case KeyEvent.VK_T :
                System.out.println("valid: "+keyCode);
                break;
            default:
                System.out.println("invalid: "+keyCode);
                event.consume();
                break;
        }//keyPressed()The system out's are correct ("valid", "invalid"), but the invalid characters are still typed in the textfield - even though i call event.consume(). ?

    i had to introduce a class variable as a flag and also implement the other methods of KeyListener:
         * Implements KeyListener.
        public void keyPressed(KeyEvent event) {
            //verify:
            int keyCode = event.getKeyCode();
            switch (keyCode) {
            case KeyEvent.VK_T :
            case KeyEvent.VK_ESCAPE :
                isKeyConsumed = false;
                break;
            default:
                event.consume();
                isKeyConsumed = true;
                break;
        }//keyPressed()
         * Implements KeyListener.
        public void keyTyped(KeyEvent event) {
            if (isKeyConsumed) {
                event.consume();
        }//keyTyped()
         * Implements KeyListener.
        public void keyReleased(KeyEvent event) {
           if (isKeyConsumed) {
               event.consume();
        }//keyReleased()not pretty, but it works as expected.

  • 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

  • How to implement a keyListener in JSF/JSP

    Hello,
    I�m using JSC and want to implement a keyListener in my application. I want to press ENTER and a method in my java class should be called (regardless of the component, which has the focus). Is this possible (normally, a component must have the focus for that)?
    I can get the pressed key using javascript but how can I call the corresponding java method? And if I use javascript, that means that a UI-component should gain the focus first to call its javascript method. In this case I don`t even need javascript, because I need a general possibility to catch a key pressed event.
    Thanks for suggestions

    Hi Dan,
    Here is some key listner code that makes sure the user only enters numbers. Maybe you can change it for the return button (I think the charCode of the return button is 10, btw)
    <script type="text/javascript">
    function checkIt(evt)      
         var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
         if (charCode > 31 && (charCode < 48 || charCode > 57))
              alert("Please make sure entries are numbers only.");
              return false;
              return true;
    </script>And in the h:inputText I have onkeypress="return checkIt(event)"
    Cheers,
    Illu

  • Keylistener broken when applet implemented into application

    I am currently trying to imbed my "Game" into an application to make a game menu for it. However, when
    i try and do this the game loads fine but my keylistener doesnt work.
    I am using the code.
    import java.awt.*;
    import java.applet.*;
    public class RunApplets_BROKEN
    public static void main (String [] args)
    Applet myApplet = new Bomberman_Version_Aplha_EDITABLE (); // define applet of interest
    Frame myFrame = new Frame ("Applet Holder"); // create frame with title
    // Call applet's init method
    myApplet.init ();
    // add applet to the frame
    myFrame.add (myApplet, BorderLayout.CENTER);
    myFrame.setSize (500, 600);
    myFrame.setVisible (true); // usual step to make frame visible
    } // end main
    } // end class
    I am wondering if the problems exists in where i am calling the keylister into the application but it does not call
    the methods (such as keylistener), altho i call the init method in the application. Do i have to call the keypressed and such methods also?

    The way you are approaching this is not a good idea though.
    Don't try and plug an applet into a Frame. It's not that simple. An applet has a context for example and yours doesn't. If you have a program that you want to use as both an applet and an application then you should make your applet just behave as the bootstrapping component and take your GUI stuff to another class. Then you can use this common class (maybe a JPanel/Panel) in multiple places (Frame, Applet, etc).

  • Keylistener breaks when implementing applet into application

    I am currently trying to imbed my "Game" into an application to make a game menu for it. However, when
    i try and do this the game loads fine but my keylistener doesnt work.
    I am using the code.
    import java.awt.*;
    import java.applet.*;
    public class RunApplets_BROKEN
    public static void main (String [] args)
    Applet myApplet = new Bomberman_Version_Aplha_EDITABLE (); // define applet of interest
    Frame myFrame = new Frame ("Applet Holder"); // create frame with title
    // Call applet's init method
    myApplet.init ();
    // add applet to the frame
    myFrame.add (myApplet, BorderLayout.CENTER);
    myFrame.setSize (500, 600);
    myFrame.setVisible (true); // usual step to make frame visible
    } // end main
    } // end class
    I know this is bad programming and i am trying to keep it simple, however when i do this to my other program it works fine. So i dont understand. Could anyone please help?

    Intentional multi-post
    [http://forums.sun.com/thread.jspa?threadID=5360722]
    You were given two answers yesterday. Don't start a new thread because you didn't like them, that just wastes peoples time.

Maybe you are looking for