无法将按钮图标与另一个图标进行比较

时间:2018-12-14 17:42:56

标签: java swing compare icons jbutton

我要覆盖actionListener。除“ playbutton”以外的所有按钮都有一个作为图标附加的图像(button1,button2,button3)。每次按下按钮时,都应将其图标与准备好的ImageIcon“ livePicture”进行比较,如果它们相同,则应使用“ Escaped()”方法。否则,程序将运行“ Died()”方法。 但是,至少在当前代码中,它仅使用“ Died()”。我猜这意味着比较图片的ifs出了点问题,但这是我在互联网上发现的唯一比较方式。 另外,请记住,这是我的第一个项目,因此可能看起来有些混乱。

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Vector;

public class Frame
{
private final int WIDTH = 1024;
private final int HEIGHT = 768;

private JFrame frame;
private JPanel panel;
private JLabel human;
private JTextArea text;
private JTextArea deathMessage;
private ImageIcon livePicture;
private JButton button1;
private JButton button2;
private JButton button3;
private GridBagConstraints gbc;
private ActionListener actionListener;
private JButton playButton;
private Border border = BorderFactory.createEmptyBorder();
private Font font = new Font(Font.MONOSPACED, Font.PLAIN, 20);

public Frame()
{
    Quest survival = new Quest();

    actionListener = e -> {
        if (e.getSource() == playButton) //playbutton works fine
        {
            if (!survival.IsEmpty())
            {
                AppendQuest(survival.GetQuest());
                survival.RemoveQuest();
            }
            else
            {
                Escaped();
            }
        }
        else if (e.getSource() == button1) //button1 action
        {
            if (button1.getIcon().toString() != livePicture.toString())
            {
                Died();
            }
            else
            {
                if (!survival.IsEmpty())
                {
                    AppendQuest(survival.GetQuest());
                    survival.RemoveQuest();
                }
                else
                {
                    Escaped();
                }
            }
        }
        else if (e.getSource() == button2) //button2 action
        {
            if (button2.getIcon().toString() != livePicture.toString())
            {
                Died();
            }
            else
            {
                if (!survival.IsEmpty())
                {
                    AppendQuest(survival.GetQuest());
                    survival.RemoveQuest();
                }
                else
                {
                    Escaped();
                }
            }
        }
        else if (e.getSource() == button3) //button3 action
        {
            if (button3.getIcon().toString() != livePicture.toString())
            {
                Died();
            }
            else
            {
                if (!survival.IsEmpty())
                {
                    AppendQuest(survival.GetQuest());
                    survival.RemoveQuest();
                }
                else
                {
                    Escaped();
                }
            }
        }
    };
    //I left the rest of the constructor for bonus info
    frame = new JFrame();
    panel = new JPanel();
    gbc = new GridBagConstraints();
    human = new JLabel(ImageSize(200, 200, "res/human.png"));
    text = new JTextArea("You have lost in the forest. Now you have to find " +
            "your way back.");
    FormatText(text);
    deathMessage = new JTextArea();
    frame.setTitle("Shady Path");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(WIDTH, HEIGHT);
    frame.setLocationRelativeTo(null);
    frame.getContentPane().setBackground(Color.BLACK);
    frame.setResizable(false);

    playButton = new JButton();
    playButton.addActionListener(actionListener);
    playButton.setFont(font);
    playButton.setText("Play");
    playButton.setForeground(Color.WHITE);
    playButton.setBackground(Color.BLACK);
    playButton.setBorder(border);

    panel.setLayout(new GridBagLayout());
    panel.setOpaque(false);
    gbc.anchor = GridBagConstraints.PAGE_START;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    panel.add(human, gbc);

    gbc.insets = new Insets(30, 0, 0, 0);
    gbc.weightx = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    panel.add(text, gbc);

    gbc.fill = GridBagConstraints.VERTICAL;
    gbc.insets = new Insets(50, 0, 68, 0);
    panel.add(playButton, gbc);
    frame.add(panel);
    frame.setVisible(true);
}

public void AppendQuest(Vector<String> event)
{
    panel.removeAll();

    panel.add(human, gbc);
    gbc.insets = new Insets(0, 0, 30, 0);
    text.setText(event.remove(0));
    FormatText(text);
    panel.add(text, gbc);
    deathMessage.setText(event.remove(0));
    FormatText(deathMessage);
    livePicture = ImageSize(50, 50, event.remove(0));

    Collections.shuffle(event);
    ImageIcon picture1 = ImageSize(50, 50, event.get(0)); //setting button1
    button1 = new JButton();
    button1.addActionListener(actionListener);
    button1.setIcon(picture1);
    button1.setBorder(border);
    ImageIcon picture2 = ImageSize(50, 50, event.get(1)); //setting button2
    button2 = new JButton();
    button2.addActionListener(actionListener);
    button2.setIcon(picture2);
    button2.setBorder(border);
    ImageIcon picture3 = ImageSize(50, 50, event.get(2)); //setting button3
    button3 = new JButton();
    button3.addActionListener(actionListener);
    button3.setIcon(picture3);
    button3.setBorder(border);
    gbc.gridwidth = GridBagConstraints.HORIZONTAL;
    gbc.insets = new Insets(50, 360, 100, 0);
    panel.add(button1, gbc);
    gbc.insets = new Insets(50, 77, 100, 77);
    panel.add(button2, gbc);
    gbc.insets = new Insets(50, 0, 100, 360);
    panel.add(button3, gbc);

    panel.revalidate();
    panel.repaint();
}

private void Escaped()
{
    //Unnecessary info
}

private void Died()
{
    //Unnecessary info
}
//This just resizes the images
private ImageIcon ImageSize(int x, int y, String fileName)
{
    BufferedImage baseImg = null;
    try {
        baseImg = ImageIO.read(new File(fileName));
    } catch (IOException e) {
        e.printStackTrace();
    }
    Image resizedImg = baseImg.getScaledInstance(x, y, Image.SCALE_SMOOTH);
    ImageIcon IconImg = new ImageIcon(resizedImg);
    return IconImg;
}

private void FormatText(JTextArea baseText)
{
    //Unnecessary info
}
}

编辑: 这也是一个示例,其中矢量可以在“ AppendQuest”中作为“事件”发生

Vector<String> items2 = new Vector<>();
items2.add("You are kind of disoriented. What will you use to find the right way?" +
            " moss, sun or tree barks");
items2.add("Unfortunately you didn't orient yourself well enough. Now, you " +
            "will roam through the forest forever.");
items2.add("res/orientation_sun.png");
items2.add("res/orientation_moss.png");
items2.add("res/orientation_sun.png");
items2.add("res/orientation_tree_bark.png");

1 个答案:

答案 0 :(得分:1)

您可以将对象与.equals(Object)函数进行比较:

if(!button.getIcon().equals(livePicture))
{
   Died();
}
else
{...}

==运算符检查对象的身份或本机类型的值(例如int)。 这意味着:

int nr1 = 1;
int nr2  = 1;
if(nr1 == nr2) {...} //true -> int is a native type

String str1 = "test";
String str2 = "test";
if(str1 == str2) {...} //false -> Same content but not same objects
if(str1.equals(str2)) {...} //true -> Same content, different objects

//编辑: 另一个问题可能是您在创建livePicture时从矢量中删除了图像网址:

livePicture = ImageSize(50, 50, event.remove(0));

创建按钮时,URL不再在列表中。结果是这些按钮将永远不会具有与livePicture相同的图像,除非您对其进行更改(对吗?)。