Java Swing - Listeners
TOPIC 02 – KEYLISTENER

 

LESSON NOTE

 

 

INTRO

 

We use a KeyListener object to listen for keyboard key strokes.  The KeyListener works in the same way as the MouseListener object.

 

KEYLISTENER INTERFACE

All of the following methods must be implemented inside a class that implements the interface:

      public void keyPressed(KeyEvent e)
      public void keyReleased(KeyEvent e)
      public void keyTyped(KeyEvent e)

Each method relates to an obvious event (key pressed, key released or key typed).  We will focus on keyPressed and keyReleased for now.


Note that the keyPressed event continuously gets triggered if you keep a key pressed down.

 

WHAT WILL THIS LOOK LIKE?

 

            public class MyPanelName extends JPanel implements KeyListener

            {

               //data fields go here

 

               public MyPanelName()

               {

                  addKeyListener(this);

   }

 

   public void paint(Graphics g)

   {…}

 

   public void keyPressed(KeyEvent e)

   {…}

   public void keyReleased(KeyEvent e)

   {…}

   public void keyTyped(KeyEvent e)

   {…}

}         

 

KEYEVENT OBJECTS

 

The KeyEvent objects are automatically created for you.  You will likely use them to find out which key was pressed or to find the ascii (key code) for the key that was pressed.

 

To find out which key triggered the event, you use:

 

            e.getKeyChar()

 

To find out the key code of the key that triggered the event, you use:

 

            e.getKeyCode()

 

ASCII CODES

 

If you look under the Resources section of the main page of this site, you will find the ascii code for all characters. 

 

These codes are most useful when dealing with keys that don’t have a symbol to represent their character (ie – arrow keys, shift key, space key, …).

 

EXAMPLE 1 – WHICH KEY WAS PRESSED

 

The following example will simply display the character and the ascii code of the last key that was hit.

 

import javax.swing.JFrame;

 

public class KeyboardListenerTester

{

          public static void main(String[] args)

          {

                 JFrame jf = new JFrame();               

                 jf.setSize(250,125);

                 jf.setVisible(true);

                 jf.setTitle("Keyboard Events");  

 

                 //Create my panel and add it to JFrame object

                 KeyboardListenerPanel pan = new KeyboardListenerPanel();

                 jf.add(pan);

          }

}

import java.awt.Graphics;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import javax.swing.JPanel;

 

public class KeyboardListenerPanel extends JPanel implements KeyListener

{

      

    //datafields

    public String lastKeyChar = "";

    public int lastKeyCode = 0;

      

  

   public KeyboardListenerPanel()

   {

          addKeyListener(this); 

   }

  

   //this method is needed to give keyboard focus to the panel...

   public void addNotify()   

   {

       super.addNotify();

       requestFocus();

   }

      

   public void paint(Graphics g)

   {

          super.paint(g);  //required to repaint bg everytime

          g.drawString("Last key char: " + lastKeyChar, 20, 20);

          g.drawString("Last key code: " + lastKeyCode, 20, 40);

   }

 

   public void keyTyped(KeyEvent e)

   {

   }

  

   public void keyPressed(KeyEvent e)

   {

          lastKeyChar = "" + e.getKeyChar();

          lastKeyCode = e.getKeyCode();   //ascii code

          repaint();   

   }

  

   public void keyReleased(KeyEvent e)

   {

   }

}

 

The above code will create the interactive window below.

 


EXAMPLE 2 – ARROW KEYS MOVING OBJECTS

 

The following example will paint a circle at a location that is based on the two datafields myX and myY.  Everytime the arrow keys are used, these datafields are updated.  This makes it seem that the circle is controlled by the arrow keys.

 

import javax.swing.JFrame;

 

public class MovementTester

{

   public static void main(String[] args)

   {

       JFrame jf = new JFrame();           

       jf.setSize(500,500);

       jf.setVisible(true);

       jf.setTitle("Movin Around.");  

 

       //Create my panel and add it to JFrame object

       MovementPanel pan = new MovementPanel();

       jf.add(pan);

   }

}

import java.awt.Graphics;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import javax.swing.JPanel;

 

