Solved

Help with KeyListener and Threading

Posted on 2003-12-08
13
805 Views
Last Modified: 2008-03-10
Hi there! I need some major help. I am in this programming course in high school and we are the guinea pigs this year because they have started teaching Java this year. Our teacher basically knows nothing about java and its obvious because when you ask him a question he has to research it first before he can help you. Anyways, I have an assignment due in 4 hours and im screwed. I need to make the game snake. I need to use a keylistener to get the arrow keys + other keys for other features and I need to be able to thread the keylistener and my graphics so that there is no delay in between. I am completely lost and nobody in my class knows how to thread (including my teacher).

import java.awt.*;
import java.awt.event.*;
import java.lang.Math;
import javax.swing.*;
import java.awt.Graphics;

public class KeyDemo2 extends JComponent implements KeyListener, Runnable
{

    int key = 0;
    int x = 0;
    public KeyDemo2 ()
    {
        addKeyListener (this);
        Thread t = new Thread (this);
        t.start ();
    }


    public void keyPressed (KeyEvent event)
    {
        key = event.getKeyCode ();
        System.out.println(key);
    }


    // handle release of any key
    public void keyReleased (KeyEvent event)
    {

    }


    // handle press of an action key
    public void keyTyped (KeyEvent event)
    {

    }


    public void run ()
    {
        try
        {
            while (true)
            {
                x++;
                repaint ();  // Show the change.
                Thread.sleep (100);
            }
        }
        catch (InterruptedException ie)
        {
        }
    }


    public void paint (Graphics g)
    {
        g.setColor (Color.white);
        g.fillRect (0, 0, size ().width, size ().height);
        g.setColor (Color.black);
        g.drawString (key + "", 50, 50);
        x++;
        g.drawRect (x, x, 1, 1);
    }



    public static void main (String [] args)
    {
        JFrame f = new JFrame ("HelloJava4");
        // Make the application exit when the window is closed.
        f.addWindowListener (new WindowAdapter ()
        {
            public void windowClosing (WindowEvent we)
            {
                System.exit (0);
            }
        }
        );
        f.setSize (300, 300);
        f.getContentPane ().add (new KeyDemo2 ());
        f.setVisible (true);
    }
}


This code runs but it only draws the dot moving from the top left corner to the bottom rite. It does not pick up key input. I have no idea what half of this code does. I am simply learning by example now cuz with four hours...i really have no choice. If you have any idea how i can get keyinput and output something (anything just to test) while drawing something else in the background. It would be very helpful. As you can see, i have set this to 500 points cuz i need help NOW!!!! Regards, pop.
0
Comment
Question by:popnfresh86
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 3
13 Comments
 
LVL 92

Assisted Solution

by:objects
objects earned 500 total points
ID: 9900729
you should override paintComponent() and not paint().
0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 9900742
i'd say the keyevents are getting swallowed up before they get to your component.
The preferred way for handling keys in Swing is with ActionMap's.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9900750
You're not actually trying to alter the progress of the point in your code. How do you want to do this?
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 92

Assisted Solution

by:objects
objects earned 500 total points
ID: 9900754
here's an example of mapping an action to a key stroke:
http://www.javaalmanac.com/egs/javax.swing/KeyStrokes.html?l=find
0
 
LVL 92

Assisted Solution

by:objects
objects earned 500 total points
ID: 9900771
I'd say you're not getting key events becuase your component never gets focus, try the following in your main:

        KeyDemo2 kd = new KeyDemo2 ();
        f.getContentPane ().add (kd);
        f.setVisible (true);
        kd.requestFocus();
0
 

Author Comment

by:popnfresh86
ID: 9901207
Well its not focus cuz if that was the case...the program shud work if i click on the executed window and then try entering keys.
0
 

Author Comment

by:popnfresh86
ID: 9901222
Im actually trying to make a snake game if that helps. Ignore the code i entered above. If you guys can gimme some code that allows a point to move up and down and left and right based on the arrow keys that are entered...that would be a great help cuz thats my main obstacle now.
0
 
LVL 92

Expert Comment

by:objects
ID: 9901380
> if i click on the executed window and then try entering keys.

not necessarily, the frame may have focus and not the component.
0
 
LVL 92

Expert Comment

by:objects
ID: 9901384
> If you guys can gimme some code that allows a point to move up and down and left
> and right based on the arrow keys that are entered

That'd be doing your assignment for you :)
0
 
LVL 92

Assisted Solution

by:objects
objects earned 500 total points
ID: 9901393
Here's an example you can use as a reference:
http://javaboutique.internet.com/Snake/
0
 
LVL 92

Assisted Solution

by:objects
objects earned 500 total points
ID: 9901409
to add direction control to your app I'd suggest adding member variables to store:
- current position
int x, y;
- current direction
int dx, dy;

and have your keylistener update the direction according to what key is pressed. And in your thread adjust the position according to the direction:
x += dx;
y += dy;
// need to check you don't go off board
0
 

Author Comment

by:popnfresh86
ID: 9901919
ok thanks guys but i happened to solve my own problem. I found a bunch of sites on threading with graphics and user input. I also found some other snake examples ... the one listed above isn't very helpful cuz the guy who made it doesn't know what commenting is and his variables aren't very clear. I have decided to split my points thruout all you guys who submitted a response (that was at least trying to be helpful).
0
 
LVL 92

Expert Comment

by:objects
ID: 9901942
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Suggested Courses

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question