Memory Card Game JButton 2D Array

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

32 Replies - 9241 Views - Last Post: 14 March 2012 - 02:10 PM Rate Topic: -----

#1 ral106  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 02-August 11

Memory Card Game JButton 2D Array

Posted 01 March 2012 - 01:13 PM

I am creating a 2D array of JButtons to put onto a JPanel using a GridLayout. I printed out the code hoping for it to give me the positions that is storing the elements of the array. I am getting a null pointer exception somewhere in the for loop when I try to run this code. I don't see where I am using the wrong size for the array? Thanks for your help.

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

public class Layout{
	public void jpanel(){
		JFrame frame = new JFrame();
		JPanel gridPanel = new JPanel(new GridLayout(6, 5));
		JPanel northPanel = new JPanel();
                JButton[][] button = new JButton[6][5];
		
		for(int i=0; i<6; i++){
			for(int j=0; j<5; j++){
				gridPanel.add(button[i][j]);
			}
		}


This post has been edited by ral106: 01 March 2012 - 01:17 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Memory Card Game JButton 2D Array

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10397
  • View blog
  • Posts: 38,467
  • Joined: 27-December 08

Re: Memory Card Game JButton 2D Array

Posted 01 March 2012 - 01:18 PM

You can't declare public fields inside methods. You should be getting a compilation error.

As for the NullPointerException, the elements in arrays of Objects are initialized to null by default. You have to go through each element and initialize it to a new JButton in your array. Also, the grid is only needed graphically, and the GridLayout handles this. You could easily use a one dimensional array instead of a 2D array. You don't need a structural grid.
Was This Post Helpful? 0
  • +
  • -

#3 ral106  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 02-August 11

Re: Memory Card Game JButton 2D Array

Posted 01 March 2012 - 02:01 PM

OK thanks!! I was able to get it to work using your advice. I now need to add the same image to every JButton. Can you give me some advice as to how to go about this? I attached my output if you want to look at it. Here is my code so far:

Attached Image

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

public class Layout{
	
	private int matches;
	private int attempts;
	
	public void jpanel(){
		JFrame frame = new JFrame();
		JPanel gridPanel = new JPanel(new GridLayout(5, 6));
		JPanel northPanel = new JPanel();
		JButton[][] button = new JButton[6][5];
		
		JButton attempts = new JButton("Attempts: ");
		JButton playAgain = new JButton("Play Again");
		JButton matches = new JButton("Matches: ");
		northPanel.add(attempts);
		northPanel.add(matches);
		northPanel.add(playAgain);
		frame.setSize(900, 700);
		frame.add(northPanel, BorderLayout.NORTH);
		northPanel.setSize(900, 100);
		frame.add(gridPanel);
		gridPanel.setSize(900, 600);
		gridPanel.setBackground(Color.blue);
		for(int i=0; i<button.length; i++){
			for(int j=0; j<button[i].length; j++){
				int n = i*button[i].length + j+1;
				button[i][j] = new JButton(String.valueOf(n));
				gridPanel.add(button[i][j]);
			}
		}
		java.net.URL image = Memory.class.getResource("phillies.jpg");
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}


Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10397
  • View blog
  • Posts: 38,467
  • Joined: 27-December 08

Re: Memory Card Game JButton 2D Array

Posted 01 March 2012 - 02:02 PM

See the JButton setIcon() method.
Was This Post Helpful? 0
  • +
  • -

#5 ral106  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 02-August 11

Re: Memory Card Game JButton 2D Array

Posted 01 March 2012 - 07:51 PM

I was able to set the back of the image correctly. Now I need to be able to display another image once the user clicks on a button. I tried using setPressedIcon() method for a certain button in the array, but when I click that card, it just shows a light blue and once I let go, it goes back to the default image. It's a memory card game so there will be 15 different pictures. I'm not sure how to set only 2 to each card without going through all 30 cards one by one. Here's what I tried to do:

button[0][0].setPressedIcon(new ImageIcon("blanton.jpg"));


Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8325
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Memory Card Game JButton 2D Array

Posted 01 March 2012 - 09:37 PM

setPressedIcon() is just for the time the button is pressed

once the button has been clicked in the actionPerformed() method you an:
button[i][j].setIcon(iconButtonAsBeenUsed);
button[i][j].setEnabled(false); // to avoid to be able to press it again
Was This Post Helpful? 0
  • +
  • -

#7 ral106  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 02-August 11

Re: Memory Card Game JButton 2D Array

Posted 02 March 2012 - 09:30 PM

I am trying to create a mouse listener in my code so that when the user clicks on a JButton, there will be a different image shown to the user. I have three classes in my code. I'm a little confused about using a mouse listener. Do I create a new class just for the mouse listener? Also, if I only want to use the mouse click event, do I need to include the other functions of the mouse listener? I also don't understand the extends and implements keywords, so if someone could tell me what these do, it would be appreciated. Thanks for your help.
Was This Post Helpful? 0
  • +
  • -

#8 Sheph  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 432
  • View blog
  • Posts: 1,020
  • Joined: 12-October 11

Re: Memory Card Game JButton 2D Array

Posted 02 March 2012 - 10:06 PM

An interface defines a set of methods and any class that implements that interface must define what happens when those methods are called by overriding them. That's what the implements keyword means.

If you are just using a JButton, you can have a class that implements ActionListener. ActionListener is an interface with one method, void actionPerformed(ActionEvent e);. This method is called every time an action occurs on the button (When it's clicked). You can create a new class that implements ActionListener and defines what happens in that method by overriding it.

public class MyActionListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        // code to be executed when the button is clicked.
    }
}


Of course, you don't NEED to create a new java file to do something so trivial. You can create an anonymous inner class, like so:

JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // your code here
    }
});