public class MovementPanel extends JPanel implements KeyListener

{

      

       //datafields

    public int myX;

    public int myY;

      

   public MovementPanel()

   {

          addKeyListener(this); 

   }

  

   public void addNotify()    //this method is needed to give keyboard focus to the panel...

   {

       super.addNotify();

       requestFocus();

   }

      

   public void paint(Graphics g)

   {

          super.paint(g);  //required to repaint bg everytime

          g.fillOval(myX, myY, 30,30);

          g.drawString("Try the arrow keys.",200,10);

   }

 

   public void keyTyped(KeyEvent e)

   {

   }

  

   public void keyPressed(KeyEvent e)

   {

       if(e.getKeyCode() == 37)  //LEFT ARROW

       {

          myX = myX - 5;

       }

       else if (e.getKeyCode() == 39)  //RIGHT ARROW

       {

          myX = myX + 5;

       }

       else if (e.getKeyCode() == 38)  //UP ARROW

       {

          myY = myY - 5;

       }

       else if (e.getKeyCode() == 40)  //UP ARROW

       {

          myY = myY + 5;

       }

          repaint();   

   }

  

   public void keyReleased(KeyEvent e)

   {

   }

}

 

The above code will create the following interactive window that allows you to move the circle with arrow keys:

 

 

EXAMPLE 3 – SLIDESHOW

 

The following example shows a program setup that could be used to display a slideshow where each slide could be a graphical scene or an image from the hard drive.

import javax.swing.JFrame;

 

public class SlideshowTester

{

   public static void main(String[] args)

   {

          JFrame jf = new JFrame();               

          jf.setSize(500,350);

          jf.setVisible(true);

          jf.setTitle("Movin Around.");  

 

          //Create my panel and add it to JFrame object

          SlideshowPanel pan = new SlideshowPanel();

          jf.add(pan);

   }

}

package Listeners;

 

import java.awt.Graphics;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import javax.swing.JPanel;

 

public class SlideshowPanel extends JPanel implements KeyListener

{

      

    //datafields

    boolean screen1 = true;

    boolean screen2 = false;

    boolean screen3 = false;

    boolean screen4 = false;

      

   public SlideshowPanel()

   {

          addKeyListener(this); 

   }

  

   public void addNotify() //this method is needed to give keyboard focus to panel

   {

       super.addNotify();

       requestFocus();

   }

      

   public void paint(Graphics g)

   {

          super.paint(g);  //required to repaint bg everytime

          if (screen1 == true)

          {

                 g.drawRect(0, 0, 10, 10);

                 g.drawString("Slide 1 - Press any key to continue", 150, 300);

          }     

          else if (screen2 == true) 

          {

                 g.drawRect(0, 0, 50, 50);

                 g.drawString("Slide 2 - Press any key to continue", 150, 300);

          }  

          else if (screen3 == true)

          {

                 g.drawRect(0, 0, 100, 100);

                 g.drawString("Slide 3 - Press any key to continue", 150, 300);

          }

          else if (screen4 == true)

          {

                 g.drawRect(0, 0, 200, 200);

                 g.drawString("Slide 4 - You are at the end of this show", 140, 300);

          }

   }

 

   public void keyTyped(KeyEvent e)

   {

   }

  

   public void keyPressed(KeyEvent e)

   {

         //Holding key down triggers this event many times. 

         //So its not an option for a slideshow as you'd skip many slides.

   }

  

   public void keyReleased(KeyEvent e)

   {

             if (screen1 == true)

             {

               //move to screen 2

               screen2 = true;

               screen1 = false;

               repaint();

             }

             else if (screen2 == true)

             {

               //move to screen 3

               screen3 = true;

               screen2 = false;

               repaint();

             }

             else if (screen3 == true)

             {

               //move to screen 4

               screen4 = true;

               screen3 = false;

               repaint();

             }

   }

}

 

EXAMPLE 4 – A QUIZ

 

In this example, you will see a slideshow style program that will have different screens at the end depending on which key you pressed.

 

import javax.swing.JFrame;

 

public class CardboardQuestionTester

{

   public static void main(String[] args)

