for(i=0; i<16; i++){
images[i]=new ImageIcon(getClass()
.getResource("/images/1 ("+i+").jpg"));
}
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();
label[n].setIcon((images[i*buttons.length+j]));
buttons[i][j].add(label[n]);
label[n].setVisible(false);
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(); //i want to put label[n] into array?
if((pressedButton.getIcon() == null)){
label[n].setVisible(true);
open=open++;
} else {
//pressedButton.setIcon(null);
}
}
if (open==1){
opens[0].setVisible(false);
opens[1].setVisible(false);
}
}
hello friends.i am making a memory game, if buttons have same icon, they will stay open.
i made frame in it panel, in it buttons and each button has label. If facing is true and user click, they will open by setvisible(true)
but in void actionperformed, how can i take label[n]? Not button[][]?
label[n].setIcon((images[i*buttons.length+j]));
i think error is that.is not it correct? because it doesnot execute.
edit after suggestions:
for(i=0; i<16; i++){
images[i]=new ImageIcon(getClass().getResource("/images/1 ("+i+").jpg"));
} //adding images to local variables
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();
//buttons[i][j].setIcon((images[i*buttons.length+j]));
//if i make this code, all icons are displayed at first?
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();
if(pressedButton.getIcon() == null){
pressedButton.setIcon((images[i*buttons.length+j]));
} else {
pressedButton.setIcon(null);
}
}
}
I made this code how you suggested. but now images dont display and clicks doesnot work.