通过鼠标监听器更改Jbutton的图标

Amr*_*een 4 java swing jbutton mouselistener

我正在做一个棋盘游戏项目,我正在用Jbuttons代表细胞.我为所有按钮制作了mouseLitener.我的问题是如何在单击时更改Jbutton的图标?

mKo*_*bel 7

我正在做一个棋盘游戏项目,我正在用Jbuttons代表细胞.

  • 使用JToggleButton进行基于按钮数组和鼠标事件的游戏,而不是JButton

  • 使用ButtonModel而不是任何XxxListener

  • JButtonJToggleButton直接在API中实现了这些方法

.

setIcon(Icon i);
setRolloverIcon(Icon i);
setPressedIcon(Icon i);
setDisabledIcon(Icon i);
Run Code Online (Sandbox Code Playgroud)


Sim*_*iak 5

yourButton.addActionListener(new ActionListener() {
@Override
    public void actionPerformed(ActionEvent e) {
        yourButton.setIcon(new ImageIcon("yourImage"));
    }
});
Run Code Online (Sandbox Code Playgroud)

单击JButton时会调用ActionListener.这种方式最常用.