Abdula Maher
Abdula Maher

Reputation: 3

How to add Key Listener to JFrame?

I am trying to control a rocket animation with my keys and have tried to use the KeyListener method, however, my program doesn't react to my key presses. I have tried adding keylistener to my JFrame but it does not call it since JFrame is a separate static method. If you run it you will not have the images however if you do run please replace with a rectangle. Can you please tell my mistake. Thanks in Advance.

Here is my code:

import java.awt.*;
import hsa.Console;
import javax.imageio.*;
import java.io.*;

import java.awt.Graphics;
import java.awt.Color;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

import javax.swing.*;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.Timer;

import java.util.Arrays;

public class MA_RocketLauncher extends JPanel implements ActionListener, KeyListener
{

    static Console c;

    //***********************************Main Program*********************************

    public static void main (String[] args)
    {

        c = new Console (27, 85);

        MainProgram ();

    }

    //********************************JFrame******************************************

    public static void JFrame()
    {

        JFrame jf = new JFrame();

        MA_RocketLauncher r = new MA_RocketLauncher();

        jf.setSize(692, 542);
        jf.setTitle("Rocket Launcher");
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setResizable(false);
        jf.add(r);

    }

    //********************************All Methods*************************************

    public static void MainProgram ()
    {

        //IntroMessage();
        //Password();

        JFrame ();

    }

    //***********************************Timer****************************************

    Timer t = new Timer(12, this);

    int y = 240, velY = 0, y2 = 300, velY2 = 0, x = 20, velX = 0, x2 = -5, velX2 = 0, y3 = -5, velY3 = 0,
        y4 = -5, velY4 = 0;

    //*********************************Rocket*****************************************

