如何通过MouseEvent创建一个布尔局部变量?

时间:2015-06-08 01:52:57

标签: java mouseevent boolean-expression

我刚刚开始学习Java,而我正在尝试正确初始化来自MouseEvent的4个变量。

我理解如何检索点击位置,但我不知道如何创建一个布尔局部变量leftClicked,如果在事件期间单击鼠标左键,则将其初始化为true。

我尝试使用if语句来设置一个变量,如果getButton()返回BUTTON1,则该变量将为true,但是这并不适用于其余的代码,我不是应该改变。

特别是,由于" leftClicked"它不会编译。在代码的第二部分的if语句中。有人可以指出我在语法和必要元素方面的正确方向吗?

我意识到这一定是一个非常简单的问题,但我无法理解它。非常感谢你提前!

/**
 * 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 个答案:

答案 0 :(得分:1)

SwingUtilities.isLeftMouseButton(MouseEvent anEvent)

此方法返回您想要的内容。

答案 1 :(得分:1)

你可以这样做:

boolean leftClicked = e.getButton() == MouseEvent.BUTTON1;
boolean rightClicked = e.getButton() == MouseEvent.BUTTON2;