user3076906
user3076906

Reputation: 33

How do i draw random shapes in different JPanels in Java

I am trying to make a small version of a slot machine. I am using five JPanels. Four of the JPanels will hold random shapes like a square, circle, and oval. If all four of the JPanels 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 JPanels 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 JPanels 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

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

  1. Your 5th 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.
  2. You need to get your program logic out of your paintComponent method. The logic should not be triggered by a repaint, but rather by an explicit method call, since you cannot fully control repaints.
  3. You should give your spinning components a method to allow other objects to extract their state, so that they all can be compared.

Upvotes: 4

Related Questions