你的问题归结为它的本质是:我怎样才能让一个对象改变另一个对象的状态?
有很多可能的方法来给这只猫换皮,但最简单的是给一个类,这里是 Ocean(或者可能是 gameBoard?你的代码很混乱)外部 ActionListener 可以调用的公共方法来改变它的状态。例如,您可以给按钮网格持有类一个公共方法: setText(...) 像这样:
public void setText(int row, int col, String text) {
buttons[row][col].setText(text);
}
ActionListener 可以通过构造函数参数传递对这个网格持有类的引用,允许它在需要时调用这个方法。
还请注意,您始终可以通过 ActionListener actionPerformed 方法的 ActionEvent 参数获取对按下的 JButton 的引用。它有一个getSource() 方法,该方法返回对启动事件的对象(此处为 JButton)的引用。
如果您需要更详细的解决方案,请考虑创建并发布有效的Minimal, Complete, and Verifiable example。
例如:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SimpleButtonGridMain extends JPanel {
private static void createAndShowGui() {
SimpleButtonGrid simpleButtonGrid = new SimpleButtonGrid();
MyButtonListener myButtonListener = new MyButtonListener();
simpleButtonGrid.addActionListener(myButtonListener);
JFrame frame = new JFrame("SimpleButtonGridMain");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(simpleButtonGrid);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class SimpleButtonGrid extends JPanel {
private static final int ROWS = 10;
private static final int COLS = ROWS;
private JButton[][] buttons = new JButton[ROWS][COLS];
public SimpleButtonGrid() {
setLayout(new GridLayout(ROWS, COLS, 3, 3));
for (int row = 0; row < buttons.length; row++) {
for (int col = 0; col < buttons[row].length; col++) {
String text = String.format(" [ %d, %d ] ", col, row);
JButton button = new JButton(text);
add(button);
buttons[row][col] = button;
}
}
}
public void addActionListener(ActionListener listener) {
for (JButton[] jButtons : buttons) {
for (JButton jButton : jButtons) {
jButton.addActionListener(listener);
}
}
}
}
class MyButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
JButton sourceBtn = (JButton) e.getSource();
String message = "Button pressed: " + actionCommand;
JOptionPane.showMessageDialog(sourceBtn, message, "Button Pressed", JOptionPane.PLAIN_MESSAGE);
sourceBtn.setText("Pressed");
sourceBtn.setEnabled(false);
}
}