При правильной логике создания цвета (RainbowColors
класс) класс Board
работает просто отлично:
class Board extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
super.setBackground(Color.BLACK);
drawDonut(g, Color.WHITE);
}
private void drawDonut(Graphics g, Color c) {
Graphics2D g2d = (Graphics2D) g;
RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(rh);
Dimension size = getSize();
double w = size.getWidth();
double h = size.getHeight();
Ellipse2D e = new Ellipse2D.Double(0, 0, 160, 260);
g2d.setStroke(new BasicStroke(3));
double range = 360, step = 5;
RainbowColors rb = new RainbowColors((int)(range/step));
for (double deg = 0; deg < range; deg += step) {
AffineTransform at = AffineTransform.getTranslateInstance(w/2, h/2);
at.rotate(Math.toRadians(deg));
g2d.setColor(rb.getNewColor());
g2d.draw(at.createTransformedShape(e));
}
}
}
class RainbowColors {
private static final int DEFAULT_NUMBER_OF_COLORS = 100;
private final int numberOfColors;
private int index;
private Color[] colors;
RainbowColors() {
this(DEFAULT_NUMBER_OF_COLORS);
}
RainbowColors(int numberOfColors) {
this.numberOfColors = numberOfColors > 0 ? numberOfColors : DEFAULT_NUMBER_OF_COLORS;
makeColors();
}
//based on https://stackoverflow.com/a/22973823/3992939
private void makeColors() {
int range = numberOfColors / 6; //6 for loops, each changes R G or B
int step = 255/range;
List<Color> colorsList = new ArrayList<>();
for (int r=0; r< range; r++) {
colorsList.add(new Color(r*step, 255, 0));
}
for (int g=range; g>0; g--) {
colorsList.add(new Color( 255, g*step, 0));
}
for (int b=0; b<range; b++) {
colorsList.add(new Color( 255, 0, b*step));
}
for (int r=range; r>0; r--) {
colorsList.add(new Color(r*step, 0, 255));
}
for (int g=0; g<range; g++) {
colorsList.add(new Color( 0, g*step, 255));
}
for (int b=range; b>0; b--) {
colorsList.add(new Color( 0, 255, b*step));
}
colors = colorsList.toArray(new Color[colorsList.size()]);
}
Color getNewColor() {
index = index >= colors.length ? 0 : index;
return colors[index++];
}
}
Anmcve можно скопировать с здесь .