【问题标题】:java - get a button to change color when the mouse hovers over itjava - 当鼠标悬停在它上面时,获取一个改变颜色的按钮
【发布时间】:2017-08-23 10:32:43
【问题描述】:

所以我想为一个简单的 java 游戏制作一个菜单,当鼠标悬停在按钮上时,按钮会改变颜色。我没有使用 JButton,而是使用 mouselistener 来检测点击的按钮图片。当您将鼠标悬停在按钮所在的特定区域上时,如何调用 MouseEntered?

public void mouseEntered(MouseEvent e) {
    if(e.getX() < 950 && e.getX() > 350 && e.getY() < 300 && e.getY() > 200){
        menuImage2 = true;
        menuImage1 = false;
    }
}

这就是我目前所拥有的

【问题讨论】:

  • 你不能做 object.setBackground = menuImage2 吗?
  • 也许更多 object.setBackground(menuImage2);这取决于 menuImage2 的定义和类型

标签: java


【解决方案1】:

我就是这样做的。它也播放声音。您只需使用标志。请注意,我使用的是 mouseMoved 而不是 mouseEntered。

鼠标输入类

@Override
public void mouseMoved(MouseEvent e) {
        int x=e.getX();
        int y=e.getY();

        if (x>100&&x<200&&y>150&&y<200) {
            if (mouseInStart==false) {     <---- if this line is true, means mouse entered for first time.
                Sound.playSound(soundEnum.BUTTONHOVER);
            }
            mouseInStart=true;
        } else {
            mouseInStart=false;
        }
}

public boolean mouseInStart() {    <--use this in your update method
    return mouseInStart;
}

在我的其他班级(班级菜单)

public void render(Graphics2D g) {
    ....
    ....
    gradient = new GradientPaint(100, 150, setStartColor(), 200, 200,        Color.gray);
    g.setPaint(gradient);
    g.fill(startButton);

} 

public Color setStartColor() {
    if (mouseInStart) {
        return Color.red;
    } else {
        return Color.white;
    }
}


public void update() {     <--- and this is to keep checking if your mouse is in start.  This is part of the giant game loop.
    mouseInStart=mouseInput.mouseInStart();
    mouseInLoad=mouseInput.mouseInLoad();
    mouseInQuit=mouseInput.mouseInQuit();   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 2018-07-20
    • 2012-08-16
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    相关资源
    最近更新 更多