Java按钮动作命令

Java按钮动作命令

本文介绍了Java按钮动作命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java创建一个简单的扫雷游戏。大小为9x9。

I'm creating a simple Minesweeper game in Java. Size 9x9.

我创建了一个 JPanels 数组和一个按钮数组;我将每个按钮添加到各自的 JPanel 中。然后我将 JPanels 添加到 JFrame

I create an array of JPanels and an array of buttons; I add each button to its respective JPanel. then i add the JPanels to the JFrame.

我如何区分动作事件的每个按钮?

How do i distinguish between each button on the action event?

以下是我的一些代码:

int gridx = 9;
int gridy = 9;
JButton[] buttons = new JButton[gridx*gridy];
JPanel[] jpanels = new JPanel[gridx*gridy];

public Minesweeper(){

    super("Minesweeper");


    setLayout(new GridLayout(9,9));
    JPanel panel = new JPanel();
    int i = 0;
    for(i = 0; i<gridx*gridy; i++){
        jpanels[i] = new JPanel();
        buttons[i] = new JButton();
        buttons[i].addActionListener(buttonEvent);
        jpanels[i].setLayout(new GridLayout(1,1));
        jpanels[i].add(buttons[i]);
        add(jpanels[i]);
    }
    //buttons[67].setEnabled(false);
    setSize(300,300);
    setVisible(true);
}

我能想到的唯一方法是在按钮上添加文本因此:

The only way i can think about doing this is adding text to the button like so:

    buttons[i] = new JButton(i);

然后调用 getActionCommand()但我没有希望文本显示在按钮上。还有其他想法吗?

Then calling getActionCommand() but i dont want text to show up on the button. Any other ideas?

推荐答案

您可以使用。

在您的循环中:

buttons[i].setActionCommand(i+"");

然后,当您返回 i 时,您使用 getActionCommand

Then you'll get i back when you use getActionCommand

请注意,我确实在另一个答案的注释中提到要创建一个新类我的我的扩展了JButton ,我认为这是一个更好,更完整的解决方案。但是,这可以很快完成工作。

Note I did mention in a comment on another answer that I would create a new class Mine which extends JButton which I believe to be a better and more complete solution. This however gets the job done rather quickly.

这篇关于Java按钮动作命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:28