简体   繁体   English

对按钮事件进行了混淆

[英]actionPerformed confusion on button events

I am trying to make a game in java, when a button is pressed I want it to change icon to indicate that button has been selected, then when it is clicked again I want to change it to its original icon to show it has been deselected. 我正在尝试用Java制作游戏,当按下按钮时,我希望它更改图标以指示该按钮已被选中,然后再次单击时,我要将其更改为其原始图标,以显示它已被取消选择。

public void actionPerformed(ActionEvent e)
{
    if(e.getSource() == b[7][4] && selected == false)
    {
        b[7][4].setIcon(selected);
        selected = true;
    }

    if(e.getSource() == b[7][4] && selected == true)
    {
        b[7][4].setIcon(king);
        selected = false;           
    }
}

This code currently does as I wish but it runs both at the same time thus changes the icon and then immediately changes it back to the original icon. 该代码当前可以按照我的意愿运行,但是它可以同时运行,因此可以更改图标,然后立即将其更改回原始图标。 How can I make it so one click changes it to selected and then the second click changes it back to a king icon? 我如何才能做到这一点,一键将其更改为selected ,然后再次单击将其更改回为king图标?

Use else before the next if to chain them: if要链接它们,请在下一个之前使用else

public void actionPerformed(ActionEvent e)
{
    if(e.getSource() == b[7][4] && selected == false)
    {
        b[7][4].setIcon(selected);
        selected = true;
    }
    else if(e.getSource() == b[7][4] && selected == true)
    {
        b[7][4].setIcon(king);
        selected = false;           
    }
}

This way the second if clause is only checked if the first condition evaluates to false . 这样,仅当第一个条件的值为false才检查第二个if子句。

一个更简单的解决方案:使用JToggleButton并通过setIcon(...)setSelectedIcon(...)设置其Icon和selectedIcon。

Consider condensing your code into a single setIcon() call: 考虑将代码压缩到单个setIcon()调用中:

public void actionPerformed(ActionEvent e)
{
    if (e.getSource() == b[7][4]) {
        b[7][4].setIcon(selected ? king : defau1t);
        selected = !selected;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM