Reputation: 57
I have a program which opens up a window and rapidly changes the color of the background and randomly pops up rectangles and ellipses. My code works, but I have no idea why, because I don't call the repaint() function in my code. When I include the repaint() function using my personal update() function, I don't see any noticeable changes. Here's my code:
package epilepsy;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import Math.Math;
/**
*
* @author 21psuby
*/
public class Epilepsy {
JFrame frame;
DrawPanel drawPanel;
Math math = new Math();
int screenW = 800;
int screenH = 700;
int red = math.random(0, 255);
int green = math.random(0, 255);
int blue = math.random(0, 255);
int x = math.random(0, screenW);
int y = math.random(0, screenH);
int w = math.random(0, screenW/2);
int h = math.random(0, screenH/2);
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Epilepsy().go();
}
private void go() {
frame = new JFrame();
drawPanel = new DrawPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setVisible(true);
frame.setSize(screenW, screenH);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
}
class DrawPanel extends JPanel {
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
randomize();
frame.setBackground(new Color(red, green, blue));
randomize();
g.setColor(new Color(red, green, blue));
g.fillRect(x, y, w, h);
randomize();
g.setColor(new Color(red, green, blue));
g.fillRect(x, y, w, h);
randomize();
g.setColor(new Color(red, green, blue));
g.fillRect(x, y, w, h);
randomize();
g.setColor(new Color(red, green, blue));
g.fillOval(x, y, w, h);
randomize();
g.setColor(new Color(red, green, blue));
g.fillOval(x, y, w, h);
randomize();
g.setColor(new Color(red, green, blue));
g.fillOval(x, y, w, h);
}
}
private void randomize() {
red = math.random(0, 255);
green = math.random(0, 255);
blue = math.random(0, 255);
x = math.random(0, screenW);
y = math.random(0, screenH);
w = math.random(0, screenW/2);
h = math.random(0, screenH/2);
}
private void update() {
while (true) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
frame.repaint();
}
}
}
Thanks, Pranav
Upvotes: 2
Views: 65
Reputation: 811
Method setBackground somewhere internally causes the frame to repaint itself which calls your paintComponent again and that calls setBackground again. This creates infinite loop. Remove the setBackground line and it should work as intended. If you want to change background of the panel try setting it outside the paintComponent method or draw a rectangle of desired color over the entire panel.
Upvotes: 1