Reputation: 33
I am trying to make a small version of a slot machine. I am using five JPanel
s. Four of the JPanel
s will hold random shapes like a square, circle, and oval. If all four of the JPanel
s are displaying a square then the fifth JPanel
should display JackPot
and if any other combination is displayed then the fifth JPanel
should say try again. The problem I am having is making the fifth JPanel
display a message when the user wins or loses. I am able to draw the shapes randomly on the JPanel
s but the problem I am having is making the paint method draw in a specific JPanel
. When I run the code a random shape appears on every JPanel
but I only want the shapes to appear on four JPanel
s instead of all five.
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class JackPot extends JPanel {
public JackPot(Color backColor) {
setBackground(backColor);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Random gen = new Random();
int a = gen.nextInt(10);
if (a <= 3) {
g.drawOval(20,20,25,25);
} else if (a > 3 && a <= 6) {
g.drawRect(20,20,25,10);
} else {
g.drawOval(20,20,20,10);
}
}
public static void main(String[] args) {
JFrame GUI = new JFrame();
GUI.setTitle("JackPot");
GUI.setSize(500, 400);
Container pane = GUI.getContentPane();
pane.setLayout(new GridLayout(5, 1));
JackPot panel = new JackPot(Color.red);
JackPot panel2 = new JackPot(Color.white);
JackPot panel3 = new JackPot(Color.yellow);
JackPot panel4 = new JackPot(Color.green);
JackPot panel5 = new JackPot(Color.pink);
pane.add(panel);
pane.add(panel2);
pane.add(panel3);
pane.add(panel4);
pane.add(panel5);
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setVisible(true);
}
}
Upvotes: 1
Views: 1249
Reputation: 285403
JPanel
should not be a JackPot
object but rather it's own object, perhaps a PayoutPanel
object or something similar. The key is that its behavior is intrinsically different from that of JackPot
and so its code must be different to match.paintComponent
method. The logic should not be triggered by a repaint, but rather by an explicit method call, since you cannot fully control repaints.Upvotes: 4