jeudi 13 août 2015

Check if a position is clicked using HashMap

I'm writing a simple program and want to know if an approximate position is clicked. I've got a hashmap with the position as key value and want to display a currently invisible object if the user clicks close enough to the position of the object - not just right at it. The position class just holds an x and a y value.

    HashMap<Position, Place> places = new HashMap<>(); //Assume this is populated

    @Override
    class WhatIsHere extends MouseAdapter {
        public void mouseClicked(MouseEvent me) {
            Place place = places.get(new Position(me.getX(), me.getY()));
            if (place != null) {
                place.setVisible(true);
            } else {
                System.out.println("Nothing there");
            }
        }
    }

This bit of code finds the place if you click right on it though I don't know how to look for, say, me.getX()+-10 and find objects in that range.

Do I need to set four ints holding x-10 and x+10 etc. and just loop through all the positions inbetween? It seems awfully dumb to do it that way.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire