Java 获取gridlayout上按钮的位置
如何使用gridlayout获取单击按钮的位置(我指的是行和列)Java 获取gridlayout上按钮的位置,java,arrays,swing,jbutton,mouselistener,Java,Arrays,Swing,Jbutton,Mouselistener,如何使用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.
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);
}
public void init(最终容器窗格){
JPanel controls=新的JPanel();
int size=(int)Math.sqrt(puzzle.getSize()+1);
setLayout(新的GridLayout(大小、大小));
对于(int i=0;i
getSource()
JButton进行比较
i、 e.在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
}
}
}
getSource()
JButton进行比较
i、 e.在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
}
}
}
在这种情况下,您甚至不必搜索索引,因为您在创建按钮时就知道它们:
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));
final int rowIndex = i / size;
final int columnIndex = i % size;
// Using an ActionListener, as Hovercraft Full Of Eels already told you:
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("rowIndex "+rowIndex+" columnIndex "+columnIndex);
}
});
controls.add(jb);
}
}
for(int i=0;i
在这种情况下,您甚至不必搜索索引,因为您在创建按钮时就知道它们:
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));
final int rowIndex = i / size;
final int columnIndex = i % size;
// Using an ActionListener, as Hovercraft Full Of Eels already told you:
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("rowIndex "+rowIndex+" columnIndex "+columnIndex);
}
});
controls.add(jb);
}
}
for(int i=0;i
噢。我懂了。我不知道。我懂了。我不知道。