简体   繁体   English

JButton的gridLayout,每个JButton的actionListener

[英]gridLayout of JButtons, actionListener for each JButton

I have a gridLayout of JButtons. 我有一个JButtons的gridLayout。 I'd like to distinguish every JButton from each other in the actionPerformed function. 我想在actionPerformed函数中将每个JButton彼此区分开。 I don't want to "name" each JButton. 我不想为每个JButton命名。 The user press a JButton randomly. 用户随机按下JButton。 Is there any method to know which button has been pressed? 有什么方法可以知道按下了哪个按钮? It is possible? 有可能的?

    [....]
    tUsuariCPU = new JButton[mida][mida];
    for (int i=0;i<size;i++){
        for (int j=0;j<size;j++){
            JButton temp = new JButton();
            tUsuariCPU[i][j] = temp; 
            temp.addActionListener(this);
            panel.add(temp);
        }
      }
   }

   public void actionPerformed(ActionEvent e) {}
          [....]

   }

If you wish to use a single ActionListener , you can check which Component fired the event by using the getSource button and comparing the instance to the JButton instances. 如果希望使用单个ActionListener ,则可以通过使用getSource按钮并将实例与JButton实例进行比较来检查哪个组件触发了事件。 Below uses a loop to loop over the 2D array of JButtons: 下面使用一个循环遍历JButton的2D数组:

public void actionPerformed(ActionEvent e) {}
    for ( int i = 0; i < tUsuariCPU.length; i++ ){
        for ( int j = 0; j < tUsuariCPU[i].length; j++ ){
            if ( e.getSource() == tUsuariCPU[i][j] ){
                //do something
            }
        }
    }
}

Alternatively, you can add a single ActionListener per button, or set the ActionCommand of the JButton and use this value to determine which JButton fired the event ( e.getActionCommand().equals(myButton.getActionCommand()) ) 或者,您可以为每个按钮添加一个ActionListener,或设置JButton的ActionCommand并使用此值确定哪个JButton触发了事件( e.getActionCommand().equals(myButton.getActionCommand())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM