Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Keylistener
Index -> Programming, Java -> Java Help
Goto page 1, 2  Next
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
ScarletSkyFury




PostPosted: Thu Jun 08, 2006 12:50 pm   Post subject: Keylistener

Im trying to make a game and i am fairly new to JAVA and i want perform actions when i press a certain key(i.e ENTER) so that it then switchs to a different picture, however, i am pressing the key and its not responding, plz tell me in detail what i am doing wrong so i can avoid this problem in the future, any help would be greatly appreciated, thank you

//Applet #7

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Basketball extends Applet implements Runnable
{
Thread t;
Dimension dim;
Image offscreen;
Graphics bufferGraphics;
boolean myButtonPressed = false;
boolean myButtonEntered = false;
boolean intro = true;
boolean second = false;
boolean musictimer = true;
int myMouseX = 0, myMouseY = 0;
int myRow = -1, myCol = -1;
Image background, menu;
AudioClip music;
int key;
int pressdown;

public void init ()
{
music = getAudioClip (getDocumentBase (), "menu.wav");
dim = getSize ();
addKeyListener (new MyKeyListener ());
addMouseListener (new MyMouseListener ());
addMouseMotionListener (new MyMouseMotionListener ());
setBackground (Color.white);
offscreen = createImage (dim.width, dim.height);
bufferGraphics = offscreen.getGraphics ();
background = getImage (getCodeBase (), "Graphic1.gif");
menu = getImage (getCodeBase (), "menu.jpg");
if (musictimer == true)
{
music.play ();
musictimer = false;
}
} // end init method


// public void handleMouseEvents ()
// {
// int nCol = myMouseX;
// int nRow = myMouseY;
// if (!myButtonEntered) // assumed to be: if myButtonEntered is
// //not = true i.e. false
// nCol = nRow = -1;
//
// if (nCol != myCol || nRow != myRow)
// {
// myRow = nRow;
// myCol = nCol;
// repaint ();
//
//
// } //end if
// } // end handleMouseEvents method


public void paint (Graphics g)
{
bufferGraphics.clearRect (0, 0, dim.width, dim.height);

if (intro == true)
{
bufferGraphics.drawImage (background, 0, 0, 800, 600, this);
String startstring = "Mouse X:" + myMouseX + ", Mouse Y:" + myMouseY + ".";
bufferGraphics.setFont (new Font ("TimesRoman", Font.PLAIN, 20));
bufferGraphics.drawString (startstring, 30, 30);
}
else if (second == true)
{
bufferGraphics.drawImage (menu, 0, 0, 800, 600, this);
String startstring = "Mouse X:" + myMouseX + ", Mouse Y:" + myMouseY + ".";
bufferGraphics.setFont (new Font ("TimesRoman", Font.PLAIN, 20));
bufferGraphics.drawString (startstring, 30, 30);
}


g.drawImage (offscreen, 0, 0, this);


} // end Paint method


// public void intro (KeyEvent e)
// {
// repaint ();
// pressdown = e.getKeyChar ();
// if (key == 'f')
// {
// second = true;
// intro = false;
// }
//
// } //end intro method


// public void menu (KeyEvent e)
// {
//
// //second = false;
// }


public void music ()
{
t = new Thread (this);
t.start ();
} //end music method


public void update (Graphics g)
{
paint (g);
}


public void run ()
{
Thread.currentThread ().setPriority (Thread.MIN_PRIORITY);
while (true)
{

try
{

} //end try

catch (Exception e)
{

} //end catch

} //end while
} //end run


public class MyKeyListener implements KeyListener
{
public void keyTyped (KeyEvent e)
{
//repaint ();

}


public void keyPressed (KeyEvent e)
{
pressdown = e.getKeyChar ();
if (intro == true)
{
if (pressdown == KeyEvent.VK_ENTER)
{
intro = true;
second = false;
}
}
else if (second == true)
{
if (pressdown == KeyEvent.VK_SHIFT)
{
intro = true;
second = false;
}
}
repaint ();
}


public void keyReleased (KeyEvent e)
{

}
}


public class MyMouseListener implements MouseListener
{
public void mousePressed (MouseEvent me)
{
myButtonPressed = true;
myMouseX = me.getX ();
myMouseY = me.getY ();
//handleMouseEvents ();
}


public void mouseReleased (MouseEvent me)
{
myButtonPressed = false;
myMouseX = me.getX ();
myMouseY = me.getY ();
//handleMouseEvents ();
}


public void mouseEntered (MouseEvent me)
{
myButtonEntered = true;
myMouseX = me.getX ();
myMouseY = me.getY ();
//handleMouseEvents ();
}


public void mouseExited (MouseEvent me)
{
myButtonEntered = false;
myMouseX = me.getX ();
myMouseY = me.getY ();
//handleMouseEvents ();
}


public void mouseClicked (MouseEvent me)
{
} // if you comment out these 2 lines above, then you get an error message:


// class MyMouseListener must be declared abstract. It does not define
// public void mouseClicked(mouseEvent) from java.awt.event.MouseListener. etc.
// end mouseClicked method
} // end MyMouseListener class



public class MyMouseMotionListener implements MouseMotionListener
{
public void mouseMoved (MouseEvent me)
{
myMouseX = me.getX ();
myMouseY = me.getY ();
//handleMouseEvents ();
} // end mouseMoved method


public void mouseDragged (MouseEvent me)
{
myMouseX = me.getX ();
myMouseY = me.getY ();
//handleMouseEvents ();
} // end mouseDragged method
} // end MyMouseListener class
} // end mouselistener class
Sponsor
Sponsor
Sponsor
sponsor
HellblazerX




