Adding a KeyListener

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

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

Similar Messages

  • Adding a keyListener to an entire Frame

    Hello, any idea's here are warmly appreciated..
    What've got is paint function, that paint 9 boxes on a screen, and then 1 letter in each box. There's no textfield or buttons or anything else, just a for loop calling 9 fillRect and drawString functions.
    Now, what I want to do is attach a KeyListener to the entire Frame containg this paint function, so that whenever the frame/program is in use and highlighted by the user, keyEvents [KeyPressed] triggers actions in my paint function.
    I've tried adding KeyListener to the frame itself and the class containing the paint function (the same way as I would a MouseListener)
    and simply having it doing a system.Out - but there's nothing happening.
    I know there's somethin wrong, but I havnt a notion of what it is.
    Any ideas at all????
    Thanks

    Hello Exception13,
    [..if your still there]
    I've looked up everythin I could about addWindowFocusListener, but I coudnt find anything about how you could use one capture keyEvents.
    In fact, I couldn't find much of a description about them at all. Could you tell me when exactly the window is in focus. ie when the mouse is ocer it, or when it is the active window??

  • Adding a KeyListener to java applet

    I'm going to post this again, because I didn't really understand the last answer.. I know how to add KeyListeners to textfields and buttons, etc, but how do I add it to the applet itself.. I want to do this because I have a painted box on the screen and I want it to move its position everytime I hit the up key.. But I can't add the keylistener to anything but textfields and stuff. I dont know how to do it. Can u please help.. Someone told me JApplet.addKeyListener(this); but I tried it and it didn't work.. It gave me an error cannot find symbol JApplet, I dont have a variable for my whole applet, and I'm not sure how to create one either. Can anyone help?

    I'm going to post this again, because I didn't really
    understand the last answer.. That's no excuse for cross posting.
    http://forum.java.sun.com/thread.jspa?threadID=5215206

  • 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

  • Adding a JButton when there's a paint method

    I'm creating a game application, sort of like a maze, and I want to add buttons to the levelOne panel to be able to move around the maze. When I add the buttons to the panel they don't appear, I assume the paint method is the reason for this. here's my code, I have 3 files, ill post the user_interface, and the levels class, where the level is created and where i tried to add the button. I tried putting the buttons in a JOptionPane, but then my JMenu wouldn't work at the same time the OptionPane was opened. If anyone knows a way around this instead, please let me know. I also tried using a separate class with a paintComponent method in it, and then adding the button (saw on a forum, not sure if it was this one), but that didn't work either. Also, if there is a way just to simply have the user press the directional keys on the keyboard and have the program perform a certain function when certain keys are pressed, I'd like to know, as that would solve my whole problem. Thanks.
    //Libraries
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    public class User_Interface extends JFrame
    static Levels l = new Levels ();
    static Delay d = new Delay ();
    private Container contentPane = getContentPane ();
    private JPanel main, levelOne;
    private String level;
    private CardLayout cc = new CardLayout ();
    private GridBagConstraints gbc = new GridBagConstraints ();
    private JPanel c = new JPanel ();
    private String label = "MainMenu";
    public User_Interface ()
    //Generates the User-Interface
    super ("Trapped");
    main = new JPanel ();
    GridBagLayout gbl = new GridBagLayout ();
    main.setLayout (gbl);
    c.setLayout (cc);
    // set_gbc (gbc, 2, 2, 5, 5, GridBagConstraints.NONE);
    c.add (main, "Main Page");
    contentPane.add (c, BorderLayout.CENTER);
    cc.show (c, "Main Page");
    levelOne = new JPanel ();
    levelOne.setLayout (new GridBagLayout ());
    levelOne.setBackground (Color.black);
    c.add (levelOne, "LevelOne");
    JMenuBar menu = new JMenuBar ();
    JMenu file = new JMenu ("File");
    JMenu help = new JMenu ("Help");
    JMenuItem about = new JMenuItem ("About");
    JMenuItem mainmenu = new JMenuItem ("Main Menu");
    mainmenu.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    cc.show (c, "Main Page");
    label = "MainMenu";
    JMenuItem newGame = new JMenuItem ("New Game");
    newGame.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    l.xCord = 2;
    l.yCord = 2;
    l.xLoc = 140;
    l.yLoc = 140;
    JPanel entrance = new JPanel ();
    entrance.setLayout (new FlowLayout ());
    c.add (entrance, "Entrance");
    label = "Entrance";
    level = "ONE";
    cc.show (c, "Entrance");
    JMenuItem loadgame = new JMenuItem ("Load Game");
    JMenuItem savegame = new JMenuItem ("Save Game");
    JMenuItem exit = new JMenuItem ("Exit");
    exit.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    JFrame frame = new JFrame ();
    frame.setLocation (10, 10);
    JOptionPane.showMessageDialog (frame, "Come Back Soon!", "TRAPPED", JOptionPane.INFORMATION_MESSAGE);
    System.exit (0);
    file.add (about);
    file.add (mainmenu);
    file.add (newGame);
    file.add (loadgame);
    file.add (savegame);
    file.add (exit);
    menu.add (file);
    menu.add (help);
    setJMenuBar (menu);
    //Sets the size of the container (columns by rows)
    setSize (750, 550);
    //Sets the location of the container
    setLocation (10, 10);
    //Sets the background colour to a dark blue colour
    main.setBackground (Color.black);
    //Makes the container visible
    setVisible (true);
    public void paint (Graphics g)
    super.paint (g);
    g.setColor (Color.white);
    if (label == "MainMenu")
    for (int x = 0 ; x <= 50 ; ++x)
    g.setColor (Color.white);
    g.setFont (new Font ("Arial", Font.BOLD, x));
    g.drawString ("T R A P P E D", 100, 125);
    d.delay (10);
    if (x != 50)
    g.setColor (Color.black);
    g.drawString ("T R A P P E D", 100, 125);
    if (label == "Entrance")
    l.Entrance ("ONE", g);
    label = "LevelOne";
    if (label == "LevelOne")
    l.LevelOne (g, levelOne, gbc);
    label = "";
    public static void main (String[] args)
    // calls the program
    User_Interface application = new User_Interface ();
    application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    } //End of Main Method
    //Libraries
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Levels extends Objects
    private JFrame frame = new JFrame ();
    //Sets location, size, and visiblity to the frame where the JOptionPane
    //will be placed
    frame.setLocation (600, 600);
    frame.setSize (1, 1);
    frame.setVisible (false);
    public int xCord = 2;
    public int yCord = 2;
    public void LevelOne (Graphics g, JPanel one, GridBagConstraints gbc)
    ***Trying to add the button, doesn't appear. Tried adding to the container, and any JPanel i had created***
    JButton button1 = new JButton ("TEST");
    one.add (button1);
    g.setColor (Color.white);
    g.fillRect (500, 100, 200, 300);
    g.setColor (Color.black);
    g.drawRect (500, 100, 200, 300);
    g.setFont (new Font ("Verdana", Font.BOLD, 25));
    g.setColor (Color.black);
    g.drawString ("LEVEL ONE", 525, 80);
    //ROW ONE
    counter = -80;
    counter2 = 200;
    for (int a = 1 ; a <= 7 ; ++a)
    if (xCord < a && yCord == 0)
    g.setColor (darkGray);
    g.fillRect (xLoc + counter, yLoc - 80, 40, 40);
    g.setColor (Color.black);
    g.drawRect (xLoc + counter, yLoc - 80, 40, 40);
    if (xCord > a - 1 && yCord == 0)
    g.setColor (darkGray);
    g.fillRect (xLoc + counter2, yLoc - 80, 40, 40);
    g.setColor (Color.black);
    g.drawRect (xLoc + counter2, yLoc - 80, 40, 40);
    counter += 40;
    counter2 += 40;
    *****Theres 9 more rows, just edited out to save space****
    int y = 100;
    int x = 100;
    for (int a = 0 ; a < 20 ; ++a)
    g.setColor (Color.white);
    g.fillRoundRect (x, y, 40, 40, 5, 5);
    g.setColor (Color.black);
    g.drawRoundRect (x, y, 40, 40, 5, 5);
    y += 40;
    if (a == 9)
    x += 320;
    y = 100;
    x = 140;
    y = 100;
    for (int a = 0 ; a < 14 ; ++a)
    g.setColor (Color.white);
    g.fillRoundRect (x, y, 40, 40, 5, 5);
    g.setColor (Color.black);
    g.drawRoundRect (x, y, 40, 40, 5, 5);
    x += 40;
    if (a == 6)
    x = 140;
    y += 360;
    g.setColor (Color.black);
    g.drawRect (100, 100, 360, 400);
    ImageIcon[] images = new ImageIcon [4];
    images [0] = new ImageIcon ("arrow_left.gif");
    images [1] = new ImageIcon ("arrow_up.gif");
    images [2] = new ImageIcon ("arrow_down.gif");
    images [3] = new ImageIcon ("arrow_right.gif");
    int direction = -1;
    *****This is where I tried to have the OptionPane show the directional buttons******
    //frame.setVisible (true);
    // direction = JOptionPane.showOptionDialog (frame, "Choose Your Path:", "Trapped", JOptionPane.YES_NO_CANCEL_OPTION,
    // JOptionPane.QUESTION_MESSAGE,
    // null,
    // images,
    // images [3]);
    // if (direction == 0)
    // if (xCord - 1 > 0)
    // xCord -= 1;
    // xLoc += 40;
    // if (direction == 1)
    // if (yCord - 1 > 0)
    // yCord -= 1;
    // yLoc += 40;
    // if (direction == 2)
    // if (yCord + 1 < 9)
    // yCord += 1;
    // yLoc -= 40;
    // if (direction == 3)
    // if (xCord + 1 < 13)
    // xCord += 1;
    // xLoc -= 40;
    //LevelOne (g, one, gbc);
    }

    i tried adding a keylistener, that didn't work too well, i had tried to add it to a button and a textarea which i added to the 'one' frame, it didn't show up, and it didn't work. How would i go about changing the paint method so that it doesn't contain any logic? That's the only way I could think of getting the program to move forward in the game. Thanks.
    //Libraries
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    public class User_Interface extends JFrame
        static Levels l = new Levels ();
        static Delay d = new Delay ();
        private Container contentPane = getContentPane ();
        private JPanel main, levelOne;
        private String level;
        private CardLayout cc = new CardLayout ();
        private GridBagConstraints gbc = new GridBagConstraints ();
        private JPanel c = new JPanel ();
        private String label = "MainMenu";
        public User_Interface ()
            //Generates the User-Interface
            super ("Trapped");
            main = new JPanel ();
            GridBagLayout gbl = new GridBagLayout ();
            main.setLayout (gbl);
            c.setLayout (cc);
            // set_gbc (gbc, 2, 2, 5, 5, GridBagConstraints.NONE);
            c.add (main, "Main Page");
            contentPane.add (c, BorderLayout.CENTER);
            cc.show (c, "Main Page");
            levelOne = new JPanel ();
            levelOne.setLayout (new GridBagLayout ());
            levelOne.setBackground (Color.black);
            c.add (levelOne, "LevelOne");
            JMenuBar menu = new JMenuBar ();
            JMenu file = new JMenu ("File");
            JMenu help = new JMenu ("Help");
            JMenuItem about = new JMenuItem ("About");
            JMenuItem mainmenu = new JMenuItem ("Main Menu");
            mainmenu.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    cc.show (c, "Main Page");
                    label = "MainMenu";
            JMenuItem newGame = new JMenuItem ("New Game");
            newGame.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    l.xCord = 2;
                    l.yCord = 2;
                    l.xLoc = 140;
                    l.yLoc = 140;
                    JPanel entrance = new JPanel ();
                    entrance.setLayout (new FlowLayout ());
                    c.add (entrance, "Entrance");
                    label = "Entrance";
                    level = "ONE";
                    cc.show (c, "Entrance");
            JMenuItem loadgame = new JMenuItem ("Load Game");
            JMenuItem savegame = new JMenuItem ("Save Game");
            JMenuItem exit = new JMenuItem ("Exit");
            exit.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    JFrame frame = new JFrame ();
                    frame.setLocation (10, 10);
                    JOptionPane.showMessageDialog (frame, "Come Back Soon!", "TRAPPED", JOptionPane.INFORMATION_MESSAGE);
                    System.exit (0);
            file.add (about);
            file.add (mainmenu);
            file.add (newGame);
            file.add (loadgame);
            file.add (savegame);
            file.add (exit);
            menu.add (file);
            menu.add (help);
            setJMenuBar (menu);
            //Sets the size of the container (columns by rows)
            setSize (750, 550);
            //Sets the location of the container
            setLocation (10, 10);
            //Sets the background colour to a dark blue colour
            main.setBackground (Color.black);
            //Makes the container visible
            setVisible (true);
        public void paint (Graphics g)
            super.paint (g);
            g.setColor (Color.white);
            if (label == "MainMenu")
                for (int x = 0 ; x <= 50 ; ++x)
                    g.setColor (Color.white);
                    g.setFont (new Font ("Arial", Font.BOLD, x));
                    g.drawString ("T    R    A    P    P    E    D", 100, 125);
                    d.delay (10);
                    if (x != 50)
                        g.setColor (Color.black);
                        g.drawString ("T    R    A    P    P    E    D", 100, 125);
            if (label == "Entrance")
                l.Entrance ("ONE", g);
                label = "LevelOne";
            if (label == "LevelOne")
                l.LevelOne (g, levelOne, gbc);
                label = "";
            //g.setColor (new Color
        public static void main (String[] args)
            // calls the program
            User_Interface application = new User_Interface ();
            application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        } //End of Main Method
    //Libraries
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.ActionMap;
    import javax.swing.plaf.*;
    public class Levels extends Objects
        implements KeyListener
        //static final String newline = System.getProperty ("line.separator");
        JButton button;
        private JFrame frame = new JFrame ();
            //Sets location, size, and visiblity to the frame where the JOptionPane
            //will be placed
            frame.setLocation (600, 600);
            frame.setSize (1, 1);
            frame.setVisible (false);
        JButton button1;
        public int xCord = 2;
        public int yCord = 2;
        public void LevelOne (Graphics g, JPanel one, GridBagConstraints gbc)
        //    button = new JButton ("TEST");
        //    ButtonHandler handler = new ButtonHandler ();
         //   button.addActionListener (handler);
          //  one.add (button);
            g.setColor (Color.white);
            g.fillRect (500, 100, 200, 300);
            g.setColor (Color.black);
            g.drawRect (500, 100, 200, 300);
            g.setFont (new Font ("Verdana", Font.BOLD, 25));
            g.setColor (Color.black);
            g.drawString ("LEVEL ONE", 525, 80);
            //ROW ONE
            counter = -80;
            counter2 = 200;
            for (int a = 1 ; a <= 7 ; ++a)
                if (xCord < a && yCord == 0)
                    g.setColor (darkGray);
                    g.fillRect (xLoc + counter, yLoc - 80, 40, 40);
                    g.setColor (Color.black);
                    g.drawRect (xLoc + counter, yLoc - 80, 40, 40);
                if (xCord > a - 1 && yCord == 0)
                    g.setColor (darkGray);
                    g.fillRect (xLoc + counter2, yLoc - 80, 40, 40);
                    g.setColor (Color.black);
                    g.drawRect (xLoc + counter2, yLoc - 80, 40, 40);
                counter += 40;
                counter2 += 40;
            int y = 100;
            int x = 100;
            for (int a = 0 ; a < 20 ; ++a)
                g.setColor (Color.white);
                g.fillRoundRect (x, y, 40, 40, 5, 5);
                g.setColor (Color.black);
                g.drawRoundRect (x, y, 40, 40, 5, 5);
                y += 40;
                if (a == 9)
                    x += 320;
                    y = 100;
            x = 140;
            y = 100;
            for (int a = 0 ; a < 14 ; ++a)
                g.setColor (Color.white);
                g.fillRoundRect (x, y, 40, 40, 5, 5);
                g.setColor (Color.black);
                g.drawRoundRect (x, y, 40, 40, 5, 5);
                x += 40;
                if (a == 6)
                    x = 140;
                    y += 360;
            g.setColor (Color.black);
            g.drawRect (100, 100, 360, 400);
            ImageIcon[] images = new ImageIcon [4];
            images [0] = new ImageIcon ("arrow_left.gif");
            images [1] = new ImageIcon ("arrow_up.gif");
            images [2] = new ImageIcon ("arrow_down.gif");
            images [3] = new ImageIcon ("arrow_right.gif");
            int direction = -1;
            //frame.setVisible (true);
            // direction = JOptionPane.showOptionDialog (frame, "Choose Your //\Path:", "Trapped", JOptionPane.YES_NO_CANCEL_OPTION,
            //         JOptionPane.QUESTION_MESSAGE,
            //         null,
            //         images,
            //         images [3]);
            // if (direction == 0)
            //     if (xCord - 1 > 0)
            //         xCord -= 1;
            //         xLoc += 40;
            // if (direction == 1)
            //     if (yCord - 1 > 0)
            //         yCord -= 1;
            //         yLoc += 40;
            // if (direction == 2)
            //     if (yCord + 1 < 9)
            //         yCord += 1;
            //         yLoc -= 40;
            // if (direction == 3)
            //     if (xCord + 1 < 13)
            //         xCord += 1;
            //         xLoc -= 40;
            one.addKeyListener (this);
            // one.add (button1);
            if (xCord == 1)
                LevelOne (g, one, gbc);
        /** Handle the key typed event from the text field. */
        public void keyTyped (KeyEvent e)
        /** Handle the key pressed event from the text field. */
        public void keyPressed (KeyEvent e)
            if (e.getSource () == "Up")
                JOptionPane.showMessageDialog (null, "Hi", "Hi", 0, null);
        /** Handle the key released event from the text field. */
        public void keyReleased (KeyEvent e)
            // displayInfo (e, "KEY RELEASED: ");
    }

  • 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

  • KeyListener in Fullscreen App Help

    I'm working on a fullscreen application in which i need to do some key binding. My class is implementing both the MouseListener interface and the KeyListener interface, I have defined all the methods contained in that interface, and I have added a KeyListener and a MouseListener to my Window. When I click the mouse, my application does everything I defined in the methods of the MouseListener. However, when I hit keys nothing happens. Does anyone know if there is anything extra that I need to do when using a KeyListener with a Window?

    Hi!
    I just wrote exactly what you did two weeks ago. It seems to me as if you forgot to make your object (Frame, JFrame, JLabel,...) focusable. You usually do that by calling myFrame.setFocusable(true); You can find some addidtional help in http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html where you also find a link to a pretty nice piece of code right below point 13 of "Try This[b]".
    Good luck,
    G :-)

  • Another KeyListener thread...

    Hi, I'm new here. Me and a friend are trying out some java on our own because we feel our teacher gives us boring tasks (word games etc. UH...).
    We just started making a simple platform game. I'm handling the character movement etc. but I've ran into some troubles with Key Bindings.
    The code compiles and I can move the character around, but I would like to have control of Key_pressed and Key_released events for all the keys. I've tried adding a keylistener to the JPanel but off course that doesn't work (the compiler says the JPanel is not abstract). I want to know how I can acces the Key events. I've read alot of threads about this already but they all use different methods and I can't seem to figure them out.
    This is what I have:
    import javax.swing.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.event.KeyEvent;
    import java.awt.*;
    import java.net.URL;
    import java.awt.image.BufferedImage;
    public class gamebuild2 extends JFrame{
    public static void main(String[] argumentenRij) {
    JFrame frame = new gamebuild2();
    frame.setSize(400,300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel1 = new panel1 ();
    frame.setContentPane (panel1);
    frame.setTitle("build2");
    frame.setVisible(true);      
    class panel1 extends JPanel   {
    private int res=1,x_back=0,x_player1, x_enemy=500, enemystatus=1,status;
    private ImageIcon background,player_standright,player_standleft,player_lookupright,player_lookupleft,player_walkright,player_walkleft,
    player_duckright,player_duckleft,player_attackright,player_attackleft,player_jumpright,player_jumpleft,enemy;
    public panel1(){   
    registerKeys();
    background = new ImageIcon("background.png");
    player_standright = new ImageIcon("mario_standright.gif");
    player_standleft = new ImageIcon("mario_standleft.gif");
    player_walkright = new ImageIcon("mario_walkright.gif");
    player_walkleft = new ImageIcon("mario_walkleft.gif");
    player_duckright = new ImageIcon("mario_duckright.gif");
    player_duckleft = new ImageIcon("mario_duckleft.gif");
    player_attackright = new ImageIcon("mario_attackright.gif");
    player_attackleft = new ImageIcon("mario_attackleft.gif");
    player_lookupright = new ImageIcon("mario_lookupright.gif");
    player_lookupleft = new ImageIcon("mario_lookupleft.gif");
    player_jumpright = new ImageIcon("mario_jumpright.gif");
    player_jumpleft = new ImageIcon("mario_jumpleft.gif");
    enemy = new ImageIcon("zwartebalk.png");
    //        new AePlayWave("wario2.wav").start();
    private void registerKeys() {
    int c = JComponent.WHEN_IN_FOCUSED_WINDOW;
    //        if (e.getID()==KeyEvent.KEY_PRESSED){}
    getInputMap(c).put(KeyStroke.getKeyStroke(""), "");
    getActionMap().put("", noAction);
    getInputMap(c).put(KeyStroke.getKeyStroke("UP"), "UP");
    getActionMap().put("UP", upAction);
    getInputMap(c).put(KeyStroke.getKeyStroke("LEFT"), "LEFT");
    getActionMap().put("LEFT", leftAction);
    getInputMap(c).put(KeyStroke.getKeyStroke("DOWN"), "DOWN");
    getActionMap().put("DOWN", downAction);
    getInputMap(c).put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");
    getActionMap().put("RIGHT", rightAction);
    getInputMap(c).put(KeyStroke.getKeyStroke("SPACE"), "SPACE");
    getActionMap().put("SPACE", attackAction);
    private Action noAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    status=1;
    repaint();
    private Action upAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    status=7;
    repaint();
    private Action leftAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    if(x_back==0)
    if(x_player1==0)
    else{
    x_player1=((x_player1*res)-(10*res));
    else{
    if(x_player1<=120*res)
    x_back=((x_back*res)+(10*res));
    x_enemy = ((x_enemy *res)+(10*res));
    else{
    x_player1=((x_player1*res)-(10*res));
    status=4;
    repaint();
    private Action downAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    status=5;
    repaint();
    private Action attackAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    status=11;
    repaint();
    private Action rightAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    if(x_player1>=240*res)
    x_back=((x_back*res)-(10*res));
    x_enemy = ((x_enemy *res)-(10*res));
    else{
    x_player1=((x_player1*res)+(10*res));
    status=3;
    repaint();
    public void paintComponent ( Graphics g ){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    //      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    //                            RenderingHints.VALUE_ANTIALIAS_ON);
    background.paintIcon(this, g,x_back,0);
    switch (status) {
    case 1:  player_standright.paintIcon(this, g2, x_player1,(173*res)); break;
    case 2:  player_standleft.paintIcon(this, g2, x_player1,(173*res)); break;
    case 3:  player_walkright.paintIcon(this, g2, x_player1,(170*res)); break;
    case 4:  player_walkleft.paintIcon(this, g2, x_player1,(170*res)); break;
    case 5:  player_duckright.paintIcon(this, g2, x_player1,(185*res)); break;
    case 6:  player_duckleft.paintIcon(this, g2, x_player1,(173*res)); break;
    case 7:  player_lookupright.paintIcon(this, g2, x_player1,(173*res)); break;
    case 8:  player_lookupleft.paintIcon(this, g2, x_player1,(173*res)); break;
    case 9:  player_jumpright.paintIcon(this, g2, x_player1,(173*res)); break;
    case 10: player_jumpleft.paintIcon(this, g2, x_player1,(173*res)); break;
    case 11: player_attackright.paintIcon(this, g2, x_player1,(173*res)); break;
    case 12: player_attackleft.paintIcon(this, g2, x_player1,(173*res)); break;
    default: player_standright.paintIcon(this, g2, x_player1,(173*res)); break;
    if(enemystatus == 1 ){
    enemy.paintIcon(this,g2,x_enemy,(168*res) );
    if(status==11||status==12){
    if(enemystatus==1){
    if(((x_enemy*res))<=((x_player1*res)+(32*res))){
    if((x_player1*res)<=((x_enemy*res)+(32*res)))
    enemystatus=0;
    }

    Your question is about implement a KeyListener. You where asked for a SSCCE. It does not require a jar to write a simple SSCCE. It should only take about 10-20 lines of code to write a simple KeyListener.
    We don't care about your actuall use of the KeyListener in you program. You just use a simple System.out.println(...) to make sure the key listener is invoked the way you expect it to be invoked. Once you understand the basics, you incorporate that knowledge into your main program.
    You can start by reading the Swing tutorial on [How to Write a Key Listener|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html].

  • KeyListener - Bug or feature?

    In the IRT Reference Implementation adding a KeyListener to an HScene works, but adding it to an HContainer does not. (I tried that with focus on HScene and focus on the Container)
    Is that how it should work (so a reference to my HScene is always needed)?
    Thanks a lot! elBoB

    Well it looks like your exact problem is listed on that incompatibility list:
    JDBC - As of 5.0, comparing a java.sql.Timestamp to a java.util.Date by invoking compareTo on the Timestamp results in a ClassCastException. For example, the following code successfully compares a Timestamp and Date in 1.4.2, but fails with an exception in 5.0:
    aTimeStamp.compareTo(aDate) //NO LONGER WORKS
    This change affects even pre-compiled code, resulting in a binary compatibility problem where compiled code that used to run under earlier releases fails in 5.0. We expect to fix this problem in a future release.
    For more information, see bug 5103041.
    Michael Bishop

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

  • Problem with the keylistener

    Hi ,
    I am strucking with keylistener problem. I need the date in yyyy/mm/dd and no other letter it should allow me that means 2008/12/21.(i .e.,only digits and / at 5 and 8 postion) and the total length of the field is not more than 10.
    i have done to accept only digits and max length of the date field is 10 by using the below code but unable valide / at chart 5 and 8 position.
    Seek urgent help and reply would greately be appreciated.
    public class DateListener extends JTextField implements KeyListener
         /* (non-Javadoc)
         * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
         public void keyPressed(KeyEvent arg0) {
              // TODO Auto-generated method stub
         /* (non-Javadoc)
         * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
         public void keyReleased(KeyEvent arg0) {
              // TODO Auto-generated method stub
         public void keyTyped(KeyEvent e)
              final char c = e.getKeyChar();
              System.out.println("this.getText() value is" +this.getText());
              if( this.getText().length()> 9)
                   e.consume();
              System.out.println(this.getCaretPosition());
              if((c < '0' || c > '9') )
                   e.consume();
              }else if(this.getText().length() < 4 && this.getText().length() > 5 && c != '/' )
                   e.consume();
    Thank you,

    Hi, I struk with Maskformatter. I am validating the date entered my user. I have made the date using
    mft = new MaskFormatter("####/##/##");
    mft.setPlaceholderCharacter('_');
    activeDateTF = new avax.swing.JFormattedTextField(mft); where activeDateTF is a format text field . I have added the keylistener to that
    DateListener dateListener = new DateListener();
    this.activeDateTF.addKeyListener(dateListener);
    and datelistener has the following.
    public void keyReleased(KeyEvent e)
    { // TODO Auto-generated method stub
    System.out.println("you are in key released");
    final char c = e.getKeyChar();
    if(c!='\b') {
    al.add(c);
    JTextField ft =(JTextField)
    e.getSource(); if(al.size()== 8 )
    { System.out.println("ft.text value is " +ft.getText());
    al.clear();
    } where al is a arraylist used to know how many digits have been entered by user since the date contains only 8 (2008/12/12) excluding /. But the validations are becoming very difficult since the user may just enter 2008 and leave. my question is how do i get the value without _(placeholder) from the formatted text filed and how to validate the digits entered by user. Plesae help srini

  • Add event(keyListener) to JTable Cell default editor.

    I've got a form(Jdialog) with a Jtable on it.
    I've added a keyListener to the JButtons and Jtable so that, wherever the the focus IS, when I hit the "F7" key, it fills the Jtable from the database connection.
    It's working REALLY fine now but there is one small glitch.
    When I'm editing a cell, the keyListener event is not thrown. I supposed it's because the "DefaultCellEditor" does not throw the event.
    How can I add such a thing??
    I'm looking for something like :
    table.getDefaultEditor().addKeyListener
    but it does not exists.
    If it's not possible, is there a way to make the JDialog listen to all the keyListener events from its childs??(Mimics the JDK < 1.4)
    Thx

    Using key binding is better implementation.
    After you read the tutorial your next move is to google for it.
    http://www.google.com/search?hl=en&q=jtable+keybinding
    Second result brings you to camickr's example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=657819

  • KeyListener never invoked on my editor

    I am trying to make TAB go to the next field in my table. But none of my keylistener methods get invoked on my cell editor. Can anyone help? Here is my code...
    public class MultiLineCellEditor extends DefaultGridCellEditor implements GridCellEditor, KeyListener
    String value_;
    JScrollTextArea textArea_;
    CommonJSmartGrid grid_;
    public MultiLineCellEditor()
    super(new JTextField());
    JTextField jtf = (JTextField) this.getComponent();
    jtf.addKeyListener(this);
    textArea_ = new JScrollTextArea();
    value_ = null;
    setClickCountToStart(2);
    public void keyReleased(KeyEvent e)
    System.out.println("keyReleased...");
    public void keyPressed(KeyEvent e)
    System.out.println("keyPressed...");
    public void keyTyped(KeyEvent e)
    System.out.println("keytype...");
    Thanks in advance,
    Steve

    This info was helpful... however, I still can't get anything to register a keyevent once I am in the editor. The table has focus (I check) when I first open this screen, and loses focus when I double click on the cell containing the multiline cell editor. The thing is... what object then gains focus? I checked the scrollpane and the jTextField. Neither of these ever gets focus so adding a keylistener to them won't do any good. Any other ideas?
    Thanks,
    Steve

  • JFrame KeyListener

    Im trying to get a JFrame to be updated when the user presses F12. I have added a KeyListener however I get no response. This is my implementation of the KeyListener:
    public void keyTyped(KeyEvent e){}
    public void keyReleased(KeyEvent e){}
    public void keyPressed(KeyEvent e){
    System.out.println("YES");
    if (e.getKeyCode()==e.VK_F12) {
    System.out.println("YES");
    load();
    Any ideas why its not working?
    Cheers, Adam

    In the future, Swing related questions should be posted in the Swing forum.
    [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Problem in keyboard reading....

    i was creating a program which using the keyboard to control the movement of a character,(picture). but when i run the program in jvm 1.4.1 , the program doesn't read anything from the keyboard. previously i was running it in jvm 1.3.1 ..... any solution?

    Well, if you're adding the KeyListener to a JPanel, it would be yourJPanel.requestFocus(); That's all. There was a change to the focus model in 1.4, that's why you might have to add this line.

Maybe you are looking for

  • Literally the worst customer support experience I've ever had to deal with -- Why don't they let their customers speak to supervisors on demand?

    Call 1: I spoke to them to see if I was eligible for an upgrade. It turned out they had accidentally counted a temporary phone switch to an old device as an upgrade. The representative was extremely slow minded and took over an hour to read through m

  • About load rules

    Hi, we r loading the for PLV app using loadrules (act.rul) with admin rights.It is planning application. how to give the access to the user. For rule file & calc scripts in read only mode .i mean he need to load the data & execution of script.no any

  • Having Trouble Shutting Down

    Hey guys- My comp doesn't seem to want to shut down (or restart). i.e. If I follow Apple>Shut Down>"OK", it will close out all my apps and act like its going to shut down, then just sits on the Finder. I checked out the activity monitor and can't fin

  • Small image ant fonts to fit my monitor

    my mozilla browser window comes with big size image and fonts .i want make it smaller and fix to monitor to save my limited internet data volume pack and improve the speed of browsing.

  • New Updates - Should I reinstall?

    I have Aperture on my shelf. After many trials with version 1.5 I just gave up for multiple reasons. iPhoto 08 seems to be fine for me and I like the "Time Machine" in Leopard. I'm keeping an eye on the discussions to see when Apple "REALLY" upgrades