如何获得带有gridlayout的点击按钮的位置(我的意思是行和列)?
public void init(final Container pane) {
JPanel controls = new JPanel();
int size = (int) Math.sqrt(puzzle.getSize() + 1);
controls.setLayout(new GridLayout(size, size));
for (int i = 0; i < puzzle.getSize(); i++) {
int k = puzzle.getListItem(i);
if (k == puzzle.getEmptyFlag())
controls.add(new JLabel(""));
else {
JButton jb = new JButton(String.valueOf(k));
jb.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//get row and column
}
});
controls.add(jb);
}
}
pane.add(controls);
}
2 回答
永远不要在JButton上添加MouseListener用于此目的 . 请改用ActionListener .
为什么不创建JButton的数组或ArrayList,然后简单地遍历列表以找到合适的数组?
即,
在其他地方,您需要使用可行的JButton对象填充网格,并将这些JButton放入GUI中 .
然后在程序中使用嵌套for循环迭代网格,比较网格按钮和
getSource()
JButton .即在JButton的ActionListener中
Edit
你问:
因为它赢得了't work correctly in many situations. ActionListeners have been built to work specifically with JButtons and JMenuItems and have mechanisms that make this function work well l and easily. For example, say you decide to have a JButton that is only enabled once the user has filled two JTextFields, and you use the JButton'方法来执行此操作,禁用JButton不会阻止MouseListener工作,但它将停止ActionListener .
Edit 2
例如,
在这种情况下,您甚至不必搜索索引,因为您在创建按钮时知道它们: