Reputation:
Im trying to make a simple memory game where if two buttons rather the icons on them match, the score increases. Im quite stuck on how to make the icon on the button show after it has been clicked. So far I have used:
public class NextFrame extends javax.swing.JFrame {
/**
* Creates new form NextFrame
*/
public NextFrame() {
initComponents();
btnCard1.setIcon(null);
btnCard2.setIcon(null);
btnCard3.setIcon(null);
btnCard4.setIcon(null);
btnCard5.setIcon(null);
btnCard6.setIcon(null);
//list goes on....
}
private void btnCard1ActionPerformed(java.awt.event.ActionEvent evt) {
//Not sure what goes here....
}
Using java Swing I have placed my icons within the JButtons. So only when a user clicks on it I want the selected button to display the icon. By setting the property of the button to pressedIcon only shows the icon when I press and click on the button. How do I make it so that the icon is rather fixed as I click once.
Also since my images are already there in GUI and I've only just set each button to null in the beginning, is there a method to just change from null to the actual icon.
Upvotes: 1
Views: 287
Reputation: 10673
You're overthinking things.
You know how to create an icon and set it as a button icon, yes?
Image image = new ImageIcon("C:\\some_image.png");
JButton myButton = new JButton(imageIcon);
What if you actually created two icons like so:
Image image1 = ImageIcon(getClass().getResource("real_image.png")
Image image2 = ImageIcon(getClass().getResource("blank_image.png")
When you create the button, use the blank image, which is the same size as the real image, but doesn't contain the actual image. The reason for using a blank image rather than setting the image to null is because a button without an image may actually change size once you add the image, which can potentially mess with your layout.
JButton myButton = new JButton(image2);
Now in your ActionPerformed handler which runs when the user clicks the button, you set the real image on the button:
myButton.setIcon(image1);
Upvotes: 3