Problem With Key Listener In Swing Applet

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 966 Views - Last Post: 31 December 2012 - 09:03 PM Rate Topic: -----

#1 extremeblueness  Icon User is offline

  • D.I.C Head

Reputation: 16
  • View blog
  • Posts: 186
  • Joined: 22-October 12

Problem With Key Listener In Swing Applet

Posted 29 December 2012 - 10:00 AM

I've been trying to fix this for over half a day: my key listener won't register input (I know this because I added a showStatus line inside the listener). I figured that before I mess up my code because I'm only a beginner when it comes to applets, I'd better ask you guys.

What I've tried:
  • having the JApplet request focus in window.
  • switching the component that gets focus to JPanel a1a1
  • making sure all containers containing a1a1 were focusable
  • removing the line in the stop method setting focusable to false
  • adding a showStatus to the key listener


Here's my init(), start(), stop(), and run() methods:

    public void init()
    {
        t = null;
        showStatus("Use a, w, s, and d keys like the arrow keys to move.");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException exc) {}
        showStatus("Use x key to check the squares around you.");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException exc) {}
        showStatus("Use j key to attack and defend.");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException exc) {}
        showStatus("Use k key to collect something.");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException exc) {}
        showStatus("Enemies will appear red on your map.");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException exc) {}
        showStatus("Resources will appear green on your map.");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException exc) {}
        showStatus("Permanent resources will eliminate your need for a certain item.");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException exc) {}
        showStatus("Your ultimate goal will be to take the ice castle from the walruses.");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException exc) {}
        life = rnd.nextInt(9);
        life += 6;
        showStatus("Your life: " + life + " out of 16 life.");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException exc) {}
        hunger = rnd.nextInt(9);
        hunger += 6;
        showStatus("Your hunger: " + hunger + " out of 16 hunger.");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException exc) {}
        thirst = rnd.nextInt(9);
        thirst += 6;
        showStatus("Your thirst: " + thirst + " out of 16 thirst.");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException exc) {}
        showStatus("If any stats reach zero, you will die.");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException exc) {}
        showStatus("By the way, the castle is disguised as a normal piece of land.");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException exc) {}
        try
        {
            SwingUtilities.invokeAndWait(new Runnable()
            {
                public void run()
                {
                    makeGUI();
                }
            });
        }
        catch (Exception exc)
        {
        }
        
        monsterALocationSet();
        monsterBLocationSet();
        monsterCLocationSet();
        healALocationSet();
        healBLocationSet();
        healCLocationSet();
        foodLocationSet();
        drinkLocationSet();
        itemsLocationStringSet();
        castleX = rnd.nextInt(49);
        castleY = rnd.nextInt(49);
        castleX++;
        castleY++;
        setCastleCoordinates();
        castleX = rnd.nextInt(49);
        castleY = rnd.nextInt(49);
        castleX++;
        castleY++;
        setPermFoodCoordinates();
        castleX = rnd.nextInt(49);
        castleY = rnd.nextInt(49);
        castleX++;
        castleY++;
        setPermDrinkCoordinates();
        
        addKeyListener(this);
    }
    
    public void start()
    {
        t = new Thread(this);
        pause = false;
        this.setFocusable(true);
        a1.setFocusable(true);
        a1a1.setFocusable(true);
        t.start();
    }
    
    public void stop()
    {
        pause = true;
        t = null;
    }
    
    public void run()
    {
        for( ; ; )
        {
            a1a1.requestFocusInWindow();
            try
            {
                if ((castleSmallLocation.equals(currentLocation) && (castleLargeLocation.equals(largeLocation))))
                {
                    repaint();
                    break;
                }
                else if ((castleSmallLocation.equals(currentLocation) && (castleLargeLocation.equals(largeLocation))))
                {
                    showStatus("Permanent food found!");
                    food = false;
                }
                else if ((castleSmallLocation.equals(currentLocation) && (castleLargeLocation.equals(largeLocation))))
                {
                    showStatus("Permanent drink found!");
                    drink = false;
                }
                if ((monsterALocation.equals(currentLocation) || monsterBLocation.equals(currentLocation) || monsterCLocation.equals(currentLocation)) && ch == 'j')
                {
                    monsterAttack();
                }
                else if (ch == 'x')
                {
                    look();
                }
                else if (ch == 'a')
                {
                    moveLeft();
                }
                else if (ch == 'd')
                {
                    moveRight();
                }
                else if (ch == 'w')
                {
                    moveUp();
                }
                else if (ch == 's')
                {
                    moveDown();
                }
                else if ((healALocation.equals(currentLocation) || healBLocation.equals(currentLocation) || healCLocation.equals(currentLocation) || foodALocation.equals(currentLocation) || foodBLocation.equals(currentLocation) || drinkALocation.equals(currentLocation) || drinkBLocation.equals(currentLocation)) && ch == 'k')
                {
                    collect();
                }
                else if (ch == 'B' && bobness == 0)
                {
                    bobness = 1;

                }
                else if (bobness == 1 && ch != 20000)
                {
                    if (ch == 'o')
                    {
                        bobness = 2;
                    }
                    else
                    {
                        bobness = 0;
                    }
                }
                else if (bobness == 2 && ch != 20000)
                {
                    if (ch == 'b')
                    {
                        bobness = 3;
                    }
                    else
                    {
                        bobness = 0;
                    }
                }
                if (bobness == 3)
                {
                    repaint();
                }
                
                Thread.sleep(20);
                if(pause)
                    break;
            }
            catch(InterruptedException exc) {}
            ch = 20000;
        }
    }



Here's my keyTyped(KeyEvent e), keyPressed(KeyEvent e), keyReleased(KeyEvent e), and paint(Graphics g) methods:

    public void keyTyped(KeyEvent e)
    {
        try
        {
            ch = e.getKeyChar();
            Thread.sleep(20);
            //run();
            showStatus("Key typed: " + ch);
        }
        catch(InterruptedException exc) {}
    }
    
    @Override
    public void keyPressed(KeyEvent e)
    {
    }
    
    @Override
    public void keyReleased(KeyEvent e)
    {
    }
    
    public void paint(Graphics g)
    {
        if(bobness == 3)
        {
            g.drawString(bob, 50, 50);
            bobness = 4;
        }
        
        String end = "You win!";
        if ((castleSmallLocation.equals(currentLocation) && (castleLargeLocation.equals(largeLocation))))
        {
            g.drawString(end, 50, 50);
        }
    }
}



Those are all the methods that make any mention of a key listener. Does anyone know what's going wrong?

I would post the whole applet, but it's 250,000 lines of code, most of which are graphics.

Is This A Good Question/Topic? 0
  • +

Replies To: Problem With Key Listener In Swing Applet

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8327
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Problem With Key Listener In Swing Applet

Posted 29 December 2012 - 03:21 PM

The Applet won't start before the init() method is finished so it is completly useless to sleep() in that method.

Your Applet needs to request focus for the KeyListener to work
Was This Post Helpful? 1
  • +
  • -

#3 extremeblueness  Icon User is offline

  • D.I.C Head

Reputation: 16
  • View blog
  • Posts: 186
  • Joined: 22-October 12

Re: Problem With Key Listener In Swing Applet

Posted 29 December 2012 - 05:56 PM

Look at the first line of code inside the for loop in run(). It does.
Was This Post Helpful? 0
  • +
  • -

#4 CasiOo  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1390
  • View blog
  • Posts: 3,075
  • Joined: 05-April 11

Re: Problem With Key Listener In Swing Applet

Posted 29 December 2012 - 08:08 PM

You are sleeping your event thread, that is a big no no!

