Java AWT Color create random color
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.Random; import javax.swing.JFrame; import javax.swing.JPanel; public class Main extends JPanel { Random rnd = new Random(); @Override//from ww w . j a v a 2 s.c o m public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setBackground(Color.BLACK); g2d.clearRect(0, 0, getParent().getWidth(), getParent().getHeight()); for (int i=0; i<3000; i++) { int red = rnd.nextInt(256); int green = rnd.nextInt(256); int blue = rnd.nextInt(256); g2d.setColor(new Color(red, green, blue)); int rndX = rnd.nextInt(getSize().width); int rndY = rnd.nextInt(getSize().height); g2d.drawLine(rndX, rndY, rndX, rndY); } } public static void main(String[] args) { // create frame for Main JFrame frame = new JFrame("java2s.com"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Main Main = new Main(); frame.add(Main); frame.setSize(300, 210); frame.setVisible(true); } }
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.GeneralPath; import java.security.SecureRandom; import javax.swing.JFrame; import javax.swing.JPanel; public class Main extends JPanel { @Override// w w w .j av a 2 s . c om public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; // cast g to Graphics2D int[] xPoints = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 }; int[] yPoints = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 }; GeneralPath star = new GeneralPath(); // create GeneralPath object // set the initial coordinate of the General Path star.moveTo(xPoints[0], yPoints[0]); // create the star--this does not draw the star for (int count = 1; count < xPoints.length; count++) star.lineTo(xPoints[count], yPoints[count]); star.closePath(); // close the shape g2d.translate(150, 150); // translate the origin to (150, 150) // rotate around origin and draw stars in random colors SecureRandom random = new SecureRandom(); for (int count = 1; count <= 20; count++) { g2d.rotate(Math.PI / 10.0); // rotate coordinate system // set random drawing color g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256))); g2d.fill(star); // draw filled star } } public static void main(String[] args) { JFrame frame = new JFrame("Drawing 2D shapes"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Main Main = new Main(); frame.add(Main); frame.setSize(425, 200); frame.setVisible(true); } }