简体   繁体   English

我如何比较两个按钮 java

[英]How can I compare two buttons java

I'm trying to code a memory game and I had chosen every button with a specific color.我正在尝试编写一个 memory 游戏,我选择了具有特定颜色的每个按钮。 I want to compare these two buttons.我想比较这两个按钮。 When the user clicks the next button I want to start comparing.当用户单击下一步按钮时,我想开始比较。 I came up with comparing the color's background.我想出了比较颜色的背景。 I have tried to save the background color in a variable and test if they are the same but it doesn't enter the if statement even if the two colors are the same.我试图将背景颜色保存在一个变量中并测试它们是否相同但是即使两个 colors 相同也不会进入if语句。 If you have any other ideas, please help me:)如果您有任何其他想法,请帮助我:)

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MemoryGame implements ActionListener {

    public static void main(String[] args) {
        MemoryGame a = new MemoryGame();
    }

    ArrayList<Color> colors = new ArrayList<Color>(Arrays.asList(Color.black,
                                                                 Color.BLUE,
                                                                 Color.yellow,
                                                                 Color.GRAY,
                                                                 Color.cyan,
                                                                 Color.RED,
                                                                 Color.PINK,
                                                                 Color.orange,
                                                                 Color.orange,
                                                                 Color.yellow,
                                                                 Color.black,
                                                                 Color.BLUE,
                                                                 Color.PINK,
                                                                 Color.cyan,
                                                                 Color.RED,
                                                                 Color.GRAY));
    Random rand = new Random();
    JFrame myframe = new JFrame();
    JPanel title = new JPanel();
    JPanel Button_Panel = new JPanel();
    JButton[] buttons = new JButton[16];
    JLabel textfield = new JLabel();
    boolean Click1_turn = true;

    MemoryGame() {
        myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myframe.setSize(1000, 1000);
        myframe.getContentPane().setBackground(Color.gray);
        myframe.setVisible(true);
        myframe.setLayout(new GridLayout()); // to put the buttons in it

        Button_Panel.setLayout(new GridLayout(4, 5));
        Button_Panel.setBackground(Color.black);
        myframe.add(Button_Panel);

        for (int i = 0; i < 16; i++) {
            buttons[i] = new JButton();
            Button_Panel.add(buttons[i]);
            buttons[i].setFont(new Font("MV", Font.BOLD, 120));
            buttons[i].setFocusable(false);
            buttons[i].addActionListener(this);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(e.getActionCommand());
        Color Click1 = colors.get(0);
        Color Click2 = colors.get(0);
        for (int i = 0; i < 16; i++) {
            if (e.getSource() == buttons[i]) {
                if (Click1_turn) {
                    buttons[i].setBackground(colors.get(i));
                    Click1 = buttons[i].getBackground();
                    System.out.println("1" + Click1);
                    Click1_turn = false;
                }
                else {
                    buttons[i].setBackground(colors.get(i));
                    Click2 = buttons[i].getBackground();
                    Click1_turn = true;
                    System.out.println("2" + Click2);
                    if (Click2.equals(Click1)) {
                        System.out.println("ss");
                    }
                    else {
                        System.out.println("nah");
                    }
                }
            }
        }
    }
}

JButtons, as many other UI elements have properties that are related to their screen rendering. JButton 和许多其他 UI 元素一样具有与其屏幕呈现相关的属性。 Unless you really just need such properties, it is abuse to interprete these UI related properties as application relevant.除非您真的只需要这些属性,否则将这些与 UI 相关的属性解释为与应用程序相关是一种滥用行为。

Create your own data model. With that you would know how many fields are on the game board and which values to put on which field (color, player, building, ...).创建您自己的数据 model。有了它,您就会知道游戏板上有多少个字段以及将哪些值放在哪个字段(颜色、玩家、建筑物等)上。 To be clean, ensure the model does not contain any references to UI elements.为了干净起见,请确保 model 不包含对 UI 元素的任何引用。

In a next step create a view of that board.在下一步中创建该板的视图。 It would map the fields to some UI component and ensure that one gets rendered.它会将 map 字段发送到某个 UI 组件,并确保呈现一个。 In your case, every button would have an ActionListener attached that knows which field is meant when the button gets clicked.在您的情况下,每个按钮都会附加一个 ActionListener,它知道单击按钮时意味着哪个字段。

Since you probably need to compare only when the second button gets clicked you need to remember how many buttons have already been pressed, and which.由于您可能只需要在单击第二个按钮时进行比较,因此您需要记住已经按下了多少个按钮以及哪些按钮。 All this would go into your data model.所有这些都会将 go 转换为您的数据 model。

So when a button is pressed, check if a selection is already there.所以当一个按钮被按下时,检查一个选择是否已经存在。 If not, this selection shall be set.如果不是,则应设置此选择。 (it resembles the first button). (它类似于第一个按钮)。 If there is a selection already, compare the selected field with the second button's field, then reset the selection.如果已经有选择,则将所选字段与第二个按钮的字段进行比较,然后重置选择。

Your logic – in method actionPerformed – is flawed.您的逻辑——在方法actionPerformed中——是有缺陷的。 You are resetting Click1 and Click2 to black every time method actionPerformed is invoked, ie every time a JButton is clicked.每次调用方法actionPerformed时,即每次单击JButton时,您都将Click1Click2重置为黑色

You obviously want Click1 to keep the color it was assigned when variable Click1_turn was true .您显然希望Click1保持在变量Click1_turntrue时分配给它的颜色。

Therefore you should make both Click1 and Click2 class member variables, so that they keep their assigned values between separate calls to actionPerformed .因此,您应该使Click1Click2都成为 class 成员变量,以便它们在对actionPerformed的单独调用之间保持分配的值。

If you run your code through a debugger, you will discover this.如果您通过调试器运行您的代码,您会发现这一点。 Note that every programmer needs to learn how to debug code, including code written by others.请注意,每个程序员都需要学习如何调试代码,包括其他人编写的代码。

Making both Click1 and Click2 class member variables is the simplest way to fix your program.使Click1Click2都成为 class 成员变量是修复程序的最简单方法。 Refer to the code below.请参考下面的代码。 Note that I changed the identifiers so as to conform to Java naming conventions .请注意,我更改了标识符以符合Java 命名约定

(More notes after the code.) (代码后有更多注释。)

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MemoryGame implements ActionListener {
    private Color click1;
    private Color click2;

    public static void main(String[] args) {
        MemoryGame a = new MemoryGame();
    }

    ArrayList<Color> colors = new ArrayList<Color>(Arrays.asList(Color.black,
                                                                 Color.BLUE,
                                                                 Color.yellow,
                                                                 Color.GRAY,
                                                                 Color.cyan,
                                                                 Color.RED,
                                                                 Color.PINK,
                                                                 Color.orange,
                                                                 Color.orange,
                                                                 Color.yellow,
                                                                 Color.black,
                                                                 Color.BLUE,
                                                                 Color.PINK,
                                                                 Color.cyan,
                                                                 Color.RED,
                                                                 Color.GRAY));
    Random rand = new Random();
    JFrame myFrame = new JFrame();
    JPanel title = new JPanel();
    JPanel buttonPanel = new JPanel();
    JButton[] buttons = new JButton[16];
    JLabel textfield = new JLabel();
    boolean click1Turn = true;

    MemoryGame() {
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(1000, 1000);
        myFrame.getContentPane().setBackground(Color.gray);
        myFrame.setVisible(true);

        buttonPanel.setLayout(new GridLayout(0, 4));
        buttonPanel.setBackground(Color.black);
        myFrame.add(buttonPanel);

        for (int i = 0; i < 16; i++) {
            buttons[i] = new JButton();
            buttonPanel.add(buttons[i]);
            buttons[i].setFont(new Font("MV", Font.BOLD, 120));
            buttons[i].setFocusable(false);
            buttons[i].addActionListener(this);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(e.getActionCommand());
//        Color Click1 = colors.get(0);
//        Color Click2 = colors.get(0);
        for (int i = 0; i < 16; i++) {
            if (e.getSource() == buttons[i]) {
                if (click1Turn) {
                    buttons[i].setBackground(colors.get(i));
                    click1 = buttons[i].getBackground();
                    System.out.println("1" + click1);
                    click1Turn = false;
                }
                else {
                    buttons[i].setBackground(colors.get(i));
                    click2 = buttons[i].getBackground();
                    click1Turn = true;
                    System.out.println("2" + click2);
                    if (click2 == click1) {
                        System.out.println("ss");
                    }
                    else {
                        System.out.println("nah");
                    }
                }
            }
        }
    }
}
  • Since all your colors are constants from class java.awt.Color , you can use == to compare them rather than calling method equals .由于您所有的 colors 都是来自 class java.awt.Color的常量,您可以使用==来比较它们而不是调用方法equals
  • System.out.println(e.getActionCommand()); prints nothing since none of the buttons have a value assigned to actionCommand .不打印任何内容,因为所有按钮都没有分配给actionCommand的值。
  • buttons[i].setFont(new Font("MV", Font.BOLD, 120)); Since you aren't setting any text for the JButton , changing the font has no effect.由于您没有为JButton设置任何文本,因此更改字体无效。
  • Button_Panel.setLayout(new GridLayout(4, 5)); Usually better to only set one dimension, ie Button_Panel.setLayout(new GridLayout(0, 4));通常最好只设置一个维度,即Button_Panel.setLayout(new GridLayout(0, 4)); This means that the "grid" will have exactly four columns in each row.这意味着“网格”每行将恰好有四列。 Refer to How to Use GridLayout .请参阅如何使用 GridLayout
  • myframe.setLayout(new GridLayout()); This is not necessary.这是没有必要的。 The default layout is suitable.默认布局是合适的。

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

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