Why would you even sleep in the keyTyped method? Seems very odd to me
I think you are having lots of problems because you don't know what you should be doing on the event thread, and what should be done on the 'game' thread
Was This Post Helpful? 1
  • +
  • -

#5 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 823
  • View blog
  • Posts: 2,533
  • Joined: 29-July 11

Re: Problem With Key Listener In Swing Applet

Posted 29 December 2012 - 09:24 PM

Your problem is non-obvious, but I can tell you that while the sleeping in the keylistener is bad design, it is not where your problem is. Just for the heck of it, did you mouse click in your applet window first?

This post has been edited by farrell2k: 29 December 2012 - 09:45 PM

Was This Post Helpful? 0
  • +
  • -

#6 extremeblueness  Icon User is offline

  • D.I.C Head

Reputation: 16
  • View blog
  • Posts: 186
  • Joined: 22-October 12

Re: Problem With Key Listener In Swing Applet

Posted 30 December 2012 - 09:34 AM

Yes, I did mouse-click in the window first.
Was This Post Helpful? 0
  • +
  • -

#7 extremeblueness  Icon User is offline

  • D.I.C Head

Reputation: 16
  • View blog
  • Posts: 186
  • Joined: 22-October 12

Re: Problem With Key Listener In Swing Applet

Posted 31 December 2012 - 09:53 AM

I was able to save in another file and edit my problem down to 165 lines of code. Unfortunately, I'm still clueless as to what my problem is:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
/*
<applet code="KeyListenerInitTest" width=400 height=400>
</applet>
*/

public class KeyListenerInitTest extends JApplet implements Runnable, KeyListener
{
    JPanel a1;
    JPanel a1a1;
    boolean pause;
    char ch = 0;
    Thread t;
    
    Random rnd = new Random();
    
    public void init()
    {
        t = null;
        try
        {
            SwingUtilities.invokeAndWait(new Runnable()
            {
                public void run()
                {
                    makeGUI();
                }
            });
        }
        catch (Exception exc)
        {
        }
        
        addKeyListener(this);
    }
    
    public void start()
    {
        t = new Thread(this);
        pause = false;
        this.setFocusable(true);
        a1.setFocusable(true);
        a1a1.setFocusable(true);
        t.start();
    }
    
    public void stop()
    {
        pause = true;
        t = null;
    }
    
    public void run()
    {
        for( ; ; )
        {
            a1a1.requestFocusInWindow();
            try
            {
                if (ch == 'j')
                {
                    //monsterAttack();
                    showStatus("Monster attack.");
                }
                else if (ch == 'x')
                {
                    //look();
                    showStatus("look.");
                }
                else if (ch == 'a')
                {
                    //moveLeft();
                    showStatus("left.");
                }
                else if (ch == 'd')
                {
                    //moveRight();
                    showStatus("right.");
                }
                else if (ch == 'w')
                {
                    //moveUp();
                    showStatus("up.");
                }
                else if (ch == 's')
                {
                    //moveDown();
                    showStatus("down.");
                }
                else if (ch == 'k')
                {
                    //collect();
                    showStatus("collect.");
                }
                
                Thread.sleep(20);
                if(pause)
                    break;
            }
            catch(InterruptedException exc) {}
            ch = 20000;
        }
    }
    
    public void makeGUI()
    {
        setLayout(new GridLayout (7,7));
        
        a1 = new JPanel(new GridLayout (7,7));
        
        showStatus("Rendering graphics.");
        renderGraphics();
    }
    
    public void renderGraphics()
    {
        
        setVariables();
        addComponents();
        
        setVisible(true);
    }
    public void setVariables()
    {
        a1a1 = new JPanel();
    }
    public void addComponents()
    {
        this.add(a1);
        
        a1.add(a1a1);
    }
    
    public void keyTyped(KeyEvent e)
    {
        //try
        {
            ch = e.getKeyChar();
            //Thread.sleep(20);
            //run();
            showStatus("Key typed: " + ch);
        }
        //catch(InterruptedException exc) {}
    }
    
    @Override
    public void keyPressed(KeyEvent e)
    {
    }
    
    @Override
    public void keyReleased(KeyEvent e)
    {
    }
    
    public void paint(Graphics g)
    {        
        String end = "You win!";
        g.drawString(end, 50, 50);
    }
}

Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8327
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Problem With Key Listener In Swing Applet

Posted 31 December 2012 - 10:26 AM

View Postextremeblueness, on 29 December 2012 - 08:56 PM, said:

Look at the first line of code inside the for loop in run(). It does.

Making a component setFocusable(true) does not give it the focus. It has to request it.
Was This Post Helpful? 0
  • +
  • -

#9 extremeblueness  Icon User is offline

  • D.I.C Head

Reputation: 16
  • View blog
  • Posts: 186
  • Joined: 22-October 12

Re: Problem With Key Listener In Swing Applet

Posted 31 December 2012 - 12:03 PM

YOU'RE NOT LOOKING WHERE I TOLD YOU TO!!!!!

It clearly requests focus inside the for loop inside the run() method.
Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8327
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Problem With Key Listener In Swing Applet

Posted 31 December 2012 - 12:13 PM

And you think you'll get help by giving -1 ?

:v:
Was This Post Helpful? 0
  • +
  • -

#11 extremeblueness  Icon User is offline

  • D.I.C Head

Reputation: 16
  • View blog
  • Posts: 186
  • Joined: 22-October 12

Re: Problem With Key Listener In Swing Applet

Posted 31 December 2012 - 12:22 PM

I want help, but not help that's obviously wrong. I told you two times now that it requests focus:

Quote

a1a1.requestFocusInWindow();

Was This Post Helpful? 0
  • +
  • -

#12 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 823
  • View blog
  • Posts: 2,533
  • Joined: 29-July 11

Re: Problem With Key Listener In Swing Applet

Posted 31 December 2012 - 12:55 PM

View Postpbl, on 31 December 2012 - 07:13 PM, said:

And you think you'll get help by giving -1 ?

:v:


I +1 you to even it back out because we are such good friends :)

@extremeblueness - Your problem is this:

a1a1.requestFocusInWindow();



in the for( ;; ) loop in your run method. Remove it.

Your JApplet has the KeyListener, but the JPanel a1a1 keeps stealing input focus, again, and again, and again...

This post has been edited by farrell2k: 31 December 2012 - 12:58 PM

Was This Post Helpful? 3
  • +
  • -

#13 extremeblueness  Icon User is offline

  • D.I.C Head

Reputation: 16
  • View blog
  • Posts: 186
  • Joined: 22-October 12

Re: Problem With Key Listener In Swing Applet

Posted 31 December 2012 - 01:10 PM

Well, at least the key listener registers input now. If I don't figure out why its not connecting to the run() method within a day or two, I'll post another topic.
Was This Post Helpful? 0
  • +
  • -

#14 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 823
  • View blog
  • Posts: 2,533
  • Joined: 29-July 11

Re: Problem With Key Listener In Swing Applet

Posted 31 December 2012 - 01:18 PM

View Postextremeblueness, on 31 December 2012 - 08:10 PM, said:

Well, at least the key listener registers input now. If I don't figure out why its not connecting to the run() method within a day or two, I'll post another topic.


What do you mean?
Was This Post Helpful? 1
  • +
  • -

#15 extremeblueness  Icon User is offline

  • D.I.C Head

Reputation: 16
  • View blog
  • Posts: 186
  • Joined: 22-October 12

Re: Problem With Key Listener In Swing Applet

Posted 31 December 2012 - 01:40 PM

I mean that the key listener changes the value of ch, but the run() method doesn't register it.

edit: it's not the ideal solution, but I moved the bulk of the run() method into the keyTyped(KeyEvent e) method. It seems that the run() method is the only method that failed to register the change in ch.

This post has been edited by extremeblueness: 31 December 2012 - 01:50 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2