单击时尝试更改JButton上的图标

Mja*_*ll2 1 java icons swing

我正在尝试制作一个名为Concentration的存储卡匹配游戏.到目前为止,我有3个班级.内存扩展JFrame实现了ActionListener

Board扩展了JPanel实现的ActionListener

Cell扩展了JButton

到目前为止,我已经实现了一个弹出窗口.使用列表添加成对的单元格类型.在我的董事会中随机分配所有单元格.显示所有单元格的背面(img)(有24个单元格,4行6列).现在当我点击我的卡片时,我得到一张白色图片.目前作为一个短期目标,我想要实现的是,当我点击一个按钮时,相应的图像显示在按钮上.

我在类Board中以这种方式实现了ActionPerformed.

 public void actionPerformed(ActionEvent e){

      if(e.getSource() instanceof Cell){

        Cell temp = (Cell)e.getSource();

        temp.setSelected(true);

        if (temp.selected()){

          int row = temp.getRow();
          int column = temp.getColumn();

          board[row][column].setIcon2();


        }
        }}
Run Code Online (Sandbox Code Playgroud)

我的set selected方法仅用于将Cell类中的布尔变量的值更改为true.这是我在类Cell中的setIcon2方法.

public void setIcon2(){
   ImageIcon x = new ImageIcon();


   x = getImageIcon();


    setIcon(x);
  }
Run Code Online (Sandbox Code Playgroud)

这是Cell类中的getImageIcon方法.

private ImageIcon getImageIcon() {
    int temp=0;
    int id;
    if (localSelected) { 

    id = getType();

    String tempId = Integer.toString(id);    

    icons[temp] = new ImageIcon("img-" + tempId + ".jpg");
    temp++;

    return icons[temp];
} else {

     id = IMAGE_NUMBER; 
     String strId = Integer.toString(id);
     icons[id] = new ImageIcon("img-" + strId + ".jpg");

 }

     return icons[id];
    }
Run Code Online (Sandbox Code Playgroud)

没有任何编译错误或警告.getType方法返回与存储在游戏板中的值相关联的整数变量.(Cell类型的2D数组).

试图尽可能清楚地解释我的困境,任何形式的方向都将受到高度赞赏和重视.谢谢Mjall2

mre*_*mre 6

用一个JToggleButton.更具体地说,使用setIconsetSelectedIcon方法.使用这种方法,您将避免重新发明轮子.

示例 -

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

final class JToggleButtonDemo {
    public static final void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }
    private static final void createAndShowGUI(){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout()); // For presentation purposes only.
        final JToggleButton button = new JToggleButton(UIManager.getIcon("OptionPane.informationIcon"));
        button.setSelectedIcon(UIManager.getIcon("OptionPane.errorIcon"));
        frame.add(button);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

此示例中的切换按钮将在未选中时显示信息图标,在选择时将显示错误图标.

  • 另见[相关示例](http://stackoverflow.com/a/7360696/418556). (3认同)