从 ActionListener 获取按钮名称?

发布于 2024-12-11 17:57:33 字数 958 浏览 0 评论 0原文

我已经在互联网上搜索过,但找不到答案:

我使用 for 循环创建 36 个名为 a1、a2 等的按钮,并同时为每个按钮分配一个唯一的操作命令。

后来我想从 actionPerformed(ActionEvent e) 方法中获取按钮的名称。

我可以很容易地获得 ActionCommand,但我还需要按钮的名称。

非常感谢任何帮助!

编辑:

这是我正在使用的代码:

String letters[] = {"0", "a", "b", "c", "d", "e", "f"};
JButton btn[] = new JButton[35];
int count = 0;


for (int f=1; f < 7;f++){

        for (int i=1; i < 7;i++){
            btn[i] = new JButton(letters[f]+i, cup);
            System.out.println(btn[i]));
            mainGameWindow.add(btn[i]);
            btn[i].addActionListener(this);
            String StringCommand = Integer.toString(randomArrayNum());
            btn[i].setActionCommand(StringCommand);
            count++;
            if(count == 18){
                generateArray();
            }

        }

}

这为您提供了 6x6 网格的 36 个按钮,分别为 a1-6、b1-6、c1-6 等,

一旦创建按钮,我似乎无法控制它们这样,我无法分配图标或获取按钮的名称。

提前致谢。

I have scoured the internet but can't find an answer to this :

I'm using a for loop to create 36 buttons called a1, a2, etc. and assigning each of them a unique Action Command at the same time.

Later on I wanted to get the name of the button from the actionPerformed(ActionEvent e) method.

I could get the ActionCommand easy enough, but I need the name of the button as well.

Any help much appreciated!

Edit:

Here is the code I'm using:

String letters[] = {"0", "a", "b", "c", "d", "e", "f"};
JButton btn[] = new JButton[35];
int count = 0;


for (int f=1; f < 7;f++){

        for (int i=1; i < 7;i++){
            btn[i] = new JButton(letters[f]+i, cup);
            System.out.println(btn[i]));
            mainGameWindow.add(btn[i]);
            btn[i].addActionListener(this);
            String StringCommand = Integer.toString(randomArrayNum());
            btn[i].setActionCommand(StringCommand);
            count++;
            if(count == 18){
                generateArray();
            }

        }

}

This gives you 36 buttons for a 6x6 grid that go a1-6, b1-6, c1-6 etc

I just can't seem to control the buttons once I've created them this way, I can't assign icons or get the name of the button.

Thanks in Advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

狼性发作 2024-12-18 17:57:34
JButton btnClear = new JButton("clear");
btnClear.addActionListener(this);
btnClear.setName("clear");

//..............
//..............

public void actionPerformed(ActionEvent e) {
   JButton o = (JButton)e.getSource();
   String name = o.getName();
   if (name == "clear")
   {
       euroMillText.setText("");
   }
   else if (name == "eumill")
   {
       getLottoNumbers();
   }
   //JOptionPane.showMessageDialog(null,name);      
}   
JButton btnClear = new JButton("clear");
btnClear.addActionListener(this);
btnClear.setName("clear");

//..............
//..............

public void actionPerformed(ActionEvent e) {
   JButton o = (JButton)e.getSource();
   String name = o.getName();
   if (name == "clear")
   {
       euroMillText.setText("");
   }
   else if (name == "eumill")
   {
       getLottoNumbers();
   }
   //JOptionPane.showMessageDialog(null,name);      
}   
是伱的 2024-12-18 17:57:34

Map 中保留按钮的引用

String letters[] = {"0", "a", "b", "c", "d", "e", "f"};
JButton btn;
int count = 0;

HashMap<String,JButton> buttonCache = new HashMap<String,JButton>();


for (int f=1; f < 7;f++){

    for (int i=1; i < 7;i++){
        btn = new JButton(letters[f]+i, cup);
        mainGameWindow.add(btn[i]);
        btn.addActionListener(this);
        String stringCommand = Integer.toString(randomArrayNum());
        btn.setActionCommand(stringCommand);
        buttonMap.put(stringCommand,btn);
        count++;
        if(count == 18){
            generateArray();
        }

    }

} 

然后,在您的 ActionListener 中,从命令中获取按钮:

public void actionPerformed(ActionEvent e) {
    String command = ((JButton) e.getSource()).getActionCommand();
    JButton button = buttonCache.get(command);
    if (null != button) {
        // do something with the button
    }
}

编辑

五年后重新访问此答案,我不知道为什么我建议使用 HashMap :P

此代码执行完全相同的操作,没有第三方 Map

String letters[] = {"0", "a", "b", "c", "d", "e", "f"};
int count = 0;

for (int f=1; f < 7;f++){
    for (int i=1; i < 7;i++) {
        String stringCommand = Integer.toString(randomArrayNum());
        Button btn = new JButton(letters[f]+i, cup);

        btn.setActionCommand(stringCommand);
        btn.addActionListener(this);
        mainGameWindow.add(btn[i]);

        // NOTE : I have no idea what this is for...
        count++;
        if(count == 18){
            generateArray();
        }
    }
}

ActionListener 中...