PostPosted: Thu Jun 08, 2006 4:27 pm   Post subject: (No subject)

Welcome to CompSci.ca. The next time you post code, make sure that you use code tags so we can identify what part of your post is code. First of all, with your if statement in your KeyListener:
code:
if (intro == true)
{
     if (pressdown == KeyEvent.VK_ENTER)
     {
          intro = true;
          second = false;
     }
}
else if (second == true)
{
     if (pressdown == KeyEvent.VK_SHIFT)
     {
          intro = true;
          second = false;
     }
}

In both cases, you set intro to true, and second to false, which means it won't matter what key you press, the values of intro and second will never change, and hence your picture will never change. The reason why your keylistener isn't registering the key pressings is because you're using the wrong values.
code:
pressdown = e.getKeyChar ();

getKeyChar () returns the char value of the key, but you need the int value of it, so you need to use the getKeyCode () method. It would look something like this:
code:
pressdown = e.getKeyCode ();

If you use that, then the if statements will register the key pressings.
.hack




PostPosted: Tue Jun 13, 2006 10:11 am   Post subject: (No subject)

am having similiar difficulty, however I have narrowed it down since last post, that I guess wasn't posted properly due to lack of response. This involves the key pressing, but took a different route.

Essentially this is for a menu.

As far as I know, yesterday it worked, and today it does not, and I'm sure why, I may have removed something I needed. Anyways, maybe someone can give me a hand.

code:

//Gets the keypress
public boolean keyDown (Event e, int key)
{
if (key == Event.UP)
pressedUp = true;
System.out.println ("UP KEY PRESSED");
menupos--;
Menubeep.play ();
if (menupos == 0)
{
menupos = 1;
}
keyact = true;


if (key == Event.DOWN)
pressedDown = true;
System.out.println ("DOWN KEY PRESSED");
menupos++;
Menubeep.play ();
if (menupos == 4)
{
menupos = 3;
}
keyact = true;




if (key == Event.LEFT)
pressedLeft = true;


if (key == Event.RIGHT)
pressedRight = true;


if (key == 32)
pressedSpace = true;
menuselect = true;
keyact = true;


repaint ();
return true;

}


As far as I know now, when pressing a key, it doesn't output the text I asked it to for testing purposes. So the event isn't even becoming activated and I don't know why. I followed a tutorial on this method directly. Is there a different / better / easier way to do this?


the menupos comes into play in the paint method::

code:


while (keyact == true)
        {
            if (menupos == 1)
            {
                System.out.println ("POS 1 v 2 TEST");
                g.drawImage (br, 290, 355, this);
                repaint ();
                keyact = false;

            }
            if (menupos == 2)
            {
                System.out.println ("POS 2 V 2 TEST");
                g.drawImage (br, 290, 395, this);
                repaint ();
                keyact = false;
            }
            if (menupos == 3)
            {
                System.out.println ("POS 3 V 2 TEST");
                g.drawImage (br, 290, 435, this);
                repaint ();
                keyact = false;
            }
        }



