Results 1 to 14 of 14
  1. #1
    Bagzli is offline Member
    Join Date
    Feb 2011
    Posts
    63
    Rep Power
    0

    Default How to compare Range of numbers?

    For example if I am getting position of my mouse cursor from the screen
    Java Code:
    e.getX()
    and I need to check if that location is anywhere from 50 to 100

    so if i were checking just 50 i'd do this:
    Java Code:
    addMouseMotionListener(new MouseAdapter() 
            {
                public void mouseDragged(MouseEvent e) 
                {
                	if(e.getX() == 50)
                	{
                		//Some Code
                	}
                }
            });
    How would i check this for all numbers between 50 and 100, i can only think of looping but that somehow seems like a bad idea?

    Basically I have a square on the screen and i want to check if my mouse is anywhere on the surface of that square.

    this is my attempt with loop, square only moves down and to the right with this code, it wont go left or up
    Java Code:
    addMouseMotionListener(new MouseAdapter() 
            {
                public void mouseDragged(MouseEvent e) 
                {
                	for(int i=squareX; i<squareX + squareW; i++)
    	            	if(e.getX() == i)
    	            	{
    	            		moveSquare(e.getX(),e.getY());
    	            	}
                }
            });
    Even if this worked i'd need a second loop that would check Y Position and that is now getting way too messy...
    Last edited by Bagzli; 07-02-2011 at 09:32 PM.

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

    Default

    Just use an if block with a slightly more complex boolean condition:

    Java Code:
    if (myVar >= minValue && myVar < maxValue) { // or > minValue... or <= maxValue ...
       // do something
    }
    And actually you'll need a slightly more complex boolean condition than that since you'll want to do the same double checks for the x value and the y value.

  3. #3
    Bagzli is offline Member
    Join Date
    Feb 2011
    Posts
    63
    Rep Power
    0

    Default

    Here it is but i got a major problem...
    Java Code:
    public void mouseDragged(MouseEvent e) 
                {
                	if((e.getX() >= squareX && e.getX() <= squareX + squareW) && (e.getY() >= squareY && e.getY() <= squareY + squareH))
                	{
                		moveSquare(e.getX(),e.getY());
                	}
    	            
                }
    This will only move the box while mouse is inside it. The box is drawn from x and y cordinate and it goes by length and height. So lets say l = 20, w = 20, x = 50, y = 50.

    Box will start at 50, 50 and will end at 70, 70. So while my mouse is in between 50 -70 x and 50 - 70 y it will move it. That is moving down and to the right and it works perfectly. If I try to move my mouse left or up it will exit the box and the box will not get moved, is there a way to change this? So instead of box starting at 50, 50 to make the center of the box 50, 50 so that way when i move up and left i am still in the box and the box moves.

    Hope I was not too confusing >.<

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

    Default

    You need to think logically: when is it important that the mouse click inside of the box? When the mouse is being dragged or when the mouse clicks (or better mousePressed)? So which method of the MouseListener (or better, MouseAdapter) should you be checking for this? mouseDragged? or mousePressed?

  5. #5
    Bagzli is offline Member
    Join Date
    Feb 2011
    Posts
    63
    Rep Power
    0

    Default

    dragged because he is dragging the box to new location

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

    Default

    Quote Originally Posted by Bagzli View Post
    dragged because he is dragging the box to new location
    No, in this situation it is mousePressed. You've said it yourself, the user must press the mouse button in the box and then drag the mouse with the box to a new location. The only time when it is important that the mouse be within the initial x and y confines of the box is on the initial press. Later when the user is dragging the mouse, the mouse is often in a completely different location. So the MouseAdapter must override mousePressed and be activated if the mouse press is within the box and de-activated on mouseReleased. If the mouse is dragging and the MouseAdapter is activated, then the box location must be changed based on the mouse's location.

    So to reiterate what is important initially is that you only activate the MouseAdapater when the mouse is pressed within the box. Later on when the mouse is dragged, you don't care if the mouse is within the initial confines of the box.

    Also you will need to add your MouseAdapter as both a MouseListener and a MouseMotionListener to your dragging JPanel.

    For example, please have a look at the code in this thread: questions-about-events-differents-layers

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

    Default

    Actually the example linked to above is probably too complex. This is more along the lines of what I meant:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class SquareMove extends JPanel {
       private static final Stroke STROKE = new BasicStroke(5);
       private static final Color SQUARE_COLOR = Color.red;
       private static final Color SQR_MOVE_COLOR = new Color(175, 175, 255);
       private static final int PNL_WIDTH = 600;
       private static final int PNL_HEIGHT = 450;
       private Rectangle rect = new Rectangle(20, 20, 100, 100);
       private Color squareColor = SQUARE_COLOR;
    
       public SquareMove() {
          MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
          addMouseListener(myMouseAdapter);
          addMouseMotionListener(myMouseAdapter);
       }
    
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D) g;
          g2.setStroke(STROKE);
          g2.setColor(squareColor);
          g2.drawRect(rect.x, rect.y, rect.width, rect.height);
       }
    
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PNL_WIDTH, PNL_HEIGHT);
       }
    
       private class MyMouseAdapter extends MouseAdapter {
          private boolean active = false;
          private Point delta = null;
    
          @Override
          public void mousePressed(MouseEvent e) {
             // could use if (e.getX() >= rect.x && e.getX() <= rect.x + rect.width && ...
             // but it's easier just to see if mouse is inside of the Rectangle
             // via the Rectangle's contains method
             if (rect.contains(e.getX(), e.getY())) {
                active = true;
                squareColor = SQR_MOVE_COLOR;
                delta = new Point(e.getX() - rect.x, e.getY() - rect.y);
                repaint();
             }
          }
    
          @Override
          public void mouseReleased(MouseEvent e) {
             active = false;
             squareColor = SQUARE_COLOR;
             repaint();
          }
    
          @Override
          public void mouseDragged(MouseEvent e) {
             if (active) {
                int x = e.getX() - delta.x;
                int y = e.getY() - delta.y;
    
                rect.setLocation(x, y);
                repaint();
             }
          }
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("SquareMove");
          frame.getContentPane().add(new SquareMove());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }

  8. #8
    Bagzli is offline Member
    Join Date
    Feb 2011
    Posts
    63
    Rep Power
    0

    Default

    ok I'll take a look at this code a bit later, been cleaning up house all day and somewhat tired, but thanks a lot I'll definitively go over it later and let you know how I did.

  9. #9
    Bagzli is offline Member
    Join Date
    Feb 2011
    Posts
    63
    Rep Power
    0

    Default

    Ugh, my level of knowledge is nowhere near this type of programming to be honest. I have been doing my best to try and keep up with your style of code but I honestly don't even know what a runable is. Is there any chance you could comment out that code telling me what each part is doing so I could try and understand it a bit more clearer?

    See in school last thing i learned was maps and object writing, i only have 2 semesters of Java programming and what I am trying here is way ahead of me. I am doing this though because I want to learn more and this program is for a friend. So please stay patient with me :)

  10. #10
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,457
    Rep Power
    20

    Default

    I honestly don't even know what a runable is.
    Bookmark this page: Java Platform SE 6

    db

  11. #11
    Iron Lion is offline Senior Member
    Join Date
    Nov 2010
    Posts
    210
    Rep Power
    5

    Default

    You might also want to look up "anonymous inner class". The Runnable that's created in the main() method is an example of this.

  12. #12
    Dark's Avatar
    Dark is offline Senior Member
    Join Date
    Apr 2011
    Location
    Camp Lejuene, North Carolina
    Posts
    643
    Rep Power
    4

    Default

    If you attempting to complete tasks that are beyond you then I suggest working your way up there. If you can, get a Java book and read through it. Different books cover different aspects and honestly, you will always learn something new. If not try using the Java Tutorials, they are free and go pretty in depth.

    The code Fubarable posted, not the link, doesn't even contain runnable. As long as you know post good questions and you prove to us that you are trying then people will continue helping you.
    • Use [code][/code] tags when posting code. That way people don't want to stab their eyes out when trying to help you.
    • +Rep people for helpful posts.

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

    Default

    Quote Originally Posted by Dark View Post
    The code Fubarable posted, not the link, doesn't even contain runnable. As long as you know post good questions and you prove to us that you are trying then people will continue helping you.
    Actually it does:
    Java Code:
       private static void createAndShowUI() {
          JFrame frame = new JFrame("SquareMove");
          frame.getContentPane().add(new SquareMove());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater([b][color="red"]new Runnable()[/color][/b] {
             public void run() {
                createAndShowUI();
             }
          });
       }
    To the OP: by creating a Runnable, starting the GUI in the Runnable, and adding it to the event queue, you make sure that the program is called on the Swing thread. This is as per the recommendations in the Oracle Swing tutorials. Please have a look here: Concurrency in Swing

  14. #14
    Dark's Avatar
    Dark is offline Senior Member
    Join Date
    Apr 2011
    Location
    Camp Lejuene, North Carolina
    Posts
    643
    Rep Power
    4

    Default

    My apologies, I only skimmed the code and I didn't see it.
    • Use [code][/code] tags when posting code. That way people don't want to stab their eyes out when trying to help you.
    • +Rep people for helpful posts.

Similar Threads

  1. Replies: 11
    Last Post: 01-14-2011, 07:36 PM
  2. Replies: 8
    Last Post: 04-19-2009, 06:50 PM
  3. Compare two lists of number - what numbers arent there
    By Bishop609 in forum New To Java
    Replies: 5
    Last Post: 02-18-2009, 02:22 AM
  4. printing two smallest numbers from a series of numbers
    By trofyscarz in forum New To Java
    Replies: 2
    Last Post: 10-15-2008, 12:46 AM
  5. Compare 5 numbers
    By Snowboardmylife in forum New To Java
    Replies: 5
    Last Post: 04-15-2008, 08:04 PM

Posting Permissions

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