Link a button to a picture using a listener in Java

I am trying to create a memory game in Java. Something like this, but much more simplier -> http://www.zefrank.com/memory/

Here is my code:

import javax.swing.*;

public class Memoriin {

    public static void main(String[] args) {
        JFrame frame = new MemoriinFrame();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

And:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class MemoriinFrame extends JFrame {

    private static final long serialVersionUID = 1L;
    public static final int DEFAULT_HEIGHT = 600;
    public static final int DEFAULT_WIDTH = 800;
    public JButton button[] = new JButton[8];
    ArrayList<ImageIcon> icons = new ArrayList<ImageIcon>();
    ImageIcon tail = new ImageIcon("foto.jpg");

    ImageIcon photo1 = new ImageIcon("foto1.jpg");
    ImageIcon photo2 = new ImageIcon("foto2.jpg");
    ImageIcon photo3 = new ImageIcon("foto3.jpg");
    ImageIcon photo4 = new ImageIcon("foto4.jpg");
    ImageIcon photo1copy = photo1;
    ImageIcon photo2copy = photo2;
    ImageIcon photo3copy = photo3;
    ImageIcon photo4copy = photo4;



    public MemoriinFrame() {
          setTitle("Memory Game");
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
          setLayout(new GridLayout(2, 4));

          addIcons();
          for(int i = 0; i <= 7; i++) {
              button[i] = new JButton();
              button[i].setIcon(tail);
              button[i].addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                      performActionEventHandler();
                  }
              });
              add(button[i]);
          }

    }

    public void performActionEventHandler() {
        // how can I link each button with a specific picture?
    }

    public void addIcons() {
        icons.add(photo1);
        icons.add(photo2);
        icons.add(photo3);
        icons.add(photo4);
        icons.add(photo1copy);
        icons.add(photo2copy);
        icons.add(photo3copy);
        icons.add(photo4copy);
        Collections.shuffle(icons);
    }

    public void tailToImage(JButton button) {
        button.setIcon(icons.get(0));
        icons.remove(0);
    }
}

So, I am trying to link a button with a specific picture. I tried to do that, but I had an unnecessary result: if I click a button then picture changes to a random picture. But I have 8 buttons and 8 pictures and I want to link them, so that each button goes with the same picture all game long.

P.S. English is not my native language.

Answers


In order to associate a button and a Picture, it is wiser to have a Mapping between them. You can use something like.

Map<JButton, ImageIcon>

Now the above is a very crude relation between a button and an Icon. You may have to improvise on this. Something like this..

Image source : For foto1 through foto4 I took the avatar of the top 4 users from Stackoverflow.

ImageIcon photo1 = new ImageIcon("foto1.jpg");
ImageIcon photo2 = new ImageIcon("foto2.jpg");
ImageIcon photo3 = new ImageIcon("foto3.jpg");
ImageIcon photo4 = new ImageIcon("foto4.jpg");
ImageIcon photo1copy = new ImageIcon("foto1.jpg");
ImageIcon photo2copy = new ImageIcon("foto2.jpg");
ImageIcon photo3copy = new ImageIcon("foto3.jpg");
ImageIcon photo4copy = new ImageIcon("foto4.jpg");

Map<JButton, ImageIcon> buttonImage = new HashMap<JButton, ImageIcon>();

public MemoriinFrame() {
      setTitle("Memory Game");
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
      setLayout(new GridLayout(2, 4));

      for(int i = 0; i <= 7; i++) {

          button[i] = new JButton();
          button[i].setIcon(tail);
          button[i].addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  performActionEventHandler((JButton)e.getSource());
              }
          });
          add(button[i]);
      }

      addIcons();

}

public void performActionEventHandler(JButton clickedButton) {
    clickedButton.setIcon(buttonImage.get(clickedButton));
}

public void addIcons() {
    icons.add(photo1);
    icons.add(photo2);
    icons.add(photo3);
    icons.add(photo4);
    icons.add(photo1copy);
    icons.add(photo2copy);
    icons.add(photo3copy);
    icons.add(photo4copy);
    Collections.shuffle(icons);

    for(int i=0;i<icons.size();i++){
        buttonImage.put(button[i], icons.get(i));
    }
}

NOTE : This is not a COMPLETE bug free answer since I was just playing with it. And it has a lot of scope to be refactored. But this should be very much enough to get you going.


Myself, I've created an ArrayList of ImageIcon (ArrayList<ImageIcon>) and have added two of each ImageIcon to it. I then call Collections.shuffle(...) on the list to randomize. Then use a HashMap<JButton, Icon> and associate each button with an image. Then when the button has been pressed, set the JButton's icon to the one in the map (or null if you want to remove the icon if he guess wrong).


Need Your Help

Converting Treemap keys and values to array

java treemaps

I need to convert a TreeMap to an array; could anyone show me how it's done? I need both keys and values.I am mapping each word to its frequency in a text file

Linking project with statically build curl

c++ curl cmake mingw32

I'm doing small project in C++ with CMake and MinGW32, which requires libcurl library, but when i try to link statically build libcurl.a I get undefined reference errors

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.