【发布时间】:2015-05-02 01:59:30
【问题描述】:
package javaapplication3;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class BattleShip2 extends JFrame implements ActionListener {
JButton[][] array2dtop = new JButton[10][10];
BattleShip2(String title) { //Board Display
super(title);//show Title
setLayout(new FlowLayout()); // button posistion
for(int x = 0; x < array2dtop.length; x++) {
for(int y = 0; y < array2dtop.length; y++) {
array2dtop[x][y] = new JButton(String.valueOf((x * 10) + y)); //display
array2dtop[x][y].setBounds(20,40,140,20);
array2dtop[x][y].setActionCommand("x"); //itself value
array2dtop[x][y].addActionListener(this);
add(array2dtop[x][y]);
}
}
}
public void actionPerformed(ActionEvent evt) { //operation
String cmd = evt.getActionCommand();
if(cmd == "x") {
System.out.println("x");
}
}
}
public class pratice3 {
public static void main(String[] args) {
BattleShip2 board = new BattleShip2("BattleShip");
board.setSize(500, 400);
board.setLocation(250, 250);
board.setDefaultCloseOperation(board.EXIT_ON_CLOSE); //Press x to EXIT
board.setVisible(true);
}
}
您好,我正在创建一个战舰游戏,我的想法是当用户或 AI 按下按钮时,它可以显示船的大小 例如,有 3 艘船:ship1(size = 3)、ship2(size = 2)、ship3(size = 1),当用户/AI 击中 ship1,他们看到 3 时,他们会知道他们击中了 ship1
但我在 setActioncommand 上遇到问题
关于代码,
array2dtop[x][y].setActionCommand("x")
我想分配或声明一个整数(船的大小)到 array2dtop[x][y] 但我不知道,但分配一个字符串以及如何在 actionPerformed 中使用它
【问题讨论】:
-
所以你有一个按钮矩阵,你希望一个 JButton 在你点击后神奇地变成一个整数?我敢肯定这是不对的——你能更详细地解释一下你要做什么吗?
-
所以在actionperformed函数中,字符串cmd是在比较字符串x,所以可以用整数而不是字符串进行比较吗?
标签: java arrays swing jframe jbutton