    public void paintComponent (Graphics c)
    {  

        super.paintComponent (c);

        Color darkGrey = new Color (32, 32, 32);

        c.setColor (darkGrey);
        c.fillRect (0, 0, 700, 550);

        c.setColor (Color.black);
        c.drawRect (18, 0, 639, 379);

        Image picture3 = loadImage ("Canada.png");
        c.drawImage (picture3, 19, 1, null);

        Font f2 = new Font ("Monaco", Font.BOLD, 20);

        c.setColor (Color.white);
        c.setFont (f2);

        c.drawString ("LIVE VIEW", 550, 25);

        Font f = new Font ("Courier New", Font.BOLD, 30);

        c.setColor (Color.red);
        c.setFont (f);

        c.drawString ("Status: ", 30, 420);

        c.setColor (Color.green);

        c.drawString ("        Launching!", 30, 420);

        Font f3 = new Font ("Courier New", Font.BOLD, 25);

        c.setFont (f3);

        c.drawString ("Clearance Level 1 Achieved", 30, 460);
        c.drawString ("ETA: 30 seconds", 30, 500);

        Image picture2 = loadImage ("circle_flag_us_america_united_states-512.png");
        c.drawImage (picture2, 627, 475, null);

        Font f1 = new Font ("Courier New", Font.BOLD, 12);

        c.setColor (Color.green);
        c.setFont (f1);

        c.drawString ("Property of the United States government", 340, 490);
        c.drawString ("Confidential Information", 450, 505);

        Image picture4 = loadImage ("RocketUp.png");

        c.drawImage (picture4, 100, y, null);
        c.drawImage (picture4, 500, y, null);

        t.start ();

        addKeyListener(this);

        setFocusable(true);

        setFocusTraversalKeysEnabled(false);

        if (y < -130)
        {

            c.setColor (darkGrey);
            c.fillRect (0, 0, 700, 550);

            c.setColor (Color.black);
            c.drawRect (18, 0, 639, 379);

            Image picture5 = loadImage ("Sky.png");

            c.drawImage (picture5, 19, 1, null);

            Image picture6 = loadImage ("RocketUpMedium.png");

            c.drawImage (picture6, 100, y2, null);
            c.drawImage (picture6, 500, y2, null);

            c.setColor (Color.white);
            c.setFont (f2);

            c.drawString ("LIVE VIEW", 550, 25);

            c.setColor (Color.red);
            c.setFont (f);

            c.drawString ("Status: ", 30, 420);

            c.setColor (Color.green);

            c.drawString ("        Launched!", 30, 420);

            c.setFont (f3);

            c.drawString ("Clearance Level 2 Achieved", 30, 460);
            c.drawString ("ETA: 20 seconds", 30, 500);

            c.drawImage (picture2, 627, 475, null);

            c.setColor (Color.green);
            c.setFont (f1);

            c.drawString ("Property of the United States government", 340, 490);
            c.drawString ("Confidential Information", 450, 505);

            if (y2 < -130)
            {

                c.setColor (darkGrey);
                c.fillRect (0, 0, 700, 550);

                c.setColor (Color.black);
                c.drawRect (18, 0, 639, 379);

                c.setFont (f2);
                c.setColor (Color.white);

                c.drawString ("LIVE VIEW", 550, 25);

                c.setColor (Color.red);
                c.setFont (f);

                c.drawString ("Status: ", 30, 420);

                c.setColor (Color.green);

                c.drawString ("        En Route!", 30, 420);

                c.setFont (f3);

                c.drawString ("Clearance Level 3 Achieved", 30, 460);
                c.drawString ("ETA: 10 seconds", 30, 500);

                c.drawImage (picture2, 627, 475, null);

                c.setColor (Color.green);
                c.setFont (f1);

                c.drawString ("Property of the United States government", 340, 490);
                c.drawString ("Confidential Information", 450, 505);

                Image picture7 = loadImage ("Space.jpg");

                c.drawImage (picture7, 19, 1, null);

                c.setFont (f2);
                c.setColor (Color.white);

                c.drawString ("LIVE VIEW", 550, 25);

                Image picture8 = loadImage ("Earth.png");

                c.drawImage (picture8, 19, 1, null);

                Image picture9 = loadImage ("RocketRightSmall.png");

                c.drawImage (picture9, x, 100, null);
                c.drawImage (picture9, x, 200, null);

                c.setColor (darkGrey);
                c.fillRect (658, 0, 40, 379);

                if (x > 658)
                {

                    c.setColor (darkGrey);
                    c.fillRect (0, 0, 700, 550);

                    c.setColor (Color.black);
                    c.drawRect (18, 0, 639, 379);

                    c.drawImage (picture7, 19, 1, null);

                    c.setFont (f2);
                    c.setColor (Color.white);

                    c.drawString ("LIVE VIEW", 550, 25);

                    c.setColor (Color.red);
                    c.setFont (f);

                    c.drawString ("Status: ", 30, 420);

                    c.setColor (Color.green);

                    c.drawString ("        Arriving!", 30, 420);

                    c.setFont (f3);

                    c.drawString ("Clearance Level 4 Achieved", 30, 460);
                    c.drawString ("ETA: 5 seconds", 30, 500);

                    c.drawImage (picture2, 627, 475, null);

                    c.setColor (Color.green);
                    c.setFont (f1);

                    c.drawString ("Property of the United States government", 340, 490);
                    c.drawString ("Confidential Information", 450, 505);

                    Image picture10 = loadImage ("Moon.png");

                    c.drawImage (picture10, 400, 100, null);

                    c.drawImage (picture9, x2, 100, null);
                    c.drawImage (picture9, x2, 200, null);

                    c.setColor (darkGrey);
                    c.fillRect (0, 0, 19, 379);

                    if (x2 > 450)
                    {

                        c.setColor (darkGrey);
                        c.fillRect (0, 0, 700, 550);

                        c.setColor (Color.black);
                        c.drawRect (18, 0, 639, 379);

                        c.drawImage (picture7, 19, 1, null);

                        c.setFont (f2);
                        c.setColor (Color.white);

                        c.drawString ("LIVE VIEW", 550, 25);

                        Image picture11 = loadImage ("MoonBig.png");

                        c.drawImage (picture11, 150, 250, null);

                        c.setColor (darkGrey);
                        c.fillRect (0, 380, 700, 170);

                        c.drawImage (picture2, 627, 475, null);

                        c.setColor (Color.green);
                        c.setFont (f1);

                        c.drawString ("Property of the United States government", 340, 490);
                        c.drawString ("Confidential Information", 450, 505);

                        c.setColor (Color.red);
                        c.setFont (f);

                        c.drawString ("Status: ", 30, 420);

                        c.setColor (Color.green);

                        c.drawString ("        Landing!", 30, 420);

                        c.setFont (f3);

                        c.drawString ("Clearance Level 5 Achieved", 30, 460);
                        c.drawString ("ETA: 2.5 seconds", 30, 500);

                        c.drawImage (picture6, 290, y3, null);
                        c.drawImage (picture6, 390, y3, null);

                        if (y3 > 290)
                        {

                            c.setColor (darkGrey);
                            c.fillRect (0, 0, 700, 550);

                            c.setColor (Color.black);
                            c.drawRect (18, 0, 639, 379);

                            Image picture12 = loadImage ("MoonSurface.jpg");
                            c.drawImage (picture12, 19, 1, null);

                            c.setFont (f2);
                            c.setColor (Color.white);

                            c.drawString ("LIVE VIEW", 550, 25);

                            c.drawImage (picture2, 627, 475, null);

                            c.setColor (Color.green);
                            c.setFont (f1);

                            c.drawString ("Property of the United States government", 340, 490);
                            c.drawString ("Confidential Information", 450, 505);

                            c.setColor (Color.red);
                            c.setFont (f);

                            c.drawString ("Status: ", 30, 420);

                            c.setColor (Color.green);

                            c.drawString ("        Taxi!", 30, 420);

                            c.setFont (f3);

                            c.drawString ("Clearance Level 6 Achieved", 30, 460);
                            c.drawString ("ETA: 1 second", 30, 500);

                            c.drawImage (picture4, 100, y4, null);
                            c.drawImage (picture4, 500, y4, null);

                            if (y4 > 260)
                            {

                                c.setColor (darkGrey);
                                c.fillRect (0, 0, 700, 550);

                                c.setColor (Color.black);
                                c.drawRect (18, 0, 639, 379);

                                c.drawImage (picture12, 19, 1, null);

                                c.setFont (f2);
                                c.setColor (Color.white);

                                c.drawString ("LIVE VIEW", 550, 25);

                                c.drawImage (picture2, 627, 475, null);

                                c.setColor (Color.green);
                                c.setFont (f1);

                                c.drawString ("Property of the United States government", 340, 490);
                                c.drawString ("Confidential Information", 450, 505);

                                c.setColor (Color.red);
                                c.setFont (f);

                                c.drawString ("Status: ", 30, 420);

                                c.setColor (Color.green);

                                c.drawString ("        Landed!", 30, 420);

                                c.setFont (f3);

                                c.drawString ("Clearance Level 7 Achieved", 30, 460);
                                c.drawString ("ETA: 0 seconds", 30, 500);

                                c.drawImage (picture4, 100, 260, null);
                                c.drawImage (picture4, 500, 260, null);

                                c.setColor(Color.green);

                                Font f4 = new Font ("Monaco", Font.BOLD, 100);
                                c.setFont(f4);

                                c.drawString("SUCCESS", 90, 200);

                            }

                        }

                    }

                }

            }

        }

    }   

