真彩随机怎么写(java)

How to write true color random (java)

这是我的代码:


import java.awt.*;
import java.util.Random; 
import javax.swing.*
public class GraphsPaneTest {
    public static void main(String[] args) {
        myFrame window = new myFrame();
    }
}

class myFrame extends JFrame {
    public myFrame() {
        myPanel panel = new myPanel();
        Container cont = getContentPane();
        cont.add(panel);
        setBounds(100,100,500,500);
        setVisible(true);
    }
}

class myPanel extends JPanel {
    public void paintComponent(Graphics gr) {
        super.paintComponent(gr); 
        Random ab = new Random(); 
        colors={Color.BLUE, Color.RED, Color.ORANGE, Color.PINK}; //Here an error
        int colorsThis = ab.nextInt(colors[colorThis]); //Here an error
        gr.setColor(Color.RED); //I try it, but it does't work //And here an error
        int a=1;
        while (a<10) {
            Random b = new Random(); 
            gr.fillRect(b.nextInt(900+1),b.nextInt(900+1), b.nextInt(50+1), b.nextInt(50+1)); 
            a++; 
        }
    }
}

我试图创建一些具有正方形的代码,该正方形在具有随机边界的随机坐标处具有随机颜色。我有一个错误。请帮忙。我知道我的英文很烂

这将生成真正随机的颜色,而不是数组中的预定义颜色:

public Color randomColor() {
        Random r = new Random();
        float red, green, blue;
        red = r.nextFloat();
        green = r.nextFloat();
        blue = r.nextFloat();
        return new Color(red, green, blue);
    }

您必须声明数组的类型。在 Java 中,您必须在使用前声明变量。在这种情况下

颜色 = {...};

你必须定义数组的类型 ->

键入 [ ] 颜色 = {...};

尝试随机颜色

int R = (int)(Math.random( )*256);
int G = (int)(Math.random( )*256);
整数 B = (整数)(Math.random( )*256);
颜色 randomColor = new Color(R, G, B);