How to create a boolean local variable as a result of MouseEvent?

354 views Asked by At

I'm just starting to learn Java and I'm trying to correctly initialise 4 variables that come from a MouseEvent.

I understand how to retrieve a click position, but I don't know how to create a boolean local variable, leftClicked, and initialize it to true if the left mouse button is clicked during the event.

I've tried using if statements to set a variable that would result as true if getButton() returned BUTTON1, however this doesn't work with the rest of the code, which I'm not supposed to alter.

In particular, it won't compile due to the "leftClicked" in the if statement in the second part of the code. Could someone please point me in the correct direction in terms of syntax and necessary elements?

I realise it must be a very simple question but I can't get my head around it. Thank you very much in advance!

/**
 * Processes mouse clicks while the program is in browse mode. 
 * This method is called only after a mouse click is received while in browse mode. 
 * If a left mouse button click hits a photo, it enlarges the photo to a regular format. 
 * If a right mouse button click hits a photo, it shrinks the photo to a thumbnail format.
 **/

private void doBrowsePhoto(MouseEvent e) {

    // please write your code after this line
    int x=e.getX();
    int y=e.getY();

    // boolean?

    // code to be executed after the initialization of the variables x, y, leftClicked and rightClicked
    ColorImage[] photos = model.getPhotos();
    ColorImage photo;
    double scale1, scale2, scaleMean;
    for (int i=0; i<photos.length; i++) {
        photo=photos[i];
        if (isInsideImage(x, y, photo)) {
            scale1=findThumbnailScale(photo);
            scale2=findRegularScale(photo);
            if (rightClicked) {
                photo.setScale(scale1);
            } else if (leftClicked){
                photo.setScale(scale2);
            }
            break;
        }
    }
}
2

There are 2 answers

0
Sergey Kalinichenko On BEST ANSWER

You can do it like this:

boolean leftClicked = e.getButton() == MouseEvent.BUTTON1;
boolean rightClicked = e.getButton() == MouseEvent.BUTTON2;
0
Michael On
SwingUtilities.isLeftMouseButton(MouseEvent anEvent)

This method returns what you want.