Keys
I am making a Traffic Simulator, I am nearing finished. But I want to add keyListeners to my project, yet I do not know how. Even after all my searching on the web..
anyway, what I want to happen, is when I press the '+' key, i want it to increase the motion on the screen (the pause function that is control of the thread method in the main), and vice versa.
This is my information I took on the web.. but it wasn't much help. But, Maybe it will be to you for understanding my problem :
import java.awt.event.*;
import javax.swing.*;
import java.util.List;
import java.util.Arrays;
publicclass KeyInputextends Trafficimplements KeyListener{
publicvoid init(){
}
publicvoid keyPressed(KeyEvent e){
KeyStroke key = KeyStroke.getKeyStrokeForEvent(e);
if (key == KeyEvent.VK_PLUS){
pause--;
}
elseif (key == KeyEvent.VK_MINUS){
pause++;
}
}
}
I hope you help. :D
Much thanks,
Adam.
Message was edited by:
pureleb
[1835 byte] By [
pureleba] at [2007-11-27 5:35:46]

KeyListener doesn't require an init() method. There's no need to include one, unless for some reason Traffic does -- but why extend Traffic? What were you hoping to accomplish by doing that?
You didn't say what your problem is, but I'm guessing that it's not compiling, because you didn't create a keyTyped or keyReleased method (and they're probably not in Traffic either). You have to implement all methods specified by an interface.
Probably the easiest thing would be to:
1) Stop extending Traffic -- it's probably not necessary, and probably not doing what you think it does
2) make your class extend KeyAdapter -- that way, you don't have to create methods you're not using (you'll inherit no-op defaults)
3) make your class an inner class, probably inside of Traffic. That way you'll get access to Traffic's internal state, which I'm guessing is what you were trying to accomplish by subclassing Traffic.
simple demo
(I've used 107/109 which are the keycodes for my notepad's +/-)
press the + key a few times and the flash rate will increase
the - key will decrease
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Testing
{
FlashPanel fp = new FlashPanel();
Timer timer;
public void buildGUI()
{
JFrame f = new JFrame();
f.getContentPane().add(fp);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
fp.requestFocusInWindow();
timer = new Timer(1000,new ActionListener(){
public void actionPerformed(ActionEvent ae){
fp.color = (fp.color == Color.BLUE? fp.getBackground():Color.BLUE);
fp.repaint();
}
});
timer.start();
fp.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent ke){
//System.out.println(ke.getKeyCode());//check what your +/- keyCodes are, modify next 2 lines accordingly
if(ke.getKeyCode() == 107) timer.setDelay((int)(timer.getDelay() * .75));
if(ke.getKeyCode() == 109) timer.setDelay((int)(timer.getDelay() * 1.25));
}
});
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Testing().buildGUI();
}
});
}
}
class FlashPanel extends JPanel
{
Color color = this.getBackground();
public FlashPanel()
{
setPreferredSize(new Dimension(300,300));
setFocusable(true);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(color);
g.fillOval(100,100,100,100);
}
}
Hello. And thanks for responding you two.
I just want traffic's int pause to be included in the new java class I made. I was trying out different coding for the functions.. which may explain the extends Traffic.
Furthermore, I have no idea how to create a class inside another class with Java.. I only used C++ before.. and well, I am sort of a newbie with Java.
Would it be something like this.. (Everything not used in this were omitted):
import java.awt.*;
import javax.swing.*;
import java.awt.event.*
public class Traffic extends JApplet implements runnable, KeyListener {
Thread myThread;//create a blank thre
int pause;
public void init() {
pause=125;
}public void start()// this is an applet method
{
if (myThread == null)// make sure the thread isn't already running
{
myThread = new Thread(this);// add myThread to this applet
myThread.start();// fire it up!
}
}
public void run()
{
// thread is now running in the background?now what?
Thread thisThread = Thread.currentThread();// gets the current thread
while (thisThread == myThread)// myThread is the current one
{
repaint();// do stuff here
try
{
Thread.sleep(pause);// put it to sleep for 1 sec.
}
catch (InterruptedException ie)
{
// an error occurred - do something
}
}
}
public void keyPressed(KeyEvent e){
System.out.println(e.getKeyCode());
if (e.getKeyCode() == 107) {
pause=pause-5;
}
else if (e.getKeyCode() == 109) {
pause=pause+5;
}
}
public void keyTyped(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
public void paint(Graphics g) {
g.setColor(Color.blue);
g.drawString("Frame Rate:"+pause, 0, 10);
}
}
Or.. Should the other code that Michael put up (and i'm very grateful!) be subbed in for my.. pretty bad code? .. + It doesn't work.. but it compiles!.. and thats always good. Any idea what I did wrong.. ?
Thank you.
Hope to hear from you again.
Message was edited by:
pureleb
Mike,I'm not the @OP but cool! Thanks for the fish.Keith.
> no idea how to create a class inside another class
That's a piece of the proverbial wheat flour based confectionery.public class YourMomma {
class You {
... some code ...
}
... some more code ...
}
That's a named inner class... it's also possible to create "anonymous inner classes"... but I prefer the explicit version... google that if/when you need to.
Keith.
Oh, thank you Keith.So there is no need to repeat public over and over I guess?And I will.Furthermore, anybody know what's wrong with my code above? The frame rate won't increase/decrease when I hit +/-.. and +, i don't see any output into the system.printIn..
leb,
Dude, your code formatting is atrocious, so I had to clean it up to follow it ... package forums;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingTraffic extends JApplet implements Runnable, KeyListener {
private static final long serialVersionUID = 9456434;
Thread myThread;
int pause;
public void init() {
pause=500;
}
public void start() {
if (myThread == null) {
// add myThread to this applet, and start it up
myThread = new Thread(this);
myThread.start();
}
}
public void run() {
// myThread is running in the background, so now what?
// catch myThread when it becomes the current one
Thread thisThread = Thread.currentThread();
while (thisThread == myThread) {
// do stuff here
repaint();
try {Thread.sleep(pause);} catch (InterruptedException ignore) {}
}
}
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyCode());
switch (e.getKeyCode()) {
case KeyEvent.VK_ADD:pause-=100; break;
case KeyEvent.VK_SUBTRACT: pause+=100; break;
default: System.out.println("unknown keycode"); break;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void paint(Graphics g) {
g.setColor(Color.blue);
g.drawString("Frame Rate:"+pause, 0, 10);
}
}
and No, it doesn't work for me either, and I don't know why ... and I'd love to know where System.out (etc) go in an applet... I suspect that they are redirected to /dev/null (ie nowhere).
Sorry I can't be more help... applets really aren't my thing.
He's right about your terrible formatting. You should learn to format your code properly, it'll save you soooo much time. Anyway, the problem with your program is as follows:
1) You need to add the KeyListener to your applet, which I did by adding this line of code: this.addKeyListener(new PauseListener());
2) In order to add the KeyListener to your applet, it has to be a seperate class, the best way is to make it an inner class, and it's the inner class that has to implement KeyListener not your Applet.
3) Once I got it working I realised that you don't clear the screen, so when the number's change they just draw over the one's that are already there. So I added: g.clearRect(0, 0, this.getWidth(), this.getHeight()); to your paint method.
Tested it and it works. Enjoy.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingTraffic extends JApplet implements Runnable {
private static final long serialVersionUID = 9456434;
Thread myThread;
int pause;
public void init() {
pause=500;
this.addKeyListener(new PauseListener());
}
public void start() {
if (myThread == null) {
// add myThread to this applet, and start it up
myThread = new Thread(this);
myThread.start();
}
}
public void run() {
// myThread is running in the background, so now what?
// catch myThread when it becomes the current one
Thread thisThread = Thread.currentThread();
while (thisThread == myThread) {
// do stuff here
repaint();
try {Thread.sleep(pause);} catch (InterruptedException ignore) {}
}
}
public void paint(Graphics g) {
g.clearRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.blue);
g.drawString("Frame Rate:"+pause, 0, 10);
}
public class PauseListener implements KeyListener{
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyCode());
switch (e.getKeyCode()) {
case KeyEvent.VK_ADD:pause-=100; break;
case KeyEvent.VK_SUBTRACT: pause+=100; break;
default: System.out.println("unknown keycode"); break;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
}
Oh! YAY! It worked. Thank you! Now I could see the cars zoom by me, and vice versa!! This is a real helper during my project too.
Heh. I'm aware that the code didn't 'turn' out well, but, if your deleted unnecesary things from your long code, it has the tendancy to come out that way.
But next time I post concerning my troubles with Java, you'll see the coding be quite well presented.
But yes! Thank you again. For all of your help.
> ... and I'd love to know where System.out (etc) go in an applet...They get printed on the console. Web browsers usually let you view the java console. (In IE6 it's under "Tools"->"Sun Java Console")