public void actionPerformed(ActionEvent e) {
    JButton button = (JButton) e.getSource();
    String command = button.getActionCommand();

    // do something with the button
    // the command may help identifying the button...
}

Keep a reference of the buttons in a Map

String letters[] = {"0", "a", "b", "c", "d", "e", "f"};
JButton btn;
int count = 0;

HashMap<String,JButton> buttonCache = new HashMap<String,JButton>();


for (int f=1; f < 7;f++){

    for (int i=1; i < 7;i++){
        btn = new JButton(letters[f]+i, cup);
        mainGameWindow.add(btn[i]);
        btn.addActionListener(this);
        String stringCommand = Integer.toString(randomArrayNum());
        btn.setActionCommand(stringCommand);
        buttonMap.put(stringCommand,btn);
        count++;
        if(count == 18){
            generateArray();
        }

    }

} 

Then, in your ActionListener, get the button back from the command :

public void actionPerformed(ActionEvent e) {
    String command = ((JButton) e.getSource()).getActionCommand();
    JButton button = buttonCache.get(command);
    if (null != button) {
        // do something with the button
    }
}

Edit

Revisiting this answer over five years later, I have no idea why I suggested a HashMap :P

This code does the exact same thing, no third party Map :

String letters[] = {"0", "a", "b", "c", "d", "e", "f"};
int count = 0;

for (int f=1; f < 7;f++){
    for (int i=1; i < 7;i++) {
        String stringCommand = Integer.toString(randomArrayNum());
        Button btn = new JButton(letters[f]+i, cup);

        btn.setActionCommand(stringCommand);
        btn.addActionListener(this);
        mainGameWindow.add(btn[i]);

        // NOTE : I have no idea what this is for...
        count++;
        if(count == 18){
            generateArray();
        }
    }
}

in the ActionListener...

public void actionPerformed(ActionEvent e) {
    JButton button = (JButton) e.getSource();
    String command = button.getActionCommand();

    // do something with the button
    // the command may help identifying the button...
}
江挽川 2024-12-18 17:57:34
String buttonText = ((JButton) e.getSource()).getText()
String buttonText = ((JButton) e.getSource()).getText()
夜夜流光相皎洁 2024-12-18 17:57:34

将按钮存储在数组中并使用 e.getSource() 找出它是哪个...

Private JButton[] buttons;

public void actionPerformed(ActionEvent e) {
    int index = -1;

    for (int i = 0; i < buttons.length; i++) {
        if (e.getSource() == buttons[i]) {
            index = i;
            break;
        }
    }

    if (index == -1) {
        // e didn't come from the buttons
    } else {
        // do stuff
    }
}

Store your buttons in an array and use e.getSource() to figure out which it was...

Private JButton[] buttons;

public void actionPerformed(ActionEvent e) {
    int index = -1;

    for (int i = 0; i < buttons.length; i++) {
        if (e.getSource() == buttons[i]) {
            index = i;
            break;
        }
    }

    if (index == -1) {
        // e didn't come from the buttons
    } else {
        // do stuff
    }
}
℡Ms空城旧梦 2024-12-18 17:57:34

您还有另外三个选择

1) 通过实现

  • JButton[] 按钮;

  • ArrayList;按钮;

但仍然需要确定从循环中按下哪个 JButton

2) 向每个 JButton 添加单独的 ActionListener

    myButton.addActionListener(new java.awt.event.ActionListener() {

        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            myButtonActionPerformed(evt);
        }

        private void myButtonActionPerformed(ActionEvent evt) {
            // some Action
        }
    });

3)将 javax.swing.Action 添加到 JButton< /代码>

you have another three choices

1) by implements

  • JButton[] buttons;

  • ArrayList<JButton> buttons;

but still is required to determine which JButton is pressed from the loop

2) add to each JButton separate ActionListener

    myButton.addActionListener(new java.awt.event.ActionListener() {

        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            myButtonActionPerformed(evt);
        }

        private void myButtonActionPerformed(ActionEvent evt) {
            // some Action
        }
    });

3) add javax.swing.Action to the JButton

羁客 2024-12-18 17:57:34

您可以使用设置图标

((JButton)actionEvent.getSource()).setIcon("imageName.png");

//to get the name of button you can use
ArrayList<String> buttonNames;
buttonNames.add("button"+f+i);

you can set the Icon by using

((JButton)actionEvent.getSource()).setIcon("imageName.png");

//to get the name of button you can use
ArrayList<String> buttonNames;
buttonNames.add("button"+f+i);
笔落惊风雨 2024-12-18 17:57:34

另一个可能有效的选项是使用按钮的客户端属性。 JComponent 基类提供设置/获取任意属性的功能:

Object JComponent.getClientProperty(Object key)
void JComponent.putClientProperty(Object key, Object value)

因此您可以做的是在组件上设置应用程序定义的属性值,然后在 ActionListener 方法内询问该属性值(只需检查事件源是否为 JComponent)。

Another option that might work is to use the client properties of the button. The base JComponent class provides for setting/getting arbitrary properties:

Object JComponent.getClientProperty(Object key)
void JComponent.putClientProperty(Object key, Object value)

So what you can do is set an application defined property value on the component and then interrogate that property value inside the ActionListener method (just checking that source of the event is a JComponent).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文