- 切勿为此目的在 JButton 上添加 MouseListener。请改用 ActionListener。
- 为什么不创建 JButton 的数组或 ArrayList,然后简单地遍历列表以找到合适的?
即,
private JButton[][] buttonGrid = new JButton[ROWS][COLS];
在其他地方,您需要用可行的 JButton 对象填充网格并将这些 JButton 放入您的 GUI。
然后稍后在程序中使用嵌套的 for 循环遍历网格,将网格按钮与 getSource() JButton 进行比较。
即在 JButton 的 ActionListener 中
public void actionPerformed(ActionEvent e) {
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
if buttonGrid[row][col] == e.getSource();
// here you have your row and column
}
}
}
编辑
你问:
- 为什么?
因为它在许多情况下都无法正常工作。 ActionListeners 是专门为与 JButtons 和 JMenuItems 一起工作而构建的,并且具有使此功能工作良好且容易的机制。例如,假设您决定拥有一个仅在用户填写了两个 JTextField 后才启用的 JButton,并且您使用 JButton 的 setEnabled(boolean enabled) 方法来执行此操作,禁用 JButton 不会阻止 MouseListener 工作,但它会停止ActionListener。
编辑 2
例如,
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ButtonGridEg extends JPanel {
private static final int ROWS = 8;
private static final int COLS = ROWS;
private static final int GAP = 5;
private JButton[][] buttonGrid = new JButton[ROWS][COLS];
public ButtonGridEg() {
setLayout(new GridLayout(ROWS, COLS, GAP, GAP));
ActionListener buttonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
JButton selectedBtn = (JButton) evt.getSource();
for (int row = 0; row < buttonGrid.length; row++) {
for (int col = 0; col < buttonGrid[row].length; col++) {
if (buttonGrid[row][col] == selectedBtn) {
System.out.printf("Selected row and column: %d %d%n", row, col);
}
}
}
}
};
for (int row = 0; row < buttonGrid.length; row++) {
for (int col = 0; col < buttonGrid[row].length; col++) {
String text = String.format("Button [%d, %d]", row, col);
buttonGrid[row][col] = new JButton(text);
buttonGrid[row][col].addActionListener(buttonListener);
add(buttonGrid[row][col]);
}
}
}
private static void createAndShowGui() {
ButtonGridEg mainPanel = new ButtonGridEg();
JFrame frame = new JFrame("ButtonGridEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}