我有一个关于 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);
您想比较两个 String
的value,而不是reference。
我认为您应该将 ==
运算符替换为函数 String.equals(Object object)
。
像这样:
if(button.getText().equals(Y)) button.setText(X);
编辑:
如果您有两个具有相同值的 String
变量,它们将对该值具有相同的引用,因为在 Java 中 String
是不可变的。但他们不会有相同的地址。这里有一个例子:
所以 ==
运算符将比较变量 a
和 b
的地址,而不是值.而函数 String.equals(Object object)
将比较变量 a
和 b
的值。
关于java - 交换 2 个特定的 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32175895/