-2
           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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
clara sampson
  • 11
  • 1
  • 7

2 Answers2

2

I think this post is related to this question. Maybe an assignment?

Couple of tips:

label[n].setIcon((images[i*buttons.length+j]));

How many images do you have in images array? A quick math would say that if you have for instance a 4x4 array then you'll need i*buttons.lenght+j == 4*4+4 == 20 images at last iteration. And you only would need i*j/2 == 8 images, assuming is a pair match game.

if buttons have same icon, they will stay open. i made frame in it panel, in it buttons and each button has label.

Why do you need labels? I think if two button matches you can disable those buttons so user won't be able to click them again and dispatch an actionPerformed event.

If it's not strictly necessary use arrays, you could use ArrayList instead and get benefits of its methods.

Update

I post this code because I think you still stuck using arrays. I just want to show you that there's no need to use them to keep references, you just need think a little more under objects paradigm and delegate this task to appropriate object.

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;


public class Demo {    
    /* 
     * This variable will point to a pressed button to keep reference.
     */
    JButton _alreadyPressedButton = null;

    /**
     * Initializes the GUI
     */
    private void initGUI(){
        /*
         * Create needed icons - As this example uses 6 buttons, then I need 3 icons 
         */
        ImageIcon icon1 = (ImageIcon) UIManager.getIcon("OptionPane.errorIcon");
        ImageIcon icon2 = (ImageIcon) UIManager.getIcon("OptionPane.informationIcon");
        ImageIcon icon3 = (ImageIcon) UIManager.getIcon("OptionPane.warningIcon");
        /*
         * Make a list with 6 icons (add each icon twice)
         */
        List<ImageIcon> iconsList = new ArrayList<>();
        iconsList.add(icon1);
        iconsList.add(icon1);
        iconsList.add(icon2);
        iconsList.add(icon2);
        iconsList.add(icon3);
        iconsList.add(icon3);
        Collections.shuffle(iconsList); /* Shuffle the list */

        ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if(e.getSource() instanceof JButton){                    
                    final JButton pressedButton = (JButton) e.getSource();              
                    /* 
                     * Execute this code in a SwingWorker to prevent block EDT at "Thread.sleep(500)" line
                     * Google for EDT (Event Dispatch Thread)
                     */
                    SwingWorker sw = new SwingWorker() {
                        @Override
                        protected Object doInBackground() throws Exception {
                            if(_alreadyPressedButton != pressedButton){
                                pressedButton.setIcon(pressedButton.getPressedIcon());

                                if(_alreadyPressedButton != null){ 
                                    Thread.sleep(500);
                                    if(_alreadyPressedButton.getIcon() == pressedButton.getIcon()){
                                        _alreadyPressedButton.setEnabled(false);
                                        pressedButton.setEnabled(false);
                                    } else {
                                        _alreadyPressedButton.setIcon(null);
                                        pressedButton.setIcon(null);
                                    }
                                    _alreadyPressedButton = null;
                                } else {
                                    _alreadyPressedButton = pressedButton;
                                }

                            }
                            return null;
                        }

                    };

                    sw.execute();
                }
            }
        };

        JPanel panel = new JPanel(new GridLayout(3, 2));
        panel.setPreferredSize(new Dimension(200, 200));

        for(ImageIcon icon : iconsList){
            JButton button = new JButton();
            button.setPressedIcon(icon);
            button.addActionListener(actionListener);
            panel.add(button);
        }

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                 new Demo().initGUI();
            }
        });        

    }
}
Community
  • 1
  • 1
dic19
  • 17,821
  • 6
  • 40
  • 69
  • but how to hide and show images, i thought it would be easy with jlabels to show images without jbutton in that question pressedButton.setIcon(null); but when click again, how to go to index? – clara sampson Sep 23 '13 at 18:36
  • You can use `JButton.setIcon()` method. For example: I click a button, the icon is set so I can see the image. Then I click another button. If both images match then disable both buttons. If not then set icon to `null` for both buttons. – dic19 Sep 23 '13 at 18:40
  • after doing null, how will it find the index image of that button?is not removed? – clara sampson Sep 23 '13 at 18:45
  • @clarasampson my bad. I was thinking you can use `JButton.setPressedIcon` and `JButton.setIcon` together. When I click a button then `button.setIcon(button.getPressedIcon())`. Now when I click another button if both match then disable them. If not set icon to `null`. – dic19 Sep 23 '13 at 19:07
1

You appear to be adding a JLabel to a JButton?? If this is what in fact you're doing, don't. Instead, why not simply set the JButton's ImageIcon when you desire to show or change what image the button displays, if any. You would do this simply via myButton.setIcon(fooIcon).


Edit
You state in comment:

and how will it show the image from jbutton and hide it?

You can simply swap icons. If you want to show an image, set its ImageIcon as the JButton's Icon via setIcon(myIcon). and when done, swap it out via either setIcon(otherIcon) or setIcon(null).

The link that you've provided does not put JLabels on top of JButtons which it appears that you're trying to do, and which is why I'm telling you this information.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • because when clicked jbutton, it will show image.and if 2 images are not same, they will close again. i thought it will show image by setvisible(true) of jlabel's. – clara sampson Sep 23 '13 at 18:28
  • @clarasampson: you're thinking all wrong. Again, do not mix JLabels with JButtons as you're doing. Again, simply set the JButton's Icon. – Hovercraft Full Of Eels Sep 23 '13 at 18:30
  • and how will it show the image from jbutton and hide it? i saw from here http://stackoverflow.com/a/9722205/2807930 – clara sampson Sep 23 '13 at 18:33
  • 3
    @clara sampson [please are you team, or ???](http://stackoverflow.com/users/2800091/john-brown), becasue I can't found any diff between code an descriptions ..., if not then where is really an issue(s) – mKorbel Sep 23 '13 at 20:40