如何获取JButton的特定ID? [英] How to get specific ID for a JButton?

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

问题描述

我正在尝试构建一个使用3x3网格按钮(使用Java Swing)的程序,所以我使用GridLayout和循环来初始化它以创建按钮:

I'm trying to build a program that utilizes a 3x3 grid of buttons (using Java Swing), so I initialize it with a GridLayout and a loop to create the buttons:

     panel.setBorder(BorderFactory.createEmptyBorder(3,3,5,5))
     panel.setLayout(new GridLayout(3,3,10,10));

    String[] buttons = {"Top Left", "Top Middle", "Top Right", "Middle Left", "Middle", "Middle Right", "Bottom Left", "Bottom Middle", "Bottom Right"};

    for(int i = 0; i < buttons.length; i++) {
        buttray[i] = new JButton(buttons[i]);
        panel.add(buttray[i]);
        buttray[i].addActionListener(this);
    }

按钮加载得很好,但我不明白如何使用ActionListeners来区分按钮。当我从打印输出中检查paramString()方法时,每个按钮都给出相同的修饰符:

The buttons load just fine, but I do not understand how to use ActionListeners to differentiate between the buttons. When I check the paramString() method from the printout, each button gives the same modifier:

Top Left
ACTION_PERFORMED,cmd=Top Left,when=1431640106712,modifiers=Button1
Top Middle
ACTION_PERFORMED,cmd=Top Middle,when=1431640107566,modifiers=Button1
Top Right
ACTION_PERFORMED,cmd=Top Right,when=1431640107978,modifiers=Button1

此修饰符值是否作为按钮的标识符,如果是这样,我该怎么改呢?

Does this modifier value act as the button's identifier, and if so, how do I change it?

推荐答案

有多种方法可以区分哪个按钮触发了ActionEvent:

There are multiple ways to distinguish which button fired the ActionEvent:


  1. 设置/获取每个按钮的动作命令(例如 if(e.getActionCommand()。equals(Top Left) )

  2. 使用==比较实例(例如 if(e.getSource()== buttray [0])

  3. 获取JButton的文本(例如 if(e.getSource()。getText()。equals(Top Left)

  4. 设置/获取名称JButton(例如 if(e.getSource()。getName()。equals(Top Left)

  5. 添加一个不同的ActionListener到每个按钮(换句话说1:1监听器到按钮)

  6. ...也许更多的方法将添加到下面的评论部分。

  1. Set/get the action command of each button (eg if (e.getActionCommand().equals("Top Left"))
  2. Use == to compare instances (eg if (e.getSource() == buttray[0] ))
  3. Get the text of the JButton (eg if (e.getSource().getText().equals("Top Left"))
  4. Set/get the name of the JButton (eg if (e.getSource().getName().equals("Top Left"))
  5. Add a different ActionListener to each button (in other words 1:1 Listener to button)
  6. ...and perhaps more ways will be added in the comments section below.

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

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