set and disable icons of JToggleButton

后端 未结 2 2125
甜味超标
甜味超标 2020-11-27 22:54

hi there i am trying to make a matching memory game which i use JToggleButton. the main thing is when i press to button it must show a picture and i must find the other same

2条回答
  •  感动是毒
    2020-11-27 23:42

    One approach is to do the following:

    • Use the selected state to indicate whether to show or hide the Icon.
    • Use the enabled state to indicate that a pair has been matched.

    Code outline:

    /** Handle ItemEvents. */
    @Override
    public void itemStateChanged(ItemEvent e) {
        GameButton gb = (GameButton) e.getItem();
        gb.setState();
    }
    
    /** Remove a and b from play. */
    private void retirePair(GameButton a, GameButton b) {
        a.setSelected(true);
        a.setEnabled(false);
        b.setSelected(true);
        b.setEnabled(false);
    }
    
    class GameButton extends JToggleButton {
        ...
        public void setState() {
            if (this.isSelected() || !this.isEnabled()) {
                this.setIcon(icon);
            } else {
                this.setIcon(hidden);
            }
        }
    }
    

提交回复
热议问题