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(); } }
这是我的代码。 我在做记忆游戏。 我想这样做,每次点击一个按钮,该按钮显示图像但是
buttons[i][j].addActionListener(this);
在那,methot不能采取我和j,并没有显示任何图像。
但是比如说我做的时候
buttons[2][2].addActionListener(this);
它只显示2×2。 图片。 我该怎么做才能解决这个问题?
可能的解决方案:
- 在ActionListener内部,遍历按钮数组以查看数组中哪个JButton与按下的按钮匹配,通过调用
e.getSource()
- 给你的JButton actionCommand字符串对应于i和j
- 创建一个单独的ActionListener实现类,该类具有可以通过构造函数设置的i和j字段,并为每个按钮提供一个具有i和j set的唯一ActionListener。
试试这段代码:
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); } } }
直接formsEventObject javadoc:
public Object getSource()
事件最初发生的对象。
返回:事件最初发生的对象。
这意味着不需要知道按下按钮的数组索引,因为它可以通过getSource()
方法获知。