If you do choose to use a MouseListener you can do the same thing with implements MouseListener instead. Remember, whenever you implement an interface, you MUST declare and define all of the methods in that interface, but you don't have to do anything in them. If you are just using one, you can leave the others blank. An alternative to MouseListener would be to extend MouseAdapter, which is an abstract class that implements MouseListener, and only override the methods you want to. This is possible because MouseAdapter implements all of the methods for MouseListener, and your subclass can choose to override the ones it wants, and leave the rest for MouseAdapter to handle. Of course this is technically the same as handling it yourself.
Was This Post Helpful? 0
  • +
  • -

#9 ral106  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 02-August 11

Re: Memory Card Game JButton 2D Array

Posted 02 March 2012 - 10:29 PM

OK thank you that was really helpful! Here is my updated code. My IDE was telling me to put the override in for the action performed. Does anything else need to go in that function? Also, in my nested for loop, I want to be able to assign 2 buttons to the same image. It will do this 15 times with a different image. There is an image already on the button that is displayed when the app is loaded. When the user clicks on this button, it should show the other picture. Is there a way to do this without assigning each button 1 by 1? Also, the part I have commented out with the button.setPressedIcon method, it says something about a non-final variable button, what does this mean? Thank you!!

public class Layout implements ActionListener{
	
	private int matches;
	private int attempts;
	int attemptsCounter = -1;
	
	public void panel(){
		JFrame frame = new JFrame();
		JPanel gridPanel = new JPanel(new GridLayout(5, 6));
		JPanel northPanel = new JPanel();
		JButton[][] button = new JButton[6][5];
		
		JLabel attempts = new JLabel("Attempts: ");
		JButton playAgain = new JButton("Play Again");
		JLabel matches = new JLabel("Matches: ");
		northPanel.add(attempts);
		northPanel.add(matches);
		northPanel.add(playAgain);
		frame.setSize(900, 700);
		frame.add(northPanel, BorderLayout.NORTH);
		northPanel.setSize(900, 100);
		frame.add(gridPanel);
		gridPanel.setSize(800, 600);
		for(int i=0; i<button.length; i++){
			for(int j=0; j<button[i].length; j++){
				int n = i*button[i].length + j+1;
				button[i][j] = new JButton();
				gridPanel.add(button[i][j]);
			}
		}
		java.net.URL image = Memory.class.getResource("phillies.jpg");
		for(int i=0; i<6; i++){
			for(int j=0; j<5; j++){
				button[i][j].setIcon(new ImageIcon(image));				
				button[i][j].addActionListener(new ActionListener(){
					public void actionPerformed(ActionEvent e){
						//button[0][0].setPressedIcon(new ImageIcon("blanton.jpg"));
					}
				});
			}
		}
		
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		
	}


Was This Post Helpful? 0
  • +
  • -

#10 Sheph  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 432
  • View blog
  • Posts: 1,020
  • Joined: 12-October 11

Re: Memory Card Game JButton 2D Array

Posted 02 March 2012 - 10:52 PM

I wouldn't use an anonymous class then. You can do button[i][j].addActionListener(this); and then get a reference to that button by doing this in your actionPerformed method of your Layout class.

public void actionPerformed(ActionEvent e) {
    JButton button = (JButton)e.getSource(); // reference to the button clicked.
    button.setIcon(); //...
}


How about subclassing JButton and calling swap in actionPerformed when you want to switch the image?

public class MyButton extends JButton {
	ImageIcon alternate;
	
