Почему мой графический интерфейс со смайликами выглядит одним цветом, а все элементы имеют свои отдельные, случайные цвета? - PullRequest
1 голос
/ 17 апреля 2019

Я пытаюсь нарисовать эти смайлики в графическом интерфейсе, чтобы их части (глаза, улыбка и т. Д.) Были случайными цветами. Однако, когда я использую метод setColor для своих переменных, они все смешиваются друг с другом, и я не вижу глаз и т. Д. Вот мой код:

import java.awt.*;
import javax.swing.*;
import java.util.*;

public class Smiley extends JPanel {
    //declare required variable
    //set the width of window
    public static final int w = 400;
    //set the height of window
    public static final int h = 400;
    //assign face diameter
    public static final int fd = 180;
    //initializes the face of x position
    public static final int xp = 10;
    //initializes the face of y position
    public static final int yp = 10;
    //initializes the width of eye
    public static final int we = 20;
    //initializes the height of eye
    public static final int he = 20;
    //set the Right eye's position on the x and y
    public static final int xre = xp + 40;
    public static final int yre = yp + 60;
    //set the left eye's position on the x and y
    public static final int xle = xp + 120;
    public static final int yle = yp + 60;
    //initialzes the width and height of the mouth
    public static final int mw = 80;
    public static final int mh = 50;
    //initializes the x and y position of mouth on the face
    public static final int xm = xp + 50;
    public static final int ym = yp + 90;
    //define the class variables of type Color
    public Color profile, nface, fsmile, eye;

    // Smiley constructor takes parameters for 4 colors that will be
    public Smiley(Color profile, Color nface, Color fsmile, Color eye) {
        //set the layout
        setLayout(new BorderLayout());
        //initialize the parameters
        this.profile = profile;
        this.nface = nface;
        this.fsmile = fsmile;
        this.eye = eye;
        //call paint() method
        repaint();
    }
    public void paintComponent(Graphics gr) {
        super.paintComponent(gr);
        Random random = new Random();
        Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
        gr.setColor(color);
        profile = color;
        nface = color;
        fsmile = color;
        eye = color;
        //set the color of profile of the face
        gr.setColor(profile);
        //draw the face
        gr.fillOval(xp, yp, fd + 7, fd + 7);
        //fill the color of face
        gr.setColor(nface);
        gr.fillOval(xp + 3, yp + 3, fd, fd);
        //fill the eye color
        gr.setColor(eye);
        //for draw right eye
        gr.fillOval(xre, yre, we, he);
        gr.setColor(eye);
        //for draw left eye
        gr.fillOval(xle, yle, we, he);
        //for smile color
        gr.setColor(fsmile);
        gr.drawArc(xm, ym, mw, mh, 180, 180);
    }
}

То, что я ожидаю, выглядит примерно так:

https://imgur.com/a/7hFGzw1

Как мне добиться этого?

И это код, в котором я буду реализовывать смайлики:

import java.awt.*;
import java.awt.event.*; //determined to be useless and got rid of 
actionPerformed method
import javax.swing.*;
public class SmileyGrid extends JFrame {
    //object for SmileGrid class
    static SmileyGrid gs = new SmileyGrid();
    public static void main(String[] args) {
        gs.setSize(800, 800);
        gs.setLayout(new GridLayout(3, 3));
        //call createFace function()
        gs.createGUI();
        gs.setVisible(true);
    }

    public SmileyGrid() {

    }

    private void createGUI() {
        for (int a = 0; a < 9; a++) {
            Smiley sp = new Smiley(Color.BLUE, Color.YELLOW, Color.RED, Color.black);
            gs.add(sp);
        }
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

Ответы [ 2 ]

1 голос
/ 17 апреля 2019

Здесь:

profile = color;
nface = color;
fsmile = color;

Это должны быть ваши 3 разных цвета. Но вы инициализируете все три значения одинаковыми ! Вместо этого вам придется вызывать случайную функцию 3 раза. Или, если быть точным: вы должны вызывать эту функцию несколько раз , пока ваши 3 цвета действительно не станут разными.

В качестве альтернативы: вы можете определить 3 набора, каждый с 5, 10 различными цветами вручную. И тогда ваш код выбирает случайный цвет из каждого набора. Значение: вместо использования совершенно случайных цветов, вы можете выбрать наборы цветов, которые всегда работают вместе при смешивании.

0 голосов
/ 17 апреля 2019

Добро пожаловать на SO.Вы присваиваете один и тот же объект Color всем своим переменным, поэтому, естественно, они имеют одинаковый цвет.Вам нужно будет генерировать новые случайные цвета для каждого из них, а не назначать color для всех них.

profile = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
...
...