上个月,我用我对 Java 的了解编写了一个可爱的 Tictactoe 游戏。它的一个组成部分在下面的 3 个代码片段中:
// from the constructor ...
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(3, 3));
guiFrame.add(buttonPanel);//, BorderLayout.CENTER);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
button[i][j] = addButton(buttonPanel, i, j);
// ...
private JButton addButton (Container parent, int row, int col) {
int v = (10 * (row + 1) + col + 1); // 11, 12, 13, 21, 22, 23, ... 33
String s = " " + v;
JButton cell = new JButton();
parent.add(cell);
cell.setActionCommand(s);
cell.addActionListener(this);
return cell;
}
public void actionPerformed(ActionEvent e) {
// ... snip
String r = e.getActionCommand().substring(1, 2); // row 1, 2, or 3
String c = e.getActionCommand().substring(2, 3); // col 1, 2, or 3
try {
row = Integer.parseInt(r); col = Integer.parseInt(c);
}
catch (Exception ex) { }
}
它的要点是将(行,列)信息存储到每个单元格的“动作命令”中,以便我以后可以getActionCommand
用来判断谁的单元格包含 X 或 O(通过未显示的逻辑)。
可能是更好的方法;无论如何,它有效。
现在我要处理一个 11x11 的网格,它或多或少是一个填字游戏网格。我想使用类似的逻辑来确定JTextField
刚刚敲击的按键组合以确定是否将背景设置为黑色。这是添加单元格的非常相似的逻辑:
private JTextField addCell (Container parent, int row, int col) {
JTextField cell;
cell = new JTextField();
int v = (100 * (row + 1) + col + 1);
// v will go 101,102,...111; 201,202,...,211; ... 1101,1102,...1111
String s = "" + v;
cell.setActionCommand(s);
parent.add(cell);
cell.addKeyListener(this);
cell.addActionListener(this);
return cell;
}
但我找不到像听众事件这样getActionCommand
的东西。JTextField
这是我从以下System.out.println("keyPressed " + evt.getSource());
语句中 得到的内容(为了便于阅读而进行了大量编辑) public void keyPressed(KeyEvent evt)
:
keyPressed JTextField
[
, 5, 5, 34x32,
layout = BasicTextUI$UpdateHandler,
alignmentX = 0. 0, alignmentY = 0. 0,
border = BorderUIResource$CompoundBorderUIResource@f864fe,
flags = 296,
maximumSize = , minimumSize = , preferredSize = ,
caretColor = PrintColorUIResource [r = 51, g = 51, b = 51],
disabledTextColor = ColorUIResource [r = 184, g = 207, b = 229],
editable = true,
margin = InsetsUIResource [top = 0, left = 0, bottom = 0, right = 0],
selectedTextColor = PrintColorUIResource [r = 51, g = 51, b = 51],
selectionColor = ColorUIResource [r = 184, g = 207, b = 229],
columns = 0, columnWidth = 0,
command = 101,
horizontalAlignment = LEADING
]
她在最后一行旁边吹了,这command = 101
正是我需要得到的,但无论如何我尝试过“命令”都不可用。
你的想法/建议/hellllllp?