java - 返回点击按钮的索引?

标签 java arrays swing jbutton

我有一个包含 30 个按钮的数组 []。我有一个变量 buttonClicked。当我按下按钮时,如何获取索引并将索引号存储在 buttonClicked 中?

谢谢:)

JButton [] buttons = new JButton[30]; 


        for(int i = 1; i <= 30; i++)
        {       
            int btnNumber = (i > 10 && i <= 20) ? (31 - i) : i;

            System.out.printf("i = %d, btnNumber = %d%n", i, btnNumber);
            buttons[btnNumber - 1] = new JButton("label " + btnNumber);
            //buttons[btnNumber - 1].setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            buttons[btnNumber - 1].setBorder(BorderFactory.createEtchedBorder());
            buttons[btnNumber - 1].setOpaque(true);
            buttons[btnNumber - 1].setBackground(Color.white);

            //Puts the player 1 piece on button 1,3,5,7,9 and player 2 piece on button 2,4,6,8,10 
            if ((btnNumber - 1) < 10) 
            { 
                if (((btnNumber - 1) % 2) == 0) 
                { 
                    buttons[btnNumber - 1].setIcon(piece1); 
                } 
                else 
                { 
                    buttons[btnNumber - 1].setIcon(piece2); 
                } 
            } 
            centerPanel.add(buttons[btnNumber - 1]); 
        } 

//以下是我正在尝试做的,我知道这是不正确的。

public void move()
{
Move = dice.getDiceResult();
int buttonClicked = 0;

if(playerOneTurn =true)
{
buttonclicked + diceResult();
}

//修改过

public class MyActionListener implements ActionListener {
Dice dice;
private boolean playerOneTurn = true;
private boolean playerTwoTurn = false;
    @Override
    public void actionPerformed(ActionEvent e) 
{
    String num = e.getActionCommand();
    int index = Integer.parseInt(num);
    int move = dice.getDiceResult();
    int positionLanding = 0;

    if(playerOneTurn = true)
    {
        positionLanding = index + move;
        positionLanding.setIcon("piece1");//how can I set the image Icon to this position?
    }

}
}

最佳答案

1) putClientProperty

buttons[i][j].putClientProperty("column", i);
buttons[i][j].putClientProperty("row", j);
buttons[i][j].addActionListener(new MyActionListener());

getClientProperty

public class MyActionListener implements ActionListener {

@Override
public void actionPerformed(ActionEvent e) {
    JButton btn = (JButton) e.getSource();
    System.out.println("clicked column " + btn.getClientProperty("column")
            + ", row " + btn.getClientProperty("row"));
}

2) ActionCommand

关于java - 返回点击按钮的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10416104/

相关文章:

java - 带有 java.util.Calendar 的非标准语言环境

java - 从 python 中编译 java

java - JTable 构造函数可以接受数组以外的其他数据结构吗?

java - 是否可以将按钮添加到以编程方式设置的框架布局?

c++ - 初始化一个可变大小的数组

javascript - 勾选随机开始

java - Swing 可以告诉我是否有 Activity 的工具提示吗?

java - Eclipse Java项目错误: cannot resolve declaration in swing

java - 接受连接未设置 "timeout time"时接受超时异常

java - 来自 Java API 的 Elasticsearch 2.0 script_score