Swing如何识别哪个jbutton用户点击

Swing How to identify which jbutton user is clicking

我正在 java 中创建一个座位预订系统......我已经创建了一个 jbuttons 数组。有什么方法可以确定单击了哪个按钮,或者我可以在单击按钮时获取按钮的索引。

    for(int i=0; i<20; i++){
    btn1[i] = new JButton(String.valueOf(i+1));
    btn1[i].setPreferredSize(new Dimension(60, 30));
    btn1[i].setBackground(Color.green);
    panel.add(btn1[i]);

}

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

  1. Set/get每个按钮的动作命令(eg if (e.getActionCommand().equals("Button Name"))
  2. 使用==比较实例(例如if (e.getSource() == buttray[0] ))
  3. 获取 JButton 的文本(例如 if (e.getSource().getText().equals("Button Name"))
  4. Set/get JButton 的名称(例如 if (e.getSource().getName().equals("Button Name"))

在你的情况下你有一个名字..所以#4 应该在你的按钮事件中工作

btn1[i].addActionListener(new ActionListener()
{
  public void actionPerformed(ActionEvent e)
  {
    String bName = e.getSource().getText()
  }
});