[英]How to change JButton background colour while it is pressed?
I am trying to override the default background colour of the JButton
while it is pressed; 我试图覆盖按下JButton
时的默认背景色; the background colour must stay as long as the button is still pressed. 只要仍然按下按钮,背景颜色就必须保持不变。
I tried this code: 我尝试了这段代码:
button.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent evt) {
button.setBackground(Color.BLUE); // applied after release!!
System.out.println("pressed"); // applied on pressed - OK.
}
});}
mousePressed
here doesn't achieve my requirement!! mousePressed
在这里没有达到我的要求!
This line is never invoked: button.setBackground(Color.BLUE);
此行永远不会被调用: button.setBackground(Color.BLUE);
. 。 But this line is invoked: System.out.println("pressed");
但这行被调用: System.out.println("pressed");
. 。
However this line button.setBackground(Color.BLUE);
但是这行button.setBackground(Color.BLUE);
is invoked after releasing the button - Not while pressed!!! 释放按钮后调用-不在按下状态!!!
How to achieve my requirement? 如何达到我的要求?
Before your mouse-adapter part of code, make a Color
object as: 在代码的鼠标适配器部分之前,将Color
对象设置为:
final Color col = button.getBackground();
Then, in your mouse adapter, add this method: 然后,在鼠标适配器中,添加以下方法:
public void mouseReleased(MouseEvent e)
{
button.setBackground(col);
}
This makes your total code to : 这使您的总代码为:
final Color col = b.getBackground();
button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e)
{
b.setBackground(Color.BLUE);
}
public void mouseReleased(MouseEvent e)
{
b.setBackground(g);
}
});
So, when you press, the color changes to blue, and then when you release the mouse, it changes back to original. 因此,当您按时,颜色将变为蓝色,然后在释放鼠标时,颜色将恢复为原始颜色。 This works fine on my computer. 这在我的计算机上工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.