What is supposed to happen is it checks the menu position and moves the icon accordingly, then resets keyact to false so it is ready for more input. This part doesn't concern that much, since the program isn't accepting the keydown at all.

Sorry about the reposting. I screwed up the tags twice when editing. We need an edit post function >.<
HellblazerX




PostPosted: Tue Jun 13, 2006 4:48 pm   Post subject: (No subject)

Maybe it's because you're missing brackets in if statements. I know in some cases you don't need the bracket, but I'm not sure if it works with code with more than one line. When I copied your code into RTP, and then indented, only first line after the if statement was indented forward. The rest were not. It's possible that only the line after your if statement was read, and the rest were considered outside the if statement.
wtd




PostPosted: Tue Jun 13, 2006 5:01 pm   Post subject: (No subject)

Indeed.

Tell me what happens in the following examples:

I should be indenting, but that would make it too easy for you.

code:
if (true)
System.out.println("hello");
System.out.println("world");


code:
if (false)
System.out.println("hello");
System.out.println("world");


code:
if (false) {
System.out.println("hello");
System.out.println("world");
}
ScarletSkyFury




PostPosted: Wed Jun 14, 2006 3:32 pm   Post subject: (No subject)

Sorry if i didnt follow the rules when i made my first post, i have a few more questions/problems i have come across while trying to make my game

1.i have a music playing in the background and i want a beep noise to play whenever the user presses a button(ENTER) but i dont know how to multithread, can anyone give me anytips?

this is how my background music method looks like:
Quote:

public void music ()
{
t = new Thread (this);
t.start ();
} //end music method


2.This is a BIG problem, everytime i put a picture on the screen for the first time, it takes about 6-10 seconds to load, but after the first time if i want it to come up again it goes instantly...is there nayway to get rid of that first time 10 second load delay?

3. i know this question might sound a bit nooie but can anyone show me how to set delays(Eg....delay between pictures being drawn on the screen)

thank you
HellblazerX




PostPosted: Wed Jun 14, 2006 4:35 pm   Post subject: (No subject)

To answer your questions:

1. Well, since you're using AudioClips to play your sound files, why not use the AudioClip's own loop () method to continually play the background music. It should create its own separate thread to play this.

2. No there isn't. The first 6-10 seconds of delay means that your computer is loading that up image into its memory for use. The reason why everytime after that you run your program and you have no delay, is because that image is already in memory. The only way to speed up the loading is to get more memory or a better computer, or use smaller images.

3. What you're looking for is the method Thread.sleep (). However, this method requires an Exception object to be thrown (error-proofing), so you should make your own method to do this. A delay method would look like this:
code:
private void delay (int len) {
    try {
        Thread.sleep (len);
    }
    catch (Exception e) {
    }
}

Just put this into your code, and call up the method when you need a delay.
ScarletSkyFury




PostPosted: Wed Jun 14, 2006 7:00 pm   Post subject: (No subject)

Thank you, hmmmm im sure there has to be a way to take off the loading time off the pictures....because then what if i want to use the image only once...my point is that with the loading time..my game is gonna look like crap

what about this...maybe this can take off the loading time:

Quote:

I've never seen that method used to load up images. I only know two ways to load up an image. First of course, is to use Swing's ImageIcon class, and the way you do this is like this:
Code:
Image title = new ImageIcon ("startmenu.jpg").getImage ();

The other is to use the ImageIO class, which is supposedly be much more efficient. You'll have import it in first:
Code:
import javax.ImageIO.*;

Image title = ImageIO.read (new File ("startmenu.jpg"));

However, I'm not sure ImageIO will work with normal Image objects, so you might have to switch to BufferedImages. Also, it would probably best if you did the initialization of your Image objects inside the constructor. That way, the program won't continue until the image has been loaded.


the main reason why that botheres me so much is because what if...for example my game is in a sorta talking-scene between two characters..that would take forever to have the talking scene play and while i know that once a picture is loaded it will load again instanty...my game would only show that talking scene once anyways..so yeah i need that delay off to make my game look professional...and if the only solution is a better RAM then how much would you suggest


