java - 交换 2 个特定的 JButton

标签 java arrays button matrix swap

我有一个关于 Java 编码的快速(或不)问题。

有没有一种方法可以交换 2 个 JButton 中的文本,或者当我只单击其中一个时交换按钮本身?就像,每个按钮都有一个特定的其他按钮,需要一次单击将其替换。 尽管在我的代码中它不是整数,而是字符串“X”和“Y”。

这是我的代码:

package game;

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Game extends JFrame implements ActionListener{

  public static void main(String[] args) {
    int row = 5;
    int col = 5;
    Game gt = new Game(row, col);
    gt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gt.pack();
    gt.setVisible(true);

  }

  String X = "X";
  String Y = "Y";
  int i = 0;
  int j = 0;

  public Game(int row, int col) {
    Container pane = getContentPane();
    pane.setLayout(new GridLayout(row, col));
    for(int i = 0; i < 25; i++)
    {
      if(i == 1 || i == 2 || i == 14 || i == 15 || i == 23 || i == 9)
      {
      JButton button = new JButton(X);
      pane.add(button);
      button.addActionListener(new ActionListener()
      {
            @Override
            public void actionPerformed(ActionEvent e) {
            if (e.getSource()==button)
            {
                if(button.getText() == Y) button.setText(X);
                        else button.setText(Y);
            }
            }

      }
      );
      } else if(i == 3 || i == 5 || i == 10 || i == 19 || i == 21 || i == 22){
      JButton button = new JButton(Y);
      pane.add(button);
      button.addActionListener(new ActionListener()
      {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource()==button)
            {
                if(button.getText() == Y) button.setText(X);
                    else button.setText(Y);
            }
            }

      });
      } else {
      JButton button = new JButton();
      pane.add(button);
      button.setEnabled(false);
      button.setBorderPainted(false);
      }
    }
  } 
  @Override
    public void actionPerformed(ActionEvent e) {
    }
  }

提前致谢!

最佳答案

在这行代码中

if(button.getText() == Y) button.setText(X);

您想比较两个 Stringvalue,而不是reference。 我认为您应该将 == 运算符替换为函数 String.equals(Object object)

像这样:

if(button.getText().equals(Y)) button.setText(X);

编辑:

如果您有两个具有相同值的 String 变量,它们将对该值具有相同的引用,因为在 Java 中 String不可变的。但他们不会有相同的地址。这里有一个例子:

Illustration of the String in Java

所以 == 运算符将比较变量 ab地址,而不是值.而函数 String.equals(Object object) 将比较变量 ab

关于java - 交换 2 个特定的 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32175895/

相关文章:

java - Android 应用程序在定义字节缓冲区来读取文件时崩溃

java - 在Java中使用正则表达式分割字符串?

javascript - 如何对对象数组中的某些值进行舍入?

Java 返回问题

c++ - 在 C++ 中将 char 数组读取为 float 组,而无需使用 memcpy 复制它

javascript - 单击按钮后如何获取 console.log 的值并显示在我的输入文本中

android - 如何将宽度设置为 "fill parent"的 android 按钮中的图标和文本居中

java - 如何手动从 JMS 队列中仅获取特定类型的消息并保留所有其他消息?

java - 在 Java 应用程序环境中打开 .rtx 文件?

java - 如何动态创建按钮并跟踪按下的按钮?