I have a JFrame in which I print 3 objects using 3 threads:
Thread-1) Prints Circles
Thread-2) Prints Squares
Thread-3) Prints Triangle
The problem is that I need to print new objects over and over again, and not just repaint them. But my run() function of each thread can't touch the Graphics g variable of the Overrideded method paintComponent(Graphics g) of the class. I can only use repaint() inside the run() function.
This is what I have: (repaint() method used)
https://prnt.sc/gnxz6iM
This is what I want(WITHOUT THOSE SQUARE BORDERS of the paintImmediatly() method): https://prnt.sc/gny1qx
package tarefa03;
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.Random;
import javax.swing.OverlayLayout;
public class FigurePlacer extends JPanel implements Runnable{
final int width = 700;
final int height = 700;
int x_pos = 0;
int y_pos = 0;
int x_width = 50;
int y_height = 50;
String figure;
public FigurePlacer(String str){
figure = str;
randomCoord();
setOpaque(false);
setBounds(0, 0, width, height);
Thread th = new Thread (this);
th.start();
}
private void randomCoord(){
Random random = new Random();
x_pos = random.nextInt(width);
y_pos = random.nextInt(height);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
switch (figure){
case "circle":
g2.setColor(Color.BLUE);
g2.fillOval(x_pos, y_pos, x_width, y_height);
break;
case "square":
g2.setColor(Color.GREEN);
g2.fillRect(x_pos, y_pos, x_width, y_height);
break;
case "triangle":
g2.setColor(Color.ORANGE);
int xpoints[] = {x_pos, x_pos+25, x_pos+50};
int ypoints[] = {y_pos, y_pos+50, y_pos};
g2.fillPolygon(xpoints,ypoints,3);
}
}
@Override
public void run(){
while (true){
randomCoord();
this.paintImmediately(x_pos, y_pos, x_width, y_height);
try{
Thread.sleep (200);
}
catch (InterruptedException ex){}
}
}
}