I am trying to generate two continous graphs in a JPanel without blocking the JFrame, with Graphics and Graphics2D library. Example of one: https://gyazo.com/2027cab6799d8416b1df8ee953d71b21
What I plan to do with this is to generate the graph at the same time that the user can change values and automatically the graph changes and is generated with these.
I am trying using Threads
Thread:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Thread3 extends Thread {
static int state;
double X = 0;
// Workspace state = 1
@Override
public void run() {
if (state == 1) {
// Graphic 2
Graphics g = Thread1.ws.graphic2.getGraphics();
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
double lastX = 3;
double lastY = 0;
double Y = 0;
double XonScreen = 0;
int width = Thread1.ws.graphic2.getWidth();
int height = Thread1.ws.graphic2.getHeight();
while (Thread1.active) {
if (Thread1.ws.graphic2Active) {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
}
g.clearRect(0, 0, width, height);
XonScreen = 0;
for (int j = 0; j < 48; j++) {
lastX = XonScreen;
lastY = Y;
X += 0.005 * 10000;
XonScreen += 0.005 * 10000;
Y = Math.sin(X) * 120;
g2.drawLine(0, height / 2, width, height / 2);
g2.drawLine((int) XonScreen, ((int) Y + height / 2), (int) lastX, ((int) lastY + height / 2));
g2.drawLine(0, 0, 0, height);
}
} else {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
}
In this case I just set the JPanel to public and instantiated the JFrame in a static way. So far it works correctly but when running it, the graph does not update, it only updates when there is an event running. https://gyazo.com/dc72d3c1a119b2ec93b442063f32c797
I tried using frame.repaint(); but it just makes all the JPanel flick. I also tried using a timer with an ActionPerformed event:
private Timer timer = new Timer(20, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
repaint();
}
});
but it also didn't work (I'm not sure if I implemented it correctly; if you have any suggestions about this, please let me know.) .
Do you know of any way that I can make the graphs update constantly and still manage the rest of the frame without any problems?