【问题标题】:How to change JButton background colour while it is pressed?按下时如何更改JButton背景颜色?
【发布时间】:2016-05-08 14:41:17
【问题描述】:

我试图在按下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); 是在释放按钮后调用的 - 不是在按下时!!!

如何达到我的要求?

【问题讨论】:

  • 尝试将 contentFilled 属性设置为 false 并将 opaque 设置为 true
  • 也许这有助于link

标签: java swing colors background jbutton


【解决方案1】:

在您的鼠标适配器部分代码之前,将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);
    }
});

因此,当您按下鼠标时,颜色变为蓝色,然后当您松开鼠标时,它又变回原来的颜色。这在我的电脑上运行良好。

【讨论】:

    猜你喜欢
    • 2011-01-28
    • 2014-05-11
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-15
    相关资源
    最近更新 更多