   {

          JFrame jf = new JFrame();               

          jf.setSize(500,500);

          jf.setVisible(true);

          jf.setTitle("Movin Around.");  

 

          //Create my panel and add it to JFrame object

          CardboardQuestionPanel pan = new CardboardQuestionPanel();

          jf.add(pan);

   }

}

import java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

 

import javax.imageio.ImageIO;

import javax.swing.JPanel;

 

public class CardboardQuestionPanel extends JPanel implements KeyListener

{

      

       //datafields

    boolean screen1 = true;

    boolean screen2 = false;

    boolean screen3 = false;

    boolean screen4 = false;

    boolean screen5 = false;

    boolean screen6 = false;

    boolean screen7 = false;

    boolean screen8 = false;

      

   public CardboardQuestionPanel()

   {

          addKeyListener(this); 

   }

  

   public void addNotify()    //this method is needed to give keyboard focus to the panel...

   {

       super.addNotify();

       requestFocus();

   }

      

   public void paint(Graphics g)

   {

          super.paint(g);  //required to repaint bg everytime

          Graphics2D g2D = (Graphics2D) g;

          //=================================================================================================

          if (screen1 == true)

          {

                 BufferedImage img = null;

                 try

                 {

                        img = ImageIO.read(new File("pizzaboxbyte.png"));  //img in project folder (Eclipse)

                        g2D.setColor(Color.white);

                        g2D.fillRect(0, 0, 500, 500);  //background

                        g2D.setColor(Color.black);

                        g2D.drawString("Consider the image below.", 170, 20);

                     g2D.drawImage(img, 65, 30, null);

                     g2D.drawString("Who do you think is likely responsible for the bite taken our of the box?", 50, 443);

                     g2D.drawString("(Press any key to continue)", 170, 458);

                 }   

                 catch (IOException e)

                 {

                        System.out.println("Error");

                        e.printStackTrace();  //Optional - Shows the location of the error issue.

                 }

          }  

          //=================================================================================================

          else if (screen2 == true) 

          {

                 BufferedImage img = null;

                 try

                 {

                        img = ImageIO.read(new File("unknownGirl.JPG"));  //img in project folder (Eclipse)

                        g2D.setColor(Color.white);

                        g2D.fillRect(0, 0, 500, 500);  //background

                        g2D.setColor(Color.black);

                        g2D.drawString("Was it this girl?  She seems pretty happy with her pizza.", 84, 20);

                     g2D.drawImage(img, 30, 70, null);

                     g2D.drawString("(Press any key to continue)", 170, 458);

                 }   

                 catch (IOException e)

                 {

                        System.out.println("Error");

                        e.printStackTrace();  //Optional - Shows the location of the error issue.

                 }

          }  

          //=================================================================================================

          else if (screen3 == true)

          {

                 BufferedImage img = null;

                 try

                 {

                        img = ImageIO.read(new File("JohnStewart.jpg"));  //img in project folder (Eclipse)

                        g2D.setColor(Color.white);

                        g2D.fillRect(0, 0, 500, 500);  //background

                        g2D.setColor(Color.black);

                        g2D.drawString("Or perhaps it was John Stewart.  He's a pretty funny guy!", 84, 20);

                     g2D.drawImage(img, 35, 70, null);

                     g2D.drawString("(Press any key to continue)", 170, 458);

                 }   

                 catch (IOException e)

                 {

                        System.out.println("Error");

                        e.printStackTrace();  //Optional - Shows the location of the error issue.

                 }

          }

          //=================================================================================================

          else if (screen4 == true)

          {

                 BufferedImage img = null;

                 try

                 {

                        img = ImageIO.read(new File("michealAngelo.png"));  //img in project folder (Eclipse)

                        g2D.setColor(Color.white);

                        g2D.fillRect(0, 0, 500, 500);  //background

                        g2D.setColor(Color.black);

                        g2D.drawString("Was it Michealangelo?  He sure loves pizza.", 120, 20);

                     g2D.drawImage(img, 67, 110, null);

                     g2D.drawString("(Press any key to continue)", 170, 458);

                 }   

                 catch (IOException e)

                 {

                        System.out.println("Error");

                        e.printStackTrace();  //Optional - Shows the location of the error issue.

                 }

          }

          //=================================================================================================

          else if (screen5 == true)

          {

                 BufferedImage img = null;

                 try

                 {

                        img = ImageIO.read(new File("pirateKingFram.jpg"));  //img in project folder (Eclipse)

                        g2D.setColor(Color.white);

                        g2D.fillRect(0, 0, 500, 500);  //background

                        g2D.setColor(Color.black);

                        g2D.drawString("Or maybe it was a Pirate Fram?", 120, 20);

                     g2D.drawImage(img, 39, 80, null);

                     g2D.drawString("(Press any key to continue)", 170, 458);

                 }   

                 catch (IOException e)

                 {

                        System.out.println("Error");

                        e.printStackTrace();  //Optional - Shows the location of the error issue.

                 }  

          }

          //=================================================================================================

          else if (screen6 == true)

          {

                 g2D.drawString("Make your choice.", 160, 20);

 

                 g2D.drawString("a) Unknown girl", 160, 60);

                 g2D.drawString("b) John Stewart", 160, 90);

                 g2D.drawString("c) Michaelangelo", 160, 120);

                 g2D.drawString("d) Pirate Fram", 160, 150);

                 g2D.drawString("e) None of the above", 160, 180);

          }

          //=================================================================================================

          else if (screen7 == true)

          {

                 BufferedImage img = null;

                 try

                 {

                        img = ImageIO.read(new File("twins.png"));  //img in project folder (Eclipse)

                        g2D.setColor(Color.white);

                        g2D.fillRect(0, 0, 500, 500);  //background

                        g2D.setColor(Color.black);

                        g2D.drawString("You're wrong.  It was the mysterious Fram twins pictured here.", 60, 20);

                     g2D.drawImage(img, 25, 80, null);

                 }   

                 catch (IOException e)

                 {

                        System.out.println("Error");

                        e.printStackTrace();  //Optional - Shows the location of the error issue.

                 }  

          }

          //=================================================================================================

          else if (screen8 == true)

          {

                 BufferedImage img = null;

                 try

                 {

                        img = ImageIO.read(new File("twins.png"));  //img in project folder (Eclipse)

                        g2D.setColor(Color.white);

                        g2D.fillRect(0, 0, 500, 500);  //background

                        g2D.setColor(Color.black);

                        g2D.drawString("You're right.  It was the mysterious Fram twins pictured here.", 60, 20);

                     g2D.drawImage(img, 25, 80, null);

                 }   

                 catch (IOException e)

                 {

                        System.out.println("Error");

                        e.printStackTrace();  //Optional - Shows the location of the error issue.

                 } 

                

          }

          //=================================================================================================         

   }

 