    //********************************Action Listener Method**************************

    public void actionPerformed (ActionEvent e)
    {

        if (y < -130)
        {
            y2 = y2 - velY2;

            if (y2 < -130)
            {
                x = x + velX;

                if (x > 658)
                {

                    x2 = x2 + velX2;

                    if (x2 > 450)
                    {

                        y3 = y3 + velY3;

                        if (y3 > 290)
                        {

                            y4 = y4 + velY4;

                        }

                    }

                }

            }

        }

        y = y - velY;

        repaint();

    }

    //******************************Key Listener Method*******************************

    public void keyPressed (KeyEvent e)
    {

        int c = e.getKeyCode();

        if (c == KeyEvent.VK_LEFT)
        {

            velX = -1;

            velX2 = -1;

            velY = 0;

            velY2 = 0;

            velY3 = 0;

            velY4 = 0;

        }

        if (c == KeyEvent.VK_UP)
        {

            velY = -1;

            velY2 = -1;

            velY3 = -1;

            velY4 = -1;

            velX = 0;

            velX2 = 0;

        }

        if (c == KeyEvent.VK_RIGHT)
        {

            velX = +1;

            velX2 = +1;

            velY = 0;

            velY2 = 0;

            velY3 = 0;

            velY4 = 0;

        }

        if (c == KeyEvent.VK_DOWN)
        {

            velY = +1;

            velY2 = +1;

            velY3 = +1;

            velY4 = +1;

            velX = 0;

            velX2 = 0;

        }

    }

    public void keyTyped(KeyEvent e){}

    public void keyReleased(KeyEvent e){}

    //********************************Image Loader Method*****************************

    public static Image loadImage (String name)
    {

        Image img = null;

        try
        {

            img = ImageIO.read (new File (name));

        }

        catch (IOException e)
        {

        }

        return img;

    }

Upvotes: 0

Views: 1371

Answers (2)

Abdula Maher
Abdula Maher

Reputation: 3

So what I was doing wrong was putting the timer and key commands inside the pain component so all I had to do was create a public class and put my commands there. I also loaded the images from the main program and just called them in the paint component as the as the above answer states.

This is a part of my working code:

    import java.awt.*;
    import hsa.Console;
    import javax.imageio.*;
    import java.io.*;

    import java.awt.Graphics;
    import java.awt.Color;

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;

    import javax.swing.*;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.Timer;

    import java.util.Arrays;

    public class MA_RocketLauncher extends JPanel implements ActionListener, KeyListener
    {

        static Console c;

        //***********************************Main Program*********************************

        public static void main (String[] args)
        {

            c = new Console (27, 85);

            MainProgram ();

        }

        //********************************JFrame******************************************

        public static void JFrame()
        {

            JFrame jf = new JFrame();

            MA_RocketLauncher r = new MA_RocketLauncher();

            jf.setSize(692, 542);
            jf.setTitle("Rocket Launcher");
            jf.setVisible(true);
            jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jf.setResizable(false);
            jf.add(r);

        }

        //********************************All Methods*************************************

        public static void MainProgram ()
        {

            //IntroMessage();
            //Password();

            JFrame ();

        }

        //***********************************Timer****************************************

        Timer t = new Timer(10, this);

        int y = 240, velY = 0, y2 = 300, velY2 = 0, x = 20, velX = 0, x2 = -5, velX2 = 0, y3 = -5, velY3 = 0,
            y4 = -5, velY4 = 0;

        public MA_RocketLauncher()
        {

            t.start ();

            addKeyListener(this);

            setFocusable(true);

            setFocusTraversalKeysEnabled(false);

        }

        //**********************************Images****************************************

        Image picture2 = loadImage ("circle_flag_us_america_united_states-512.png");

        Image picture3 = loadImage ("Canada.png");

        Image picture4 = loadImage ("RocketUp.png");

        Image picture5 = loadImage ("Sky.png");

        Image picture6 = loadImage ("RocketUpMedium.png");

        Image picture7 = loadImage ("Space.jpg");

        Image picture8 = loadImage ("Earth.png");

        Image picture9 = loadImage ("RocketRightSmall.png");

        Image picture10 = loadImage ("Moon.png");

        Image picture11 = loadImage ("MoonBig.png");

        Image picture12 = loadImage ("MoonSurface.jpg");

        //*********************************Rocket*****************************************

        public void paintComponent (Graphics c)
        {  

            super.paintComponent (c);

            //Graphics

        }   

        //********************************Action Listener Method**************************

        public void actionPerformed (ActionEvent e)
        {

            if (y < -130)
            {
                y2 = y2 - velY2;

                if (y2 < -130)
                {
                    x = x + velX;

                    if (x > 658)
                    {

                        x2 = x2 + velX2;

                        if (x2 > 450)
                        {

                            y3 = y3 + velY3;

                            if (y3 > 290)
                            {

                                y4 = y4 + velY4;

                            }

                        }

                    }

                }

            }

            y = y - velY;

            repaint();

        }

        //******************************Key Listener Method*******************************

        public void keyPressed (KeyEvent e)
        {

            int c = e.getKeyCode();

            if (c == KeyEvent.VK_LEFT)
            {

                velX = -1;

                velX2 = -1;

            }

            if (c == KeyEvent.VK_UP)
            {

                if (y < -130)
                {

                    y = -1000;

                }

                else 
                {

                    velY = 1;

                }

                if (y2 < -130)
                {

                    y2 = -1000;

                }

                else
                {

                    velY2 = 1;

                }

                velY3 = -1;

                velY4 = -1;

            }

            if (c == KeyEvent.VK_RIGHT)
            {

                velX = +1;

                velX2 = +1;

            }

            if (c == KeyEvent.VK_DOWN)
            {

                velY = -1;

                velY2 = -1;

                velY3 = +1;

                velY4 = +1;

            }

        }

        public void keyTyped(KeyEvent e){}

        //*****************************Key Released Method********************************

        public void keyReleased(KeyEvent e)
        {

            velX = 0;

            velX2 = 0;

            velY = 0;

            velY2 = 0;

            velY3 = 0;

            velY4 = 0;

        }
}

Upvotes: 0

camickr
camickr

Reputation: 324207

The paintComponent(...) should only be used to do painting. It should NOT:

  1. read image files
  2. set properties of the panel: setFocusable(..), setFocusKeysEnabled(...)
  3. add listeners to the panel: addKeyListener(...)

All of the above code should be ONCE in the constructor.

The paintComponent() method is invoked every time a repaint() is done so you don't want to keep reading images or adding listeners.

You posted way too much code to look at. When you have a problem post a proper SSCCE that demonstrates the problem.

The usual reason a listener doen't work is because the panel doesn't have focus.

The common solution is to use Key Bindings, not a KeyListener. Read the section from the Swing tutorial on HOw to Use Key Bindings for more information.

Upvotes: 3

Related Questions