简体   繁体   English

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

[英]Can't compare button icon to another icon

I am overriding the actionListener. 我覆盖了actionListener。 All of the buttons besides "playbutton" have an image attached as an icon (button1, button2, button3). 除“ playbutton”以外的所有按钮都有一个作为图标附加的图像(button1,button2,button3)。 Every time a button is pressed, it should compare its icon to the prepared ImageIcon "livePicture" and if they are the same, it should go with the "Escaped()" method. 每次按下按钮时,都应将其图标与准备好的ImageIcon“ livePicture”进行比较,如果它们相同,则应使用“ Escaped()”方法。 Otherwise, the program will run the "Died()" method. 否则,程序将运行“ Died()”方法。 However, at least with the current code, it only uses "Died()". 但是,至少在当前代码中,它仅使用“ Died()”。 This, I guess, means that there is something wrong with the ifs that compare the images, but that is the only way of comparison I found on the internet. 我猜这意味着比较图片的ifs出了点问题,但这是我在互联网上发现的唯一比较方式。 Also, keep in mind that this is my first project, so it may seem a little cluttered. 另外,请记住,这是我的第一个项目,因此可能看起来有些混乱。

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

EDIT: Here is also an example of what vector could go as an "event" in "AppendQuest" 编辑:这也是向量可以作为“ 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");

You can compare Objects with the .equals(Object) function: 您可以将对象与.equals(Object)函数进行比较:

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

The == operator checks the identity of objects or the value of native types (eg int). ==运算符检查对象的身份或本机类型(例如int)的值。 That means: 这意味着:

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

//Edit: Another problem might be that you remove the image-url from your vector while creating the livePicture: //编辑:另一个问题可能是在创建livePicture时从矢量中删除了图像网址:

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

The url is not in the list anymore when you create your buttons. 创建按钮时,该URL不再在列表中。 The result is that the buttons will never have the same image as your livePicture has, unless you're changing it (do you?). 结果是,除非您进行更改,否则按钮将永远不会具有与livePicture相同的图像(对吗?)。

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

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