Results 1 to 5 of 5
  1. #1
    tjamzt is offline Member
    Join Date
    Sep 2011
    Posts
    3
    Rep Power
    0

    Default Key Event in Loop *Solved*

    Hi, I am very new (3 weeks) to java and i am wondering how I would get a key event inside while loop. I am trying to create a very simple version of pong with some basic code (creates a screen and draws a ball) that I modified. I tried putting the key event outside the while loop but it doesnt work and I have no idea how to move it inside. Thanks for any help.

    Java Code:
    [B]BallSimple.java[/B]
    
    package Ball;
    
    // import built in classes that you need to use
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    import java.awt.event.*;
    import java.util.Random;
    
    
    //import java.util.Random;
    
    
    public class BallSimple {
    	
    	
    	Boolean running = true;
    
    	//set x and y position
    	int x_pos = 20;
    	int y_pos = 20;
    	int paddle_posx = 600;
    	
    	//set x and y velocity
    	int velocityx = 3;
    	int velocityy = 3;
    	int velopaddle = 5;
    	
    	//set background and ball color
    	Color BackCol = Color.cyan;
    	Color BallCol = Color.red;
    	
    	//define paddle movement
    	public void keyPressed(KeyEvent evt) { 
    		int key = evt.getKeyCode();
    		if (key == KeyEvent.VK_UP){
    			System.out.println("Key Pressed");
    		}
    	}
    	
    	// Constructor - accepts arguments and builds object
    	public BallSimple(JFrame window) {
    		
    		// get graphics object from JFrame so we can draw on it
    		Graphics g = window.getGraphics();
    	
    	
    		//while loop to run program
    		while(running){
    			
    			g.setColor(BackCol);			
    			g.fillRect(0, 0, window.getWidth(), window.getHeight());	// this is bad coding practice, use descriptively named variables
    			g.setColor(BallCol);
    			g.fillOval(x_pos, y_pos, 25, 25);
    			g.setColor(Color.white);
    			g.drawLine(paddle_posx, 200, paddle_posx, 280);
    		
    			//right side collision
    			if (x_pos < 0){
    				velocityx*=-1;
    				ColorChangeBG();
    				ColorChangeBall();
    			}
    			
    			else if (x_pos + 12.5 > window.getWidth()){
    				velocityx*=-1;
    				ColorChangeBG();
    				ColorChangeBall();
    			}
    			
    			if (y_pos + 12.5 > window.getHeight() || y_pos - 12.5 < 0){
    				velocityy*=-1;
    				ColorChangeBG();
    				ColorChangeBall();
    			}
    			
    			//move ball
    			x_pos += velocityx;
    			y_pos += velocityy;
    			
    			
    			// puts current application thread to sleep for specified number of milliseconds
    			// try-catch block checks for error exception
    			try {
    				Thread.sleep(15);
    			} catch (InterruptedException ex) {
    				System.out.println("Could not sleep!");
    			}
    			
    		} // end for loop
    	} // end constructor
    	
    	private void ColorChangeBG(){
    		Random rand = new Random(); 
    		int RandomColor = rand.nextInt(5);
    		switch (RandomColor) {
    	    	case 0: 
    	    		BackCol = Color.green;
    	    		break;
    	    	case 1: 
    	    		BackCol = Color.black;
    	    		break;
    	    	case 2: 
    	    		BackCol = Color.white;
    	    		break;
    	    	case 3: 
    	    		BackCol = Color.blue;
    	    		break;
    	    	case 4: 
    	    		BackCol = Color.white;
    	    		break;
    		}
    		}
    	
    	private void ColorChangeBall(){
    		Random rand = new Random(); 
    		int RandomColor = rand.nextInt(5);
    		switch (RandomColor) {
    	    	case 0: 
    	    		BallCol = Color.orange;
    	    		break;
    	    	case 1: 
    	    		BallCol = Color.magenta;
    	    		break;
    	    	case 2: 
    	    		BallCol = Color.yellow;
    	    		break;
    	    	case 3: 
    	    		BackCol = Color.cyan;
    	    		break;
    	    	case 4: 
    	    		BackCol = Color.DARK_GRAY;
    	    		break;
    		}
    	}
    
    } // end ball class
    Java Code:
    [B]Screen.java[/B]
    
    package Ball;
    import javax.swing.JFrame;
    
    // new class screen is an extension of built in class JFrame and inherits
    // its properties, like setSize, setLocation etc.
    public class Screen extends JFrame {
    	
    	// constructor, where properties of object are set
    	public Screen(String frameLabel) {
    		setSize(640, 480);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setVisible(true);
    	}
    	
    	// main method to start object
    	public static void main(String[] args){
    		
    		// create a screen and a simple ball animation on it
    		Screen window = new Screen("new screen");
    		new BallSimple(window);
    	}
    	
    }
    Last edited by tjamzt; 09-25-2011 at 06:01 AM.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Key Event in Loop

    Please allow me the courtesy of being blunt -- your code is bad on many levels, almost too many to enumerate, but I'll try to point out a few.

    • You're doing an infinite loop (while(true)) on the main Swing thread, the event dispatch thread which will put your GUI completely to sleep.
    • You're calling Thread.sleep on the main Swing thread, the event dispatch thread which will put your GUI completely to sleep.
    • Your getting your Graphics object from a component via its getGraphics() method and expecting that this will persist -- it won't, and you'll lose your drawing if a re-draw must occur.
    • You're trying to use a key listener instead of key bindings
    • Even if it were recommended to use a KeyListener here, you don't have a class that implements the interface.
    • You're not painting within the paintComponent method of a JComponent or one of its children such as a JPanel
    • You're not using a Swing Timer or a background thread for your animation loop


    The key is to find and read the tutorials on Swing, Swing graphics, and Swing Timers first before trying to code this stuff. Much of it is not intuitive (at least not for me), and so assumptions must be thrown out before this type of code can work.
    Last edited by Fubarable; 09-25-2011 at 05:19 AM.

  3. #3
    tjamzt is offline Member
    Join Date
    Sep 2011
    Posts
    3
    Rep Power
    0

    Default Re: Key Event in Loop

    Like I said I am completely new to java and also to programming. Should I just rewrite the entire entire thing after reading the tutorials?

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Key Event in Loop

    Quote Originally Posted by tjamzt View Post
    Like I said I am completely new to java and also to programming. Should I just rewrite the entire entire thing after reading the tutorials?
    Yeah, you'll not want to use this code. Nothing wrong with being new, and once you get a handle on the tutorials, this will go much more smoothly.

  5. #5
    tjamzt is offline Member
    Join Date
    Sep 2011
    Posts
    3
    Rep Power
    0

Similar Threads

  1. JTextField loop 2x for-loop WEIRD!
    By Streetproject in forum AWT / Swing
    Replies: 2
    Last Post: 02-16-2011, 05:46 PM
  2. while-loop stopping on first loop
    By davester in forum New To Java
    Replies: 6
    Last Post: 06-26-2009, 08:46 PM
  3. checking for an event during an event
    By infinity in forum AWT / Swing
    Replies: 22
    Last Post: 04-09-2009, 01:08 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •