[英]How to change JButton background colour while it is pressed?
我试图覆盖按下JButton
时的默认背景色; 只要仍然按下按钮,背景颜色就必须保持不变。
我尝试了这段代码:
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
在这里没有达到我的要求!
此行永远不会被调用: button.setBackground(Color.BLUE);
。 但这行被调用: System.out.println("pressed");
。
但是这行button.setBackground(Color.BLUE);
释放按钮后调用-不在按下状态!!!
如何达到我的要求?
在代码的鼠标适配器部分之前,将Color
对象设置为:
final Color col = button.getBackground();
然后,在鼠标适配器中,添加以下方法:
public void mouseReleased(MouseEvent e)
{
button.setBackground(col);
}
这使您的总代码为:
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);
}
});
因此,当您按时,颜色将变为蓝色,然后在释放鼠标时,颜色将恢复为原始颜色。 这在我的计算机上工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.