I am making a memory card game. I created a 2D array of JButtons, size 5x6. Each button is placed on my board using a gridlayout with the same image shown when the card is face down. When the user clicks on the card, I would like to have that button show a different image. I created a string array that has 15 images location stored in it. I am unable to get the buttons to show a different image. When I click a button, it shows it as a light blue, but then as soon as I let go of the click, it goes back to what it was without showing the image. Thanks for your help. Here is my code:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Layout implements MouseListener{ JButton[][] button = new JButton[6][5]; private int matches; private int attempts; int attemptsCounter = -1; String Images[] = {"blanton.jpg", "brown.jpg", "halladay.jpg", "hamels.jpg", "howard.jpg", "lee.jpg", "mayberry.jpg", "papelbon.jpg", "pence.jpg", "polanco.jpg", "rollins.jpg", "ruiz.jpg", "utley.jpg", "victorino.jpg", "worley.jpg"}; public void jpanel(){ JFrame frame = new JFrame(); JPanel gridPanel = new JPanel(new GridLayout(5, 6)); JPanel northPanel = new JPanel(); 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].addMouseListener(this); } } frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } 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(); } } } } }