简体   繁体   中英

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 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);
    }
}
  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM