pMpC
pMpC

Reputation: 257

Associate an image to a mouseclick

What's the best way to associate an image that's in a JPanel to a mouseclick in order to do something? I mean, is there any function in API that can do that? If not, what's the best solution?

By the way, for you who may be wondering why I'm asking for help in this matter is because I'm doing a Sudoku game, and my code already generates randomly all the numbers in the matrix, checks if the solution is correct, the only thing that's not done yet is the interface(the user choosing a square in order to select a number in there). Thank you.

Upvotes: 0

Views: 71

Answers (3)

kirbyquerby
kirbyquerby

Reputation: 725

Well, you could do something like this to determine if a mouse click is inside a certain region(the image's bounds):

public boolean isIn(int x,int y,int width,int height,int thex,int they){
    boolean b=
            thex>=x
            &&thex<=(x+width)
            &&they>=y&&
            they<=(y+height);
    //b=true;
    return b;
}

where: x is the x-coordinate of the top left corner y is the y-coordinate of the top left corner width is the width of the image height is the height of the image

and x and y are the x and y-coordinates of the mouse click.

After determining which square the mouse's click is inside, you can then make a pop up to get the number to place.

Upvotes: 0

Dimitris Sfounis
Dimitris Sfounis

Reputation: 2500

Would a clickable image help you?

ImageView clickableImg = new ImageView(new Image(getClass().getResourceAsStream("graphics/image.png")));
Tooltip image_tooltip = new Tooltip("Maybe add a tooltip to it, as well");
Tooltip.install(clickableImg, image_tooltip);
//Turn the cursor into a hand when hovering over it, too
about.setStyle("-fx-cursor: hand;");
about.setOnMouseClicked(new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEvent mouseEvent) {
        System.out.println("The image was clicked!");
    }
});

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347184

The "best" way? Use a JLabel

A different way, use a custom JPanel which is responsible for rendering a single image and paint it via the paintComponent method of the panel

A "interesting" way, use a custom JPanel to paint all the images, maintain in some kind of List where each image is associated with a Rectangle that describes the location and size of the image. When the panel is clicked, loop through the Rectangle List and use the contains method of the Rectangle to determine if the mouse event occurred within it, use the index of the Rectangle to loop up the image (or use some kind of Map to maintain a link between the two)

Which you do depends on how much work you want to do and what functionality you intend to implement.

Take a close look at:

Upvotes: 2

Related Questions