Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8088701
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T19:09:59+00:00 2026-06-05T19:09:59+00:00

In the following program, i’m trying to change the text of a label based

  • 0

In the following program, i’m trying to change the text of a label based on the key pressed, but i dont know how to do it. The statements to be executed when a key is pressed are defined in actionPerformed() method of the TimerListener InnerClass. but I dont understand how do I access the label from there.

package aircraftPackage;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;

public class Controller extends JPanel {

    private static final long serialVersionUID = 1L;
    public static final int STEP = 3;
    private static final int TIMER_DELAY = STEP * 8;
    private BufferedImage playerImage = null;
    private Map<Direction, Boolean> directionMap = new HashMap<Direction, Boolean>();



    enum Direction {

        UP(KeyEvent.VK_UP, 0, -1), DOWN(KeyEvent.VK_DOWN, 0, 1),
        LEFT(KeyEvent.VK_LEFT, -1, 0), RIGHT(KeyEvent.VK_RIGHT, 1, 0);
        private int keyCode;
        private int xDirection;
        private int yDirection;

        private Direction(int keyCode, int xDirection, int yDirection) {
            this.keyCode = keyCode;
            this.xDirection = xDirection;
            this.yDirection = yDirection;
        }

        public int getKeyCode() {
            return keyCode;
        }

        public int getXDirection() {
            return xDirection;
        }

        public int getYDirection() {
            return yDirection;
        }
    }

    public Controller() {

        for (Direction direction : Direction.values()) {
            directionMap.put(direction, false);
        }
        setKeyBindings();
        Timer timer = new Timer(TIMER_DELAY, new TimerListener());
        timer.start();
    }

    private void setKeyBindings() {
        InputMap inMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actMap = getActionMap();
        for (final Direction direction : Direction.values()) {
            KeyStroke pressed = KeyStroke.getKeyStroke(direction.getKeyCode(), 0, false);
            KeyStroke released = KeyStroke.getKeyStroke(direction.getKeyCode(), 0, true);
            inMap.put(pressed, direction.toString() + "pressed");
            inMap.put(released, direction.toString() + "released");
            actMap.put(direction.toString() + "pressed", new AbstractAction() {

                private static final long serialVersionUID = 1L;

                @Override
                public void actionPerformed(ActionEvent e) {
                    directionMap.put(direction, true);
                }
            });
            actMap.put(direction.toString() + "released", new AbstractAction() {

                private static final long serialVersionUID = 1L;

                @Override
                public void actionPerformed(ActionEvent e) {
                    directionMap.put(direction, false);
                }
            });
        }

    }



    private class TimerListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            boolean moved = false;
            for (Direction direction : Direction.values()) {
                if (directionMap.get(direction)) {
                    if (direction.keyCode == 37) {
                        System.out.println("go LEFT");

                    } else if (direction.getKeyCode() == 39) {
                        System.out.println("go RIGHT");
                    } else if (direction.getKeyCode() == 38) {
                        System.out.println("go UP");
                    }
                    else if (direction.getKeyCode()==40){
                        System.out.println("go DOWN");
                    }
                }
            }
        }
    }

    public static void createAndShowUI() {
        JFrame frame = new JFrame("MoveIcon");
        JPanel panel = new JPanel();
        JLabel jl = new JLabel();
        jl.setText("testing....");
        frame.add(jl);
        frame.add(panel);
        frame.getContentPane().add(new Controller());
        new Controller();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

    public static void main(String[] args) {

        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            @SuppressWarnings("static-access")
            public void run() {
                createAndShowUI();
            }
        });
    }
}

Actually, what I wanted to do was, to create a nice form which would contain various labels in Netbeans(its easier to do it there) and use the above code just to know which key has been pressed and change values of each label accordingly.
I tried it, but it didnt work.
Please help me on this.
Thanks.

PS : You’ll find the parts of above code in some questions or on some sites, Because I didnt write it all by myself. I dont have any experience with keybindings/keyListeners etc before. this is just a part of a project im doing.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T19:10:01+00:00Added an answer on June 5, 2026 at 7:10 pm

    I tried to remove everything that you don’t need right now, and added a JLabel which displays the directions like this:

    go
    go UP
    go UP DOWN LEFT RIGHT


    This should get you started.

    import java.awt.event.*;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.*;
    
    public class Controller extends JPanel {
    
        private static final long serialVersionUID = 1L;
        private static final int STEP = 3;
        private static final int TIMER_DELAY = STEP * 8;
        private Map<Direction, Boolean> directionMap = new HashMap<Direction, Boolean>();
    
        private JLabel lblDirection = new JLabel();
    
        enum Direction {
    
            UP(KeyEvent.VK_UP), DOWN(KeyEvent.VK_DOWN),
            LEFT(KeyEvent.VK_LEFT), RIGHT(KeyEvent.VK_RIGHT);
    
            private int keyCode;
    
            private Direction(int keyCode) {
                this.keyCode = keyCode;
            }
    
            public int getKeyCode() {
                return keyCode;
            }
        }
    
        public Controller() {
    
            add(lblDirection);
    
            for (Direction direction : Direction.values()) {
                directionMap.put(direction, false);
            }
            setKeyBindings();
            Timer timer = new Timer(TIMER_DELAY, new TimerListener());
            timer.start();
        }
    
        private void setKeyBindings() {
            InputMap inMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            ActionMap actMap = getActionMap();
            for (final Direction direction : Direction.values()) {
                KeyStroke pressed = KeyStroke.getKeyStroke(direction.getKeyCode(), 0, false);
                KeyStroke released = KeyStroke.getKeyStroke(direction.getKeyCode(), 0, true);
                inMap.put(pressed, direction.toString() + "pressed");
                inMap.put(released, direction.toString() + "released");
                actMap.put(direction.toString() + "pressed", new AbstractAction() {
    
                    private static final long serialVersionUID = 1L;
    
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        directionMap.put(direction, true);
                    }
                });
                actMap.put(direction.toString() + "released", new AbstractAction() {
    
                    private static final long serialVersionUID = 1L;
    
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        directionMap.put(direction, false);
                    }
                });
            }
        }
    
        private class TimerListener implements ActionListener {
    
            @Override
            public void actionPerformed(ActionEvent e) {
                StringBuilder s = new StringBuilder("go ");
                for (Direction direction : Direction.values()) {
                    if (directionMap.get(direction)) {
                        s.append(direction.name() + " ");
                    }
                }
                lblDirection.setText(s.toString());
            }
        }
    
        public static void createAndShowUI() {
            JFrame frame = new JFrame("KeyMapping");
            frame.getContentPane().add(new Controller());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 80);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    createAndShowUI();
                }
            });
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Observe the following program written in Java (complete runnable version follows, but the important
The following program used the implementation of atomic locks from 'Cuda By Example', but
the following program needs to print the words First Second Third But because i
The following program compiles with g++ but then crashes upon running: class someClass {
The following program cannot compile in gcc. But it compiles OK with g++ and
The following program compiles with ifort (version 12) but not with GFortran (up to
The following program works correctly. However, I would like to change it to not
following program should print error but its printing success.why? #include<iostream> using namespace std; int
Following program list me all files in a directory but how can I display
The following program segfaults when v2 is printed but not during the array copy.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.