Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Java Applet Help: Keylistener/

  1. #1
    Junior Member
    Join Date
    May 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Unhappy Java Applet Help: Keylistener/

    So for my computer science class we are required to make a video game. I've made a game using an Applet, and it runs properly. Problem is, the KeyListener and the ActionListener won't cooperate. The button will work, but the arrow keys moving the sprite will not. I tried making a seperate class for the button and the game, but they won't work together either. Is there any way around this?

    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.Button;
    import java.net.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
     
    public class VideoGameProject extends Applet implements Runnable, KeyListener, ActionListener
     
    {   
    	Button battle; 
     
    	Image background;
    	Image frontview;
     
    	int dx, dy;
    	int xpos, ypos;
    	int random;
     
    	int xCoord, yCoord;
     
    	Thread runner;
     
    	public void init() 
    	{
    		battle = new Button("Look for Pokemon");
    		battle.addActionListener(this);
    		add(battle);
     
    		background = getImage(getDocumentBase(),"BACKGROUND.png");	
    		frontview = getImage(getDocumentBase(),"frontview.png");
    		addKeyListener(this);
    		add (battle);
    	}
     
    	public void start()
    	{
    		if (runner == null)
    		{
    			runner = new Thread(this);
    			runner.start();
    		}
    	}
     
    	public void stop()
    	{
    		if (runner != null)
    		{
    			runner.stop();
    			runner = null;
    		}
    	}
     
    	public void run()															
    	{
    		setBackground(new Color(102,197,153));
    		while(true)
    		{
     
    			repaint();
     
    			xpos+=dx;
    			ypos+=dy;
     
    			if (xpos>getWidth()-30 || xpos<0)
    				dx*=0;
    			if (ypos>getHeight()-30 || ypos<0)
    				dy*=0;
     
    			try {Thread.sleep(100);}
    			catch(InterruptedException e) { }
     
    		}
     
    	}
     
    	public void paint(Graphics g) 
    		{
    					this.setSize(370, 540);
    					g.drawImage(background,0,0,this);
     
    					g.drawImage(frontview, xpos, ypos, this);
     
    					g.setColor(Color.gray);
    					g.fillRect(45,40,60,20);
    					g.fillRect(65,20,20,60);
    					g.setColor(new Color(200,30,26));
    					g.fillOval(260,50,30,30);
    					g.fillOval(300,30,30,30);
    					g.setColor(Color.white);
    					g.drawString("A",271,70);
    					g.drawString("B",310,50);
     
    					if(xCoord >500 && yCoord >150 && xCoord <530 && yCoord<200)	
    								{
    									g.drawImage(background,0,0,this);
    								} 
    		}
     
     
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                dx = -10;
            }
            else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                dx = 10;
            }
            else if (e.getKeyCode() == KeyEvent.VK_UP) {
                dy = -10;
            }
            else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                dy = 10;
            }
            repaint( );
        }
     
     
      public void keyReleased(KeyEvent e) {
     
      		dx = 0;
      		dy = 0;
     
      	} 
     
      public void keyTyped(KeyEvent e)    {}
     
      	public void actionPerformed(ActionEvent e)
    	{
    		System.out.println("Placeholder");
    	}
     
    }

    I'm really desperate for help; my teacher doesn't know how to use the ActionListener and all the chat groups require pay, and I don't have any money. Any help is greatly appreciated, thanks!
    Last edited by VelvetVixxie; May 22nd, 2014 at 12:22 PM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java Applet Help: Keylistener/

    Please edit your post and wrap your code with code tags:
    [code=java]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.

    The key listener requires that the component has the focus. There are some methods for requesting the focus. Sometimes clicking on a component will give it the focus if it is capable of receiving the focus.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    May 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Applet Help: Keylistener/

    Fixed!

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Java Applet Help: Keylistener/

    Quote Originally Posted by VelvetVixxie View Post
    Fixed!
    So you've completed your program, or were you just saying the code tags are fixed?

  5. #5
    Junior Member
    Join Date
    May 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Applet Help: Keylistener/

    Sorry, should have clarified. Only fixed the code tags. I really am stuck with this project, I don't understand why they don't work together

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java Applet Help: Keylistener/

    Which of the focus requesting/enabling methods have you tried?
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Java Applet Help: Keylistener/

    I have to give you a hard time about not commenting your code, because that's what I do. You should comment your code for your own benefit, but if you're going to post it and expect others to help you with it, you should certainly have comments that give some clue about what what each part of the program is supposed to do and how the parts play with each other.

    Why are you using AWT's Applet instead of the more modern and up-to-date JApplet? Or more simply, why are you using AWT instead of Swing?

    Empty catch blocks are pointless. Don't write them. Put something in there.

    What's supposed to be moving? How does varying dx and dy cause that movement? Does dx and dy really vary? I'm confused by the dx *= 0 and dy *= 0 statements.

    A while ( true ) loop is not a good way to animate graphics. The loop captures the CPU's attention and prevents the program from reliably processing input interrupts, updating the display, etc, causing an unsatisfactory user experience. A much better way is to use a Timer.

Similar Threads

  1. KeyListener Problem
    By jibby in forum What's Wrong With My Code?
    Replies: 1
    Last Post: January 16th, 2014, 09:28 PM
  2. KeyListener
    By tim8w in forum AWT / Java Swing
    Replies: 9
    Last Post: January 25th, 2013, 01:40 AM
  3. Help with KeyListener and graphics
    By 123099 in forum AWT / Java Swing
    Replies: 21
    Last Post: July 18th, 2011, 01:26 PM
  4. help with KeyListener
    By all_pro in forum AWT / Java Swing
    Replies: 4
    Last Post: April 14th, 2011, 06:51 AM
  5. Replies: 1
    Last Post: February 10th, 2011, 08:57 AM