繁体   English   中英

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

[英]Trying to change icon on JButton when clicked

我正在尝试制作一个与浓度匹配的存储卡匹配游戏。 到目前为止,我有3节课。 内存扩展JFrame实现ActionListener

开发板扩展JPanel实现ActionListener

单元格扩展JButton

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

我以这种方式在Class 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();


        }
        }}

我设置的选定方法仅用于将Cell类中的布尔变量的值更改为true。 这是我在Cell类中的setIcon2方法。

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


   x = getImageIcon();


    setIcon(x);
  }

这是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];
    }

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

为了尽可能清晰地解释我的困境,任何方向都将受到高度赞赏和重视。 谢谢Mjall2

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

在此示例中,切换按钮将在未选中时显示一个信息图标,在选中时显示一个错误图标。

暂无
暂无

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

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