	MyButton(ImageIcon normal, ImageIcon alternate) {
		super();
		setIcon(normal);
		this.alternate = alternate;
	}
	
	public void swap() {
		ImageIcon temp = (ImageIcon)getIcon();
		setIcon(alternate);
		alternate = temp;
	}
}

Was This Post Helpful? 0
  • +
  • -

#11 ral106  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 02-August 11

Re: Memory Card Game JButton 2D Array

Posted 02 March 2012 - 11:27 PM

I was able to get it to work kinda. I should be able to figure it out from there. Now I have a different problem. I have a 2D array of JButtons, and I would like to create a String array that stores the images I want to use. Is there a way to assign these images to the JButtons twice? Here's what I was trying to do. It doesn't work, but I was hoping to be able to do something along these lines. Is it possible to do a for loop that just runs 30 times with a 2D array to get the images to be stored in the button array?

public void mouseClicked(MouseEvent event){
		for(int i=0; i<6; i++){
			for(int j=0; j<5; j++){
				String tempImage = Images[i];
				button[i][j] = tempImage;
			}
		}
	}


Was This Post Helpful? 0
  • +
  • -

#12 ral106  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 02-August 11

Re: Memory Card Game JButton 2D Array

Posted 03 March 2012 - 01:39 PM

I updated my code a little. The Images array has the path of the 15 images I want to use. When I click on a button, it turns a light blue instead of showing the image. I want to be able to assign these images to 2 buttons each, and have the image show once the button is clicked. What am I doing wrong?

public void mouseClicked(MouseEvent event){
		for(int k=0; k<30; k++){
			for(int i=0; i<6; i++){
				for(int j=0; j<5; j++){
					button[i][j].setPressedIcon(new ImageIcon(Images[k]));
					button[i][j].getPressedIcon();
				}
			}
		}
	}


Was This Post Helpful? 0
  • +
  • -

#13 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10397
  • View blog
  • Posts: 38,467
  • Joined: 27-December 08

Re: Memory Card Game JButton 2D Array

Posted 03 March 2012 - 08:31 PM

Duplicate threads merged. Please avoid duplicate posting.
Was This Post Helpful? 0
  • +
  • -

#14 ral106  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 02-August 11

Re: Memory Card Game JButton 2D Array

Posted 03 March 2012 - 09:10 PM

Sorry, I didn't even realize that! Can somebody please look at my last post and try to help me though?
Was This Post Helpful? 0
  • +
  • -

#15 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2197
  • View blog
  • Posts: 5,224
  • Joined: 10-September 10

Re: Memory Card Game JButton 2D Array

Posted 04 March 2012 - 04:02 AM

You have a String array called Images that has the paths to 15 images, right? I'm not sure what you mean by assigning them twice, but since you have 30 JButtons, I'm guessing that you want somehow assign each button an image and with only 15 images for 30 buttons, some buttons (which ones?) will have the same image.

Your nested loops aren't currently correct to do as you've described. Currently, k remains fixed while you iterate through the entire array of buttons, so you assign every button the first image, then every button the second image, and so on until every button is assigned to the last image. Why you're getting "light blue" when clicked may be due to code you haven't shown us, the setPressedIcon() or getPressedIcon() methods.

For the for loop:

Get rid of the k loop, keep the i and j loops to iterate to the desired 2 buttons, and assign the images using something like:

k = 0; // outside the i/j loops
// begin looping:
button1[i][j] = Images[k];
button2[i][j] = Images[k++];

The above is simplified, essentially pseudo code, but should give you the idea. Again, I don't know which buttons will share images, and without that detail I'm not sure how you'll set up the i/j loops to reach them both with each iteration. If you can't figure it out, give that detail, and we can help you set it up.
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3