Also about one of my previous questions...maybe you didnt understand my question or i didnt understand your answer but ill explain it again....In my game i am in a title screen where there are two options, 1.new game, 2. instructions and while that screen is on, a music is playing but if the user presses ENTER on either of the options i want a beep noise to come up(while the background song is still playing)......wouldnt the thread.sleep stop the background song from playing thus then playing the beep noise..i want them simultaniously is what i am trying to say

last question how do i make a music play over and over again...and if i wanted to, how would i stop the endless loop if needed to(to switch to another song)?

thank you
Sponsor
Sponsor
Sponsor
sponsor
HellblazerX




PostPosted: Wed Jun 14, 2006 8:04 pm   Post subject: (No subject)

ScarletSkyFury wrote:
my point is that with the loading time..my game is gonna look like crap

Lol, the ironic part of that is that most good games have long loading times. Actually the method I proposed for .hack was to prevent his image objects from being used before they're properly loaded up. However, those methods are supposed to be very efficient and fast when loading up images, with the ImageIO supposedly being 10% faster than the ImageIcon method. If you use those, I'm sure the images will take much less time to be loaded up.
ScarletSkyFury wrote:
wouldnt the thread.sleep stop the background song from playing

No, see, the Thread.sleep () method stops the current thread that is running for a period of time, but it doesn't affect any other threads that are running. See, if you place that method inside your main loop, then the only thread that can call that sleep () method is your main thread, and thus, only your main thread will be stopped. The thread started by your AudioClip object (I think they use threads anyways) will not be affected in anyway, except for the fact that it'll be getting more CPU time.
ScarletSkyFury wrote:
last question how do i make a music play over and over again...and if i wanted to, how would i stop the endless loop if needed to(to switch to another song)?

Just call the loop () method in your AudioClip to cause it to play continually, and call the stop () method to stop it.
ScarletSkyFury




PostPosted: Wed Jun 14, 2006 8:19 pm   Post subject: (No subject)

Thank you....any else you think i should know/tips if im trying to make an RPG game
ScarletSkyFury




PostPosted: Wed Jun 14, 2006 8:26 pm   Post subject: (No subject)

(sorry for the double posting...WHERE is the edit button)

anyways, if im using ready to program 1.17, would that be a probelm for me trying to load "import javax.ImageIO.*;" because it gives me an error when i include that line in my program

ps: i am in high school so i dont know if the version im using is very good, i have a feeling its not 0.o
HellblazerX




PostPosted: Wed Jun 14, 2006 9:51 pm   Post subject: (No subject)

Wait, are you using version 1.7, or version 1.17? Because ImageIO should be in version 1.7. If you're using an older version, then ImageIO wouldn't be available to you.
ScarletSkyFury




PostPosted: Thu Jun 15, 2006 3:16 pm   Post subject: (No subject)

Ohhh man heres my new problem:

java.lang.OutOfMemoryError

ok im using:

1 .wav file
13 PNG pixtures
1 GIF picture

The PNG pictures range from 350-450kb each...is that what could be causing the problem or is the RAM on my PC not good enough(800RAM)
whats kinda weird is that i made a RPG on turing and i used soooo many more pictures then i am currently using in JAVA and i never had any problems....i am getting(getCodeBase) all the pictures/music from my MP3(they are all stored there) and my MP3(1GB) is alomst full, dont know if that has anything to do with it.

well i cant run my game cause of that error...any suggestions would be greatly appreciated....my game is due soon so plz i really need this
Thank you
HellblazerX




PostPosted: Thu Jun 15, 2006 4:34 pm   Post subject: (No subject)

I didn't even know Java supported PNG format. Jeez, and half a megabyte a piece, too. I suggest you convert those images into something else, like gif or jpeg format, something that will much easier on your computer. You most likely recieved that error because you ran out of memory. Make sure you load those images up only once, and don't call on them on the fly, or else they'll start accumulating in your memory.
rizzix




PostPosted: Thu Jun 15, 2006 5:24 pm   Post subject: (No subject)

Usually I've get an out of memory error when I try to load up an arry with a gazillion elements.. just check your algorithms.. make sure you are not unnecessarily holding references to very large objects or too many objects (like in an array, list, hashmap, etc)..
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 2  [ 24 Posts ]
Goto page 1, 2  Next
Jump to:   


Style:  
Search: