有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java试图在单击JButton时更改图标

我正在尝试制作一款名为“专注”的记忆卡匹配游戏。到目前为止,我有三节课。 内存扩展JFrame实现ActionListener

板扩展JPanel实现ActionListener

单元扩展按钮

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

我以这种方式在课堂上实施了行动

 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();


        }
        }}

My set selected methods仅用于将Cell类中布尔变量的值更改为true。 这是我在类单元格中的setIcon2方法

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


   x = getImageIcon();


    setIcon(x);
  }

下面是类单元格中的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];
    }

没有任何类型的编译错误或警告。getType方法返回一个整数变量,该变量与存储在我的游戏板中的值相关联。(单元格类型的二维数组)

尽可能清楚地解释我的困境,任何方向都会受到高度赞赏和重视。 非常感谢。 Mjall2


共 (1) 个答案

  1. # 1 楼答案

    使用^{}。更具体地说,使用^{}^{}方法。使用这种方法,您将避免重新发明轮子

    示例-

    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);
        }
    }
    

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