Results 1 to 13 of 13
  1. #1
    js91723 is offline Member
    Join Date
    May 2010
    Posts
    7
    Rep Power
    0

    Default Problem with mouseListener

    Java Code:
    I've got this Jpanel:
    
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class A3JPanel extends JPanel implements ActionListener, KeyListener, MouseListener {
    	
    	private Rectangle boundary;
    	private Ant[] ants;
    	private Player player;
    	private Timer t;
    	private GameOver over;
    	
    	public A3JPanel() {
    		boundary = new Rectangle(5, 5, 490, 490);
    		ants = new Ant[30];
    		for (int i = 0; i < ants.length; i++) {
    			ants[i] = new Ant();
    		}
    		
    		player = new Player(250, 300);	
    		addKeyListener(this);
    		addMouseListener(this);
    		t = new Timer(20, this);
    	}
    	
    	public void actionPerformed(ActionEvent e) {
    		for (int i = 0; i < ants.length; i++) {
    			ants[i].move();
    		}
    		player.move();
    		
    		repaint();
    	}
    
    	public void keyPressed(KeyEvent e) {
    		
    		t.start();
    		if (e.getKeyCode() == KeyEvent.VK_SPACE) {
    			for (int i = 0; i < ants.length; i++) {
    				ants[i].move();
    			}
    		}
    		
    		if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    			player.turnLeft();
    		}
    		if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    			player.turnRight();
    		}
    		if (e.getKeyCode() == KeyEvent.VK_UP) {
    			player.turnUp();
    		}
    		if (e.getKeyCode() == KeyEvent.VK_DOWN) {
    			player.turnDown();
    		}
    		repaint();
    	}
    	
    	[COLOR="yellow"]public void mousePressed(MouseEvent e) {
    		
    		Point p = e.getPoint();
    		
    		for (int i=0; i < ants.length; i++){
    			if(ants[i].getAntSize().contains(p)){
    				ants[i].setX();
    			}
    		}[/COLOR]
    
    		repaint();
    	}
    	
    	public void paintComponent(Graphics g) {
    		super.paintComponent(g);
    		
    		for (int i = 0; i < ants.length; i++) {
    			ants[i].draw(g);
    		}
    		g.drawRect(boundary.x, boundary.y, boundary.width, boundary.height);
    		player.draw(g);
    		
    		for (int i = 0; i < ants.length; i++) {
    			if (ants[i].getAntSize().intersects(player.getPlayerSize())) {
    				over.draw(g);
    			}
    		}
    	}
    	
    	public void keyReleased(KeyEvent e) {}
    	public void keyTyped(KeyEvent e) {}
    	public void mouseReleased(MouseEvent e) {}
    	public void mouseClicked(MouseEvent e) {}
    	public void mouseEntered(MouseEvent e) {}
    	public void mouseExited(MouseEvent e) {}
    }
    and Ant class of :

    Java Code:
    import java.awt.*;
    
    public class Ant {
    
    	public int x, y, width, height;
    	public int xSpeed, ySpeed;
    	public Color antColor;
    	
    	public Ant () {
    		x = 200;
    		y = 300;
    		width  = 15;
    		height = 30;
    		xSpeed = (int) (Math.random() * 5) - 3;
    		ySpeed = (int) (Math.random() * 5) - 3;
    		int red = (int)(Math.random() * 100);
    		int green = (int)(Math.random() * 100);
    		int blue = (int)(Math.random() * 100);
    		antColor = new Color(red, green, blue);
    	}
    	
    
    	
    	public void move() {
    		x += xSpeed;
    		y += ySpeed;
    		
    		if (x <= 15) {
    			xSpeed = -1 * xSpeed;
    		} else if (x >= 490) {
    			xSpeed = -1 * xSpeed;
    		}
    		if (y <= 105) {
    			ySpeed = -1 * ySpeed;
    		} else if (y >= 565) {
    			ySpeed = -1 * ySpeed;
    		}
    	}
    	
    	[COLOR="Yellow"]public void setX() {
    		x = x + 1000;
    	}[/COLOR]
    	
    	public Rectangle getAntSize () {
    		return new Rectangle (x, y, width, height);
    	}
    	
    	public void draw(Graphics g) {
    		g.setColor(antColor);
    		g.fillOval(x-10, y-100, width, height);
    		g.setColor(Color.black);
    		g.drawOval(x-10, y-100, width, height);
    	}
    }
    I returned Ant class as Rectangle so I can use .contain but ants do not disappear even though it compiles perfectly. Do I have to change GetAntSize() or is anything else wrong?
    Last edited by js91723; 05-31-2010 at 05:29 PM.

  2. #2
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default

    Your code is unreadable, repost with code tags.

    EDIT: OP reposted in a new thread.
    Last edited by PhHein; 05-31-2010 at 06:09 PM.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

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

    Default

    Quote Originally Posted by js91723 View Post
    I returned Ant class as Rectangle so I can use .contain but ants do not disappear even though it compiles perfectly. Do I have to change GetAntSize() or is anything else wrong?
    I can read the code OK, except for the yellow parts but have to wonder just what the problem is. Assume that you're explaining this to someone who has no idea about what your program is or does. In short, you may wish to post more of the pertinent details.

    Luck!

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

    Default

    One problem I'm seeing with your code is that you're adding a KeyListener to a JPanel, but in order for this to work, the JPanel must be focusable (by default, it's not), and it must have the focus. The quick and dirty solution is to fix these things which can be done by changing the A3JPanel to allow it to receive focus and then request the focus:

    Java Code:
      public A3JPanel() {
        boundary = new Rectangle(5, 5, 490, 490);
        ants = new Ant[30];
        for (int i = 0; i < ants.length; i++) {
          ants[i] = new Ant();
        }
    
        player = new Player(250, 300);
        addKeyListener(this);
        addMouseListener(this);
        t = new Timer(20, this);
    
        // !! added  ****
        setFocusable(true); 
        requestFocusInWindow(); 
      }
    A better solution would be to not use a KeyListener but instead to use key bindings. For instructions on how to use these, please check out the Sun Swing tutorials key binding section which you can find here: How To Use Key Bindings

    If you have other specific problems, again please post back with the details.

    Again, much luck!

  5. #5
    js91723 is offline Member
    Join Date
    May 2010
    Posts
    7
    Rep Power
    0

    Default

    I added those in but it still doesn't work. However sometimes when I click random spaces, some of the ants disappear

    Is it because my player class is crashing with the ants class?

    Here is my player class:
    Java Code:
    public class Player {
    
    	private final int UP = 0;
    	private final int DOWN = 1;
    	private final int LEFT = 2;
    	private final int RIGHT = 3;
    	
    	private final int distanceToMove = 3;
    	
    	public int x;
    	public int y;
    	public int width;
    	public int height;
    	private int size;
    	private int speed;
    	private Point pos;
    	
    	private int direction;
    	private Color playerColour;
    
    	public Player(int x, int y) {
    		playerColour = new Color(250, 250, 250);
    		pos = new Point(x, y);
    		direction = LEFT;
    		width = 20;
    		height = 20;
    	}
    	
    	public Rectangle getPlayerSize() {
    		return new Rectangle(x, y, width, height);
    	}
    
    	public void draw(Graphics g) {
    
    		g.setColor(playerColour);
    		g.fillRect(pos.x, pos.y, width, height);
    		g.setColor(Color.BLACK);
    		g.drawRect(pos.x, pos.y, width, height);
    
    	}
    	
    	public void move() {
    		if (direction == LEFT) {
    			pos.x -= distanceToMove;
    		} else if (direction == RIGHT) {
    			pos.x += distanceToMove;
    		} else if (direction == UP) {
    			pos.y -= distanceToMove;
    		} else {
    			pos.y += distanceToMove;
    		}
    		if (pos.x <= 5) {
    			pos.x = 475;
    		} else if (pos.x >= 475) {
    			pos.x = 5;
    		}
    		if (pos.y <= 5) {
    			pos.y = 475;
    		} else if (pos.y >= 475) {
    			pos.y = 5;
    		}
    	}
    
    	public void turnLeft() {
    		direction = LEFT;
    	}
    	
    	public void turnRight() {
    		direction = RIGHT;
    	}
    	
    	public void turnUp() {
    		direction = UP;
    	}
    	
    	public void turnDown() {
    		direction = DOWN;
    	}
    }
    and sorry for reposting the same problem, thanks.

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

    Default

    Quote Originally Posted by js91723 View Post
    I added those in but it still doesn't work. However sometimes when I click random spaces, some of the ants disappear

    Is it because my player class is crashing with the ants class?
    ....
    You're still leaving out much detail that prevents me at least from understanding your problem. Again, I strongly suggest that you write out your question with the assumptions that we know absolutely nothing about your code or problem. Assume that we are idiots and that you have to explain this to us slowly and carefully. Please read the link in my signature called "How to Ask Smart Questions". It provides many helpful suggestions on how to ask a question so that it can be answered.

  7. #7
    js91723 is offline Member
    Join Date
    May 2010
    Posts
    7
    Rep Power
    0

    Default

    Ok, I am trying to make a game that when I click the circles which are in the class of array Ant[] ants, they disappear. Also when they intersect with the Rectangle called player, the game ends. Obviously ants and player classes are not the rectangle class so I had to create rectangle class of getAntSize and getPlayerSize to use .contain and .intersect method to perform these action but it seems like getPlayerSize and getAntSize method returns nothing. I think the problem is either getPlayerSize, getAntSize method or setX method in the Ant class which I created to move x value of the ants. What do need to change to make the ants disappear and make the game switch to the GameOverScreen class that I created?

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

    Default

    OK, thanks for explaining that. I see one problem here:

    Java Code:
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
    
        for (int i = 0; i < ants.length; i++) {
          ants[i].draw(g);
        }
        g.drawRect(boundary.x, boundary.y, boundary.width, boundary.height);
        player.draw(g);
    
        for (int i = 0; i < ants.length; i++) {
          if (ants[i].getAntSize().intersects(player.getPlayerSize())) {
            over.draw(g);
          }
        }
      }
    in that in this last for loop, you're calling program logic code from within the paintComponent method. This should probably be inside your the Timer's actionPerformed method instead, and it should change the program state so that the game is over, stopping the timer and such.

    Another problem is in your Ant class. Why are you using x and y offsets of -10 and -100 when drawing the Ants?

    Java Code:
      public void draw(Graphics g) {
        g.setColor(antColor);
        g.fillOval(x - 10, y - 100, width, height);
        g.setColor(Color.black);
        g.drawOval(x - 10, y - 100, width, height);
      }
    You understand that the rectangle returned does not have these offsets and so to click on an Ant, the user has to click below and to the left of the Ant.

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

    Default

    Also, to simplify things, you may consider giving Ant and Player a contains(Point p) method, and perhaps give Player an intersects(Ant a) method, or some-such.

  10. #10
    js91723 is offline Member
    Join Date
    May 2010
    Posts
    7
    Rep Power
    0

    Default

    thank you so much, I've made the ants to disappear. I just got one last question, you said the last loop has to be in the actionPerformed method but shouldn't that be in the paintComponent because it's drawing the GameOver screen? or do I need to create another class such as drawGameOver() and use it as drawGameOver.draw() in the paintComponent?, thanks.

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

    Default

    It involves program logic so it should not be in paintComponent. The Timer should likely detect the collision and have this change the class's state (a boolean field perhaps) and this can be used by paintComponent perhaps.

  12. #12
    js91723 is offline Member
    Join Date
    May 2010
    Posts
    7
    Rep Power
    0

    Default

    This is what my JPanel looks like now:
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class A3JPanel extends JPanel implements ActionListener, KeyListener, MouseListener {
    	
    	private Rectangle boundary;
    	private Ant[] ants;
    	private Player player;
    	private Timer t;
    	private GameOver over;
    	private YouWin win;
    	private TitleScreen title;
    	
    	public A3JPanel() {
    		boundary = new Rectangle(5, 5, 490, 490);
    		ants = new Ant[30];
    		for (int i = 0; i < ants.length; i++) {
    			ants[i] = new Ant();
    		}
    		
    		player = new Player(250, 300);	
    		addKeyListener(this);
    		addMouseListener(this);
    		t = new Timer(20, this);
    		over = new GameOver();
    		win = new YouWin();
    		title = new TitleScreen();
    		setFocusable(true);
    		requestFocusInWindow();
    	}
    	
    	public boolean drawGameOver(boolean o) {
    		for (int i = 0; i < ants.length; i++) {
    			ants[i].getAntSize().intersects(player.getPlayerSize());
    		}
    		return o = false;
    	}
    	
    	public boolean drawYouWin(boolean w) {
    		for (int i = 0; i < ants.length; i++) {
    			boundary.contains(ants[i].getAntSize());
    		}
    		return w = true;
    	}
    	
    	public boolean drawTitle(boolean l) {
    		return l = true;
    	}
    	
    	public void actionPerformed(ActionEvent e) {
    		for (int i = 0; i < ants.length; i++) {
    			ants[i].move();
    		}
    		player.move();
    		repaint();
    	}
    
    	public void keyPressed(KeyEvent e) {
    		
    		t.start();
    		
    		if (e.getKeyCode() == KeyEvent.VK_ENTER) {
    			drawTitle(false);
    		}
    		
    		if (e.getKeyCode() == KeyEvent.VK_SPACE) {
    			for (int i = 0; i < ants.length; i++) {
    				ants[i].move();
    			}
    		}
    		
    		if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    			player.turnLeft();
    		}
    		if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    			player.turnRight();
    		}
    		if (e.getKeyCode() == KeyEvent.VK_UP) {
    			player.turnUp();
    		}
    		if (e.getKeyCode() == KeyEvent.VK_DOWN) {
    			player.turnDown();
    		}
    		repaint();
    	}
    	
    	public void mousePressed(MouseEvent e) {
    		
    		Point p = e.getPoint();
    		
    		for (int i=0; i < ants.length; i++){
    			if(ants[i].getAntSize().contains(p)){
    				ants[i].setX();
    			}
    		}
    
    		repaint();
    	}
    	
    	public void paintComponent(Graphics g) {
    		super.paintComponent(g);
    		
    		if (drawTitle(true)) {
    			title.draw(g);
    		}
    		
    		for (int i = 0; i < ants.length; i++) {
    			ants[i].draw(g);
    		}
    		g.drawRect(boundary.x, boundary.y, boundary.width, boundary.height);
    		player.draw(g);
    		
    		for (int i = 0; i < ants.length; i++) {
    			if (drawGameOver(true)) {
    				over.draw(g);
    			}
    		}
    		
    		for (int i = 0; i < ants.length; i++) {
    			if (drawYouWin(false)) {
    				win.draw(g);
    			}
    		}
    	}
    	
    	public void keyReleased(KeyEvent e) {}
    	public void keyTyped(KeyEvent e) {}
    	public void mouseReleased(MouseEvent e) {}
    	public void mouseClicked(MouseEvent e) {}
    	public void mouseEntered(MouseEvent e) {}
    	public void mouseExited(MouseEvent e) {}
    }
    when I run the programme, it prints out all title, win and lose class, do I have to change the value of boolean or move everything to the actionPerformed?
    Last edited by js91723; 05-31-2010 at 08:40 PM.

  13. #13
    js91723 is offline Member
    Join Date
    May 2010
    Posts
    7
    Rep Power
    0

    Default

    In drawYouWin method I tried to make that if all the ants are inside the boundary(which is the huge square around the frame) the value is true and if they are all outside, it returns false
    when I change the method like this:
    Java Code:
    public boolean drawYouWin(boolean w) {
    		for (int i = 0; i < ants.length; i++) {
    			if (boundary.contains(ants[i].getAntSize())) {
    				w = true;
    			} else {
    				w = false;
    		}
    		return w = true;
    	}
    it gives me 48 differnet error when I compile
    Last edited by js91723; 05-31-2010 at 09:03 PM.

Similar Threads

  1. can't get x and y from mouselistener
    By j2me64 in forum Java 2D
    Replies: 3
    Last Post: 04-24-2010, 05:57 PM
  2. MouseListener & GUI
    By Suurisa in forum New To Java
    Replies: 2
    Last Post: 10-27-2009, 01:52 AM
  3. Mouselistener questions
    By jigglywiggly in forum New To Java
    Replies: 0
    Last Post: 05-07-2009, 10:59 PM
  4. i need help for MouseListener
    By sfaxianovic in forum New To Java
    Replies: 2
    Last Post: 08-21-2008, 04:30 AM
  5. MouseListener
    By Aswq in forum New To Java
    Replies: 12
    Last Post: 07-18-2008, 09:10 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
  •