Reputation: 53
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);
}
}
I want to hold 2 clicked JButton
and then close or stay open. How can i hold in array or something else?
My array holding is wrong?
With this code, i can open unlimited images and none of them is getting closed.
Upvotes: 0
Views: 582
Reputation: 109823
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
load Images to local variables as Icon/ImageIcons, to avoids any FileIO meaning code line pressedButton.setIcon(new ImageIcon(getClass().getResource("/images/2.jpg")));
add this Icon/ImageIcons
to JButton.setPressedIcon(myIcon),
then there is useless code line to reset Icon
back with pressedButton.setIcon(null);
Upvotes: 1