I am trying to understand if it is possible to change the color of existing graphics while my application runs, (something of a flicker between multiple different colors).
I have a start shape that is drawn out using the GeneralPath
class and I also have my a random RGB color code selector working properly. Is it possible to change the color maybe with using repaint();
to have the color of my star change between the 3 selected colors which were randomly selected from my createRandomColor()
method?
Code
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import static java.lang.Math.random;
import java.util.Vector;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Sandbox extends JApplet {
DrawingStar canvas;
public static void main(String[] args) {
JFrame frame = new JFrame();
Sandbox path = new Sandbox();
path.init();
frame.getContentPane().add(path);
frame.setSize(250, 250);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void init() {
Container container = getContentPane();
canvas = new DrawingStar();
container.add(canvas);
}
}
class DrawingStar extends Canvas {
Vector generalPaths;
private List<Color> colors;
public DrawingStar() {
colors = new ArrayList<Color>();
for (int i = 0; i < 3; i++) {
colors.add(createRandomColor());
}
setBackground(Color.white);
setSize(400, 400);
generalPaths = new Vector();
GeneralPath gp1;
gp1 = new GeneralPath();
gp1.moveTo(50, 120);
gp1.lineTo(70, 180);
gp1.lineTo(20, 140);
gp1.lineTo(80, 140);
gp1.lineTo(30, 180);
gp1.closePath();
generalPaths.addElement(gp1);
}
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.translate(70.0f, -85.0f);
g2D.draw((GeneralPath) generalPaths.elementAt(0));
for (int i = 0; i < 3; i++) {
Color color = colors.get(i);
g2D.setColor(color);
g2D.fill((GeneralPath) generalPaths.elementAt(0));
}
System.out.println("Is this working");
repaint();
}
private Color createRandomColor(){
int r = (int) (Math.random() * 256);
int g = (int) (Math.random() * 256);
int b = (int) (Math.random() * 256);
Color color = new Color(r,g,b);
return color;
}
}