我创建了JButton,当我单击它们消失时,我想要的是照片占据空白并显示出来。
这是我的存储卡游戏的一部分,但是我找不到在代码中实现此目的的方法。这就是我的按钮侦听器到目前为止所做的
private class Disappear implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int count =0;
for(int i=0; i<52;i++)
{
if(!buttons[i].isVisible())
{
count+=1;
}
}
if(count<2)
((JButton)e.getSource()).setVisible(false);
if(count==2)
{
for(int i=0; i<52;i++)
{
if(!buttons[i].isVisible())
{
buttons[i].setVisible(true);
}
}
}
}
}
最佳答案
您可以尝试使用JToggleButton代替常规按钮。每当按下JToggleButton时,都会显示其他/新图像:
class MemGame implements ActionListener(){
ImageIcon img = new ImageIcon("Back.png"); /* Back of the card */
ImageIcon img2 = new ImageIcon("D1.png"); /* Card face */
/* Constructor */
MemGame(){
JFrame jfrm = new JFrame("Memory Game");
jfrm.setSize(220, 250);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfrm.setLayout(new FlowLayout());
JToggleButton jt1 = new JToggleButton(img);
jt1.addActionListener(this);
jfrm.getContentPane().add(new JLabel("Select a card"));
jfrm.getContentPane().add(jt1);
jfrm.setVisible(true);
}
public void actionPerformed(ActionEvent ae){
JToggleButton jt = (JToggleButton)ae.getSource();
if (!jt.isSelected()) jt.setIcon(img);
else jt.setIcon(img2);
}
}
从这里只需添加逻辑即可处理多张按下的卡,等等。
结果
Before button is pressed
After button is pressed
信用到期的地方:
卡片图片来源:whttps://thenounproject.com/term/ace-of-diamonds/170620/
和whttps://thenounproject.com/term/playing-card/146000/