java - java中的ImageIcon

标签 java swing jlabel imageicon

我正在开发匹配照片游戏,我想我可以通过知道容器标签的名称来重置 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。然后在该方法中,您可以提取 ImageIcons 并比较它们,与以前一样,但更重要的是,您有一个对保存图标的 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;
}

关于java - java中的ImageIcon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11382827/

相关文章:

java - 单击按钮时更新 jLabel

java - 如何在我的小程序中进行倒计时?

java - 使用 txt 输入文件和扫描仪处理空行

Java 8 Streams API HAVING 子句等同于 GroupingBy?

java - JFreeChart 隐藏在另一个图表后面

java - 在 Java 中修改图形上下文

java - 如何在迭代 <c :foreach> tag in select tag in JSP? 时从任何列表对象中删除元素

java - 为什么 Riak 将 "inavailable channel closed"消息记录为 ERROR

Java - repaint(x, y, w, h) 不调用 paintComponent? (与SSCCE)

java - 将文本文件中的随机行读取到 JLabel 中