2
Swing GUIで色をランダムに生成する必要がありますが、問題は明るいものにしたいということです。どのようにランダムな明るい色を生成するには?
Swing GUIで色をランダムに生成する必要がありますが、問題は明るいものにしたいということです。どのようにランダムな明るい色を生成するには?
Colorクラスの静的メソッド(getHSBColor(...)
)を使用して、3番目のパラメータ、明るさを表すパラメータが十分に高いことを確認します.0.1.0f)。ランダムと呼ばれるランダムな変数を用い
float h = random.nextFloat();
float s = random.nextFloat();
float b = MIN_BRIGHTNESS + ((1f - MIN_BRIGHTNESS) * random.nextFloat());
Color c = Color.getHSBColor(h, s, b);
、および0.8fのMIN_BRIGHTNESS値:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.*;
public class RandomBrightColors extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
private static final int RECT_W = 30;
private static final int RECT_H = RECT_W;
private static final float MIN_BRIGHTNESS = 0.8f;
private Random random = new Random();
public RandomBrightColors() {
setBackground(Color.BLACK);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 100; i++) {
g.setColor(createRandomBrightColor());
int x = random.nextInt(getWidth() - RECT_W);
int y = random.nextInt(getHeight() - RECT_H);
g.fillRect(x, y, RECT_W, RECT_H);
}
}
private Color createRandomBrightColor() {
float h = random.nextFloat();
float s = random.nextFloat();
float b = MIN_BRIGHTNESS + ((1f - MIN_BRIGHTNESS) * random.nextFloat());
Color c = Color.getHSBColor(h, s, b);
return c;
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
RandomBrightColors mainPanel = new RandomBrightColors();
JFrame frame = new JFrame("RandomBrightColors");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
例えば
は、以下のコードは、ランダムな明るい色を見つけるために、上記の方法を使用し編集:または、色を完全に飽和させる場合は、彩度パラメータを1fに変更します。
private Color createRandomBrightColor() {
float h = random.nextFloat();
float s = 1f;
float b = MIN_BRIGHTNESS + ((1f - MIN_BRIGHTNESS) * random.nextFloat());
Color c = Color.getHSBColor(h, s, b);
return c;
}
これは3つのintパラメータのRGBカラーを使用して行うこともできますが、これを行う場合、1つのパラメータは255に近づけて、255以下にする必要があります。 0から255の間のランダムな何でも。
私はこのポストがあなたを助けるかもしれないと思う。 http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color –
一部の[例](http://stackoverflow.com/search?tab=votes&q=user%3a230513%20Color .getHSBColor)。 – trashgod