如何获取单击的JButton的索引? [英] How to get the indexes of the clicked JButton?

查看:40
本文介绍了如何获取单击的JButton的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JButton[][]的矩阵.我尝试在存储按钮索引的按钮上添加ActionListener.

I have a matrix of JButton[][]. I try to add ActionListener to the buttons which stores the index of the button.

我需要做一个游戏.

第一次单击显示应该从哪个按钮移动,第二次单击显示在哪里移动.

The first click shows from which button should I step and the second shows where to step.

推荐答案

您可以使用HashMaps,2D Arrays等以多种方式实现您的需要……这是我的建议:

What you need can be achieved in several ways, using HashMaps, 2D Arrays, etc etc... here is my suggestion:

继承:您现在需要一个按钮,该按钮具有2个默认情况下未定义的属性(行和行)

Inheritance: you need now a Button with 2 properties that are not defined by default (col and row)

class MatrixButton extends JButton {
    private static final long serialVersionUID = -8557137756382038055L;
    private final int row;
    private final int col;

    public MatrixButton(String t, int col, int row) {
    super(t);
    this.row = row;
    this.col = col;
    }

    public int getRow() {
    return row;
    }

    public int getCol() {
    return col;
    }
}


您肯定有一个面板,可以在其中添加JButton,现在改为添加 MatrixButton

 panel.add(MatrixButton);

然后添加动作侦听器

button1.addActionListener(this);

当您单击时,您就可以得到位置坐标

and when you click you get the position coordinates by doing

   @Override
    public void actionPerformed(ActionEvent ae) {
    if (ae.getSource() == this.button1) {
        System.out
            .println(((MatrixButton) ae.getSource()).getRow() + "," + ((MatrixButton) ae.getSource()).getCol());
    } else if (ae.getSource() == this.button2) {
        // TODO
    } else if (ae.getSource() == this.button3) {
        // TODO
    }
    }

这篇关于如何获取单击的JButton的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