Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Addactionlistener不接受参数_Java_Image_Swing_Jbutton_Actionlistener - Fatal编程技术网

Java Addactionlistener不接受参数

Java Addactionlistener不接受参数,java,image,swing,jbutton,actionlistener,Java,Image,Swing,Jbutton,Actionlistener,在这种情况下,Method不能拍摄i和j,也不能显示任何图像 但举个例子,当我这样做的时候 buttons[i][j].addActionListener(this); 它只在2x2中显示。形象。我能做些什么来解决这个问题?可能的解决方案: 在ActionListener内部,遍历按钮数组,查看数组中的哪个JButton与按下的按钮匹配,通过调用e.getSource() 给出对应于i和j的JButtons actionCommand字符串 创建一个单独的ActionListener实现类

在这种情况下,Method不能拍摄i和j,也不能显示任何图像

但举个例子,当我这样做的时候

 buttons[i][j].addActionListener(this);
它只在2x2中显示。形象。我能做些什么来解决这个问题?

可能的解决方案:

  • 在ActionListener内部,遍历按钮数组,查看数组中的哪个JButton与按下的按钮匹配,通过调用
    e.getSource()
  • 给出对应于i和j的JButtons actionCommand字符串
  • 创建一个单独的ActionListener实现类,该类包含可以通过构造函数设置的i和j字段,并为每个按钮提供一个唯一的ActionListener,其中包含i和j集
尝试以下代码:

 buttons[2][2].addActionListener(this);
直接表单javadoc:

public Object getSource()

事件最初发生在其上的对象

返回: 事件最初发生在其上的对象


这意味着不需要知道被按下按钮的数组索引,因为它可以通过
getSource()
方法知道。

@nIcEcOw我有+1(认为是你的,谢谢),但还有一个-1,我想知道为什么。你从我这里得到了一个1+。最好用解释来说明getSource()方法的作用。谢谢。哦,我明白了。谢谢大家!:)@是的,我会继续微笑:-)
 buttons[2][2].addActionListener(this);
public void actionPerformed(ActionEvent e) {
    if(e.getSource() instanceof JButton){
        JButton pressedButton = (JButton) e.getSource();
        if(pressedButton.getIcon() == null){
            pressedButton.setIcon(new ImageIcon(getClass().getResource("/images/2.jpg")));
        } else {
            pressedButton.setIcon(null);
        }
    }
}