【发布时间】:2013-09-23 18:03:51
【问题描述】:
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);
}
}
你好朋友。我正在做一个记忆游戏,如果按钮有相同的图标,它们将保持打开状态。
我在它的面板中制作了框架,在它的按钮中,每个按钮都有标签。如果 face 为 true 并且用户点击,他们将通过 setvisible(true) 打开
但是在 void actionperformed 中,我该如何接受label[n]? Not button[][]?
label[n].setIcon((images[i*buttons.length+j]));
我认为是错误。它不正确吗?因为它不执行。
根据建议编辑:
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);
}
}
}
我按照您的建议编写了此代码。但是现在图像不显示并且点击不起作用。
【问题讨论】:
-
你有什么异常吗?到底发生了什么?
-
我删除了我认为可疑的代码,它显示的图像没有标签。在这段代码中,当我运行时,什么也没有发生,没有错误,没有警告。只是进程中的一个jawa.exe,等待结束
-
请再看一遍,我编辑了问题
-
@clarasampson:您需要创建并发布一个sscce,这是一个简单的程序,我们可以不加改动地编译和运行它并显示您的问题。