Java AWT Graphics2D clear rectangle
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//ww w . ja v a 2s. c om 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); } }