   public void keyTyped(KeyEvent e)

   {

   }

  

   public void keyPressed(KeyEvent e)

   {

        

   }

  

   public void keyReleased(KeyEvent e)

   {

             if (screen1 == true)

             {

               //move to screen 2

               screen2 = true;

               screen1 = false;

               repaint();

             }

             else if (screen2 == true)

             {

               //move to screen 3

               screen3 = true;

               screen2 = false;

               repaint();

             }

             else if (screen3 == true)

             {

               //move to screen 4

               screen4 = true;

               screen3 = false;

               repaint();

             }

             else if (screen4 == true)

             {

               //move to screen 5

               screen5 = true;

               screen4 = false;

               repaint();

             } 

             else if (screen5 == true)

             {

               //move to screen 6

               screen6 = true;

               screen5 = false;

               repaint();

             }

             else if (screen6 == true)

             {

                System.out.println(e.getKeyChar());

                if (e.getKeyChar() == 'a' || e.getKeyChar() == 'b' || e.getKeyChar() == 'c' || e.getKeyChar() == 'd')

                {

                       screen7 = true;  //go to YOU'RE WRONG screen

                       screen6 = false;

                       repaint();

                }     

                if (e.getKeyChar() == 'e')

                {

                       screen8 = true; //go to YOU'RE RIGHT screen

                       screen6 = false;

                       repaint();

                }     

             }

   }

}


IMAGES REQUIRED

 

Zip file