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 6830679
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T22:38:47+00:00 2026-05-26T22:38:47+00:00

I’m having trouble with the default Java KeyListener in my project. I noticed that

  • 0

I’m having trouble with the default Java KeyListener in my project.
I noticed that the KeyListener doesn’t seem to get KeyEvents forwarded sometimes when I start.

Symptoms of the problem:
When starting the application key input isn’t processed. This only happens sometimes. Sometimes I have to close and start the app 7-8 times until this shows up. Sometimes it’s the first try. When it happens it won’t work until I restart the app again.

What I’m using:
Window 7 x64 and the newest Eclipse and JDK versions.

What I found out already:
I’ve put a breakpoint in debug mode and checked the JPanel instance out. The KeyListener is always successfully added to it, it seems.
Also, MouseListener and MouseMotionListener work just fine, all the time.

Minimal code:

public class Player implements KeyListener
{
    public void keyTyped(KeyEvent e){}
    public void keyReleased(KeyEvent e){ }

    public void keyPressed(KeyEvent e){
        System.out.println("Key Pressed!");
    }

}

public class Game {

    public static void main(String[] args) {
        new Game();
    } 

    public Game(){
        JFrame window = new JFrame();
        window.setVisible(true);

        //Now set the window size correctly
        window.setSize(800, 600);  
        //Set-up the rest of the window
        window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        window.setResizable(true);


        //Create our panel
        JPanel canvas = new JPanel();
        canvas.setFocusable(true);
        window.add( canvas ); //Add it to our window

        Player k = new Player();
        canvas.addKeyListener(k);
    }
}

Thank you for your time!

PS:
Ok, answer to my own question:

It seems that I have to call setVisible(true) after setting the window’s size:

    JFrame window = new JFrame();


    Now set the window size correctly
    window.setSize(800, 600);  
    window.setVisible(true);

Switching out the setSize() and setVisible() like this seems to make it work. Tried it about a dozen times without a problem.

I guess setVisible might not like giving Focus to the window if it’s of size 0x0.
The question is: Why does this only cause a problem in one out of some cases?

  • 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-05-26T22:38:48+00:00Added an answer on May 26, 2026 at 10:38 pm

    Try adding a JButton to your “canvas” JPanel, then pressing the button and seeing what happens to your KeyListener — it fails because the JPanel lost the focus. To prevent this from happening, use Key Bindings instead (see the link in my comment above for the tutorial). For e.g.,

    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class Game2 {
    
       private static final String UP = "up";
    
       public static void main(String[] args) {
          new Game2();
       }
    
       public Game2() {
          JFrame window = new JFrame("Press up-arrow key");
          window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
          JPanel canvas = new JPanel();
          canvas.setPreferredSize(new Dimension(400, 300));
          window.add(canvas);
    
          canvas.add(new JButton(new AbstractAction("Press space-bar") {
             public void actionPerformed(ActionEvent e) {
                System.out.println("Button or space-bar pressed");
             }
          }));
          ActionMap actionMap = canvas.getActionMap();
          int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
          InputMap inputMap = canvas.getInputMap(condition);
    
          inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), UP);
          actionMap.put(UP, new UpAction());
    
          window.pack();
          window.setLocationRelativeTo(null);
          window.setVisible(true);
       }
    }
    
    @SuppressWarnings("serial")
    class UpAction extends AbstractAction {
       @Override
       public void actionPerformed(ActionEvent arg0) {
          System.out.println("Up Arrow pressed!");
       }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
We're building an app, our first using Rails 3, and we're having to build
I need a function that will clean a strings' special characters. I do NOT
I'm trying to create an if statement in PHP that prevents a single post

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.