java中的ImageIcon

java中的ImageIcon,java,swing,jlabel,imageicon,Java,Swing,Jlabel,Imageicon,我正在做一个匹配照片的游戏,我想我可以通过知道contenner标签的名称来重置imageIcon,然后在ismatch方法中ismatch返回false时重置标签图标 在每个标签中写入以下代码,重置仅在第二个标签中起作用。。我该怎么办 public ImageIcon firstChoice; public ImageIcon SecoundChoice; public boolean isSelected = false; public boolean isMatc

我正在做一个匹配照片的游戏,我想我可以通过知道contenner标签的名称来重置imageIcon,然后在ismatch方法中ismatch返回false时重置标签图标

在每个标签中写入以下代码,重置仅在第二个标签中起作用。。我该怎么办

public ImageIcon firstChoice;
    public ImageIcon SecoundChoice;
    public boolean isSelected = false;

    public boolean isMatch = true;

    public boolean ismatch(ImageIcon firstChoice, ImageIcon secoundChoce) {

        if (firstChoice.getImage() == secoundChoce.getImage()) {
            JOptionPane.showMessageDialog(null, " wowo you got it ^^");
            isMatch = true;
        } else {
            JOptionPane.showMessageDialog(null, "  notmatced");
            isMatch = false;


        }
        return isMatch;
    }


// label Mouse Clicked

private void label1MouseClicked(java.awt.event.MouseEvent evt) { 

    label1.setIcon(new ImageIcon("G:/Games/icons/File Server Asia.png"));

            if (isSelected == true) {
                ImageIcon icon1 = (ImageIcon) label1.getIcon();
                firstChoice = icon1;
                if (SecoundChoice != null && firstChoice != null) {
                }
                boolean match = ismatch(firstChoice, SecoundChoice);
                if (isMatch == false) {
                    label1.setIcon(null);
                    firstChoice = SecoundChoice = null;

                }

            } else {
                if (SecoundChoice == null) {

                    ImageIcon icon1 = (ImageIcon) label1.getIcon();
                    SecoundChoice = icon1;
                    isSelected = true;

                }


                if (isMatch == false) {
                    label1.setIcon(null);

                }

            }

}

我建议不要将ImageIcons传递到
ismatch(…)
方法中,而是传递两个包含ImageIcons的JLabel。然后,在该方法中,您可以提取图像图标并进行比较,与之前相同,但更重要的是,您有一个对保存图标的JLabel的引用,然后您可以将它们设置为背景图标或空图标

// "second" is mispelled
public boolean ismatch(JLabel firstChoiceLabel, JLabel secoundChoceLabel) {

    ImageIcon firstChoice = firstChoiceLabel.getIcon();
    ImageIcon secoundChoice = secoundChoiceLabel.getIcon(); 

    if (firstChoice.getImage() == secoundChoce.getImage()) {
        JOptionPane.showMessageDialog(null, " wowo you got it ^^");
        isMatch = true;
    } else {
        JOptionPane.showMessageDialog(null, "  notmatced");
        isMatch = false;

        // here set Icon to null or to background icon.
        firstChoiceLabel.setIcon(null);
        secoundChoiceLabel.setIcon(null);
    }
    return isMatch;
}

@MariamAbuEtewy:在引用应用程序资源时使用绝对路径,这确实不是一个好做法。谢谢。。但是如何将Jlabel传递给方法?@MAriam:传递Jlabel的方式与传递ImageIcon的方式相同。