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

  • Home
  • SEARCH
  • 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 7933473
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T21:20:43+00:00 2026-06-03T21:20:43+00:00

Im using a KeyAdpater to get the events and the method addKeyListener and works

  • 0

Im using a KeyAdpater to get the events and the method addKeyListener and works fine. The problem is that when a press the key, the action ocurrs only once and not while its being pressed, after 3-4 secs holding down the key the action occurs all the time which is what I want.

I’d want to know if there is good way to do the action all the time the key is being pressed from the very begining, not after 3-4 seconds holding down.

I thought on the next solution, but maybe there is already an implemented way to do it:

public abstract class MyKeyAdapter extends KeyAdapter{
    private boolean isPressed = false;
    private int pressedKey = 0;
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            while(isPressed)
                keyPressedAction(pressedKey);
        }
    });    

    @Override
    public void keyPressed(KeyEvent e) {
            if(!isPressed){
                pressedKey = e.getKeyCode();
                t.start();
            }
    }
    @Override
    public void keyReleased(KeyEvent e) {
         if(isPressed && e.getKeyCode()==pressedKey)}
             isPressed = false;
    }

    public abstract void keyPressedAction(int key);
}
  • 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-03T21:20:44+00:00Added an answer on June 3, 2026 at 9:20 pm

    I’ve had good success with this by using Key Bindings, not a KeyListener, and start a Swing Timer on key press, and then stopping the Timer on Swing release. You can differentiate between the key press and release by passing the correct KeyStroke object into the bound component’s InputMap using the KeyStroke.getKeyStroke(int keyCode, int modifiers, boolean onKeyRelease) method found here: KeyStroke API. If the boolean parameter is false, the input will respond to key press, and the converse if the parameter is true.

    For a quick and inelegant example:

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class KeyBindingEg extends JPanel {
       private static final String UP_KEY_PRESSED = "up key pressed";
       private static final String UP_KEY_RELEASED = "up key released";
       private static final int UP_TIMER_DELAY = 200;
       private static final Color FLASH_COLOR = Color.red;
    
       private Timer upTimer;
       private JLabel label = new JLabel();
    
       public KeyBindingEg() {
          label.setFont(label.getFont().deriveFont(Font.BOLD, 32));
          label.setOpaque(true);
          add(label);
    
          setPreferredSize(new Dimension(400, 300));
    
          int condition = WHEN_IN_FOCUSED_WINDOW;
          InputMap inputMap = getInputMap(condition);
          ActionMap actionMap = getActionMap();
          KeyStroke upKeyPressed = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false);
          KeyStroke upKeyReleased = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true);
    
          inputMap.put(upKeyPressed, UP_KEY_PRESSED);
          inputMap.put(upKeyReleased, UP_KEY_RELEASED);
    
          actionMap.put(UP_KEY_PRESSED, new UpAction(false));
          actionMap.put(UP_KEY_RELEASED, new UpAction(true));
    
       }
    
       private class UpAction extends AbstractAction {
          private boolean onKeyRelease;
    
          public UpAction(boolean onKeyRelease) {
             this.onKeyRelease = onKeyRelease;
          }
    
          @Override
          public void actionPerformed(ActionEvent evt) {
             if (!onKeyRelease) {
                if (upTimer != null && upTimer.isRunning()) {
                   return;
                }
                System.out.println("key pressed");
                label.setText(UP_KEY_PRESSED);
    
                upTimer = new Timer(UP_TIMER_DELAY, new ActionListener() {
    
                   @Override
                   public void actionPerformed(ActionEvent e) {
                      Color c = label.getBackground();
                      if (FLASH_COLOR.equals(c)) {
                         label.setBackground(null);
                         label.setForeground(Color.black);
                      } else {
                         label.setBackground(FLASH_COLOR);
                         label.setForeground(Color.white);
                      }
                   }
                });
                upTimer.start();
             } else {
                System.out.println("Key released");
                if (upTimer != null && upTimer.isRunning()) {
                   upTimer.stop();
                   upTimer = null;
                }
                label.setText("");
             }
          }
    
       }
    
       private static void createAndShowGui() {
          KeyBindingEg mainPanel = new KeyBindingEg();
    
          JFrame frame = new JFrame("KeyBindingEg");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Using the C# Facebook SDK 5.0.3 everything works fine whit the client.Get(/me). But when
I'm using Key Events over Key Binding because I don't understand key binding yet.
Using the Redis info command, I am able to get all the stats of
Using Location.getBearing(); I seem to get randomly changing bearings. Aka, I can turn the
I'm working on a Java assignment that has to be done using AWT. I
I have a GUI window that I've created using Netbeans. I then ported the
Using mercurial, I've run into an odd problem where a line from one committer
hi i am using Eclipse Rcp and i need to validate the textbox that
Using this code I get no errors public static void kirisekle(string kirisadi, int genislik,
Using libgdx and just trying to get the HTML version of the basic setup

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.