Addactionlistener不接受参数 [英] Addactionlistener doesnot take parameter
本文介绍了Addactionlistener不接受参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Concentration extends JFrame implements ActionListener {
private JButton buttons[][]=new JButton[4][4];
int i,j,n;
public Concentration() {
super ("Concentration");
JFrame frame=new JFrame();
setSize(1000,1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel=new JPanel(new GridLayout(4,4));
panel.setSize(400, 400);
for( i=0; i<buttons.length; i++){
for (j=0; j<buttons[i].length;j++){
n=i*buttons.length+buttons[i].length;
buttons[i][j]=new JButton();
panel.add(buttons[i][j]);
buttons[i][j].addActionListener(this);
}
}
add(panel);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
buttons[i][j].setIcon(new ImageIcon(
getClass().getResource("/images/2.jpg")));
}
public static void main(String args[]){
new Concentration();
}
}
这是我的代码。我在做记忆游戏。我想这样做,每次点击一个按钮,该按钮显示图像但是
This is my code. I am making memory game. I want to make that, each time clicked a button, that button shows image but
buttons[i][j].addActionListener(this);
其中,methot不能带i和j并且不显示任何图像。
in that, methot can not take i and j and doesnot show any image.
但是例如当我做的时候
buttons[2][2].addActionListener(this);
它仅显示在2x2中。图片。我该怎么做才能解决这个问题?
it shows only in 2x2 . image. What can i do to solve that?
推荐答案
可能的解决方案:
- 在ActionListener中,遍历按钮数组以查看数组中哪个JButton与按下的按钮匹配,通过调用
e.getSource()$ c $获得c>
- 给你的JButton actionCommand字符串对应于i和j
- 创建一个单独的ActionListener实现类,它有i和j字段,可以是通过构造函数设置,并为每个按钮提供一个唯一的ActionListener,其中包含i和j set。
这篇关于Addactionlistener不接受参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文