public int open=0;
private JButton opens[]=new JButton[1];
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);
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JButton){
JButton pressedButton = (JButton) e.getSource();
opens[open]=(JButton) e.getSource();
if((pressedButton.getIcon() == null)){
pressedButton.setIcon(new ImageIcon(getClass().getResource("/images/2.jpg")));
open=open++;
} else {
//pressedButton.setIcon(null);
}
}
if (open==1){
opens[0].setIcon(null);
opens[1].setIcon(null);
}
}
我想按住 2 个 JButton
单击,然后关闭或保持打开状态。我如何保存数组或其他东西?
我的数组持有错误?
使用此代码,我可以打开无限的图像,并且它们都不会被关闭。
最佳答案
I am trying to hold 2 images in array, then it will close them if they are not same. It is a memory game. Only 2 images can be opened
将图像加载到局部变量 Icon/ImageIcons ,以避免任何 FileIO 含义代码行
pressedButton.setIcon(new ImageIcon(getClass().getResource("/images/2.jpg")));
将此
Icon/ImageIcons
添加到JButton.setPressedIcon(myIcon) ,然后有无用的代码行用
pressedButton.setIcon(null);
重置Icon
回来
关于java - 将 e.getsource 中的 jbutton 保存在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18959561/