0
public class Concentration extends JFrame implements ActionListener{
    private JButton buttons[][]=new JButton[4][4];
    int i,j,n;
    public int open=0;
    private JButton  opens[]=new JButton[1];
    public ImageIcon  images[] = new ImageIcon[20];

    public Concentration() {

        super ("Concentration");    
        JFrame frame=new JFrame();
        setSize(1000,1000);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel=new JPanel(new GridLayout(4,4));
        panel.setSize(400, 400);

        for(i=0; i<16; i++){

             images[i]=new ImageIcon(getClass().getResource("/images/1 ("+i+").jpg"));

    }

    //shuffle

        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(images[i*buttons.length+j]);

                panel.add(buttons[i][j]);
                buttons[i][j].addActionListener(this);

            }
        }
        add(panel);
        pack();
        setVisible(true);

    }


    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);
        }
    }

    public static void main(String args[]){
        new Concentration();
    }
}

我想要一个记忆游戏。如果两个按钮相同,它将保持打开状态。但是当我执行这个时,所有图像都是打开的。WHwn 单击,它们仍然处于打开状态。

我哪里错了?

我使用 imageicon 而不是图像,这有关系吗?

4

0 回答 0