繁体   English   中英

当它是具有相同动作侦听器的JButton数组时,单击哪个Jbutton

[英]Which Jbutton is being clicked, when it is an array of JButtons with the same actionlistener

我正在为 瓷砖拼图

我有一个Jbuttons数组,其文本设置为当前包含的数字。

我有命令

evt.getActionCommand();

这将返回jbutton中的字符串,但是我需要的是按下数组中的jbutton,因此我可以使用该值来对应我的Node类,后者使用2d数组来跟踪Node值

新代码归功于充满鳗鱼的气垫船

for (int i = 0; i < tileButtons.length; i++) {
        if (source == tileButtons[i]) {
            // the current i and j are your array row and column for the source button
            System.out.println("the " + i + " button");
        }
    }

您可以通过evt.getSource()获得实际的按钮。 这将返回实际按下的JButton对象。 然后,如果将按钮固定在数组中,则可以轻松地遍历数组,直到找到与源匹配的按钮。

Object source = evt.getSource();
for (int i = 0; i < buttonArray.length; i++) {
   for (int j = 0; j < buttonArray[i].length; j++) { 
     if (source == buttonArray[i][j]) {
        // the current i and j are your array row and column for the source button
     }
   }
}

警告中的注意事项: ActionEvent#getSource()方法并不总是返回JButton,但会再次返回导致ActionListener触发的原因,这可以是AbstractButton,JMenuItem,SwingTimer的任何子级,也可能是其他子级。

从该方法的参数“ e”上调用getSource()。

public void actionPerformed(ActionEvent e);

您可以使用HashMap将每个按钮与一些自定义数据对象相关联。 这是一个实践该想法的测试程序。

public class ButtonTest implements ActionListener{
    public static void main(String[] args){
        new ButtonTest();
    }
    HashMap<JButton, String> buttonToLocationMap;
    public ButtonTest(){
        JFrame frame = new JFrame();
        frame.setLayout(new GridLayout());
        frame.setVisible(true);
        frame.setSize(300, 300);
        buttonToLocationMap = new HashMap<>();

        JButton button1 = new JButton("Button1");
        button1.addActionListener(this);
        buttonToLocationMap.put(button1, "Replace the value type of this hashmap with any object associated with button1");
        frame.add(button1);


        JButton button2 = new JButton("Button2");
        button2.addActionListener(this);
        buttonToLocationMap.put(button2, "Replace the value type of this hashmap with any object associated with button2");
        frame.add(button2);     
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(buttonToLocationMap.get((JButton)e.getSource()));
    }
}

暂无
暂无

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

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