I tried to call repaint() inside while loop to change the position of text, and after the thread end call the second thread to perform another action. The problem I found is after making first thread wait to end and call the second thread the repaint() in first thread won't run but it run after the first thread is finished. How could I call repaint() inside the synchronized function?
Here is my code:
package com.lab02.inClass;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JApplet;
import javax.swing.JPanel;
public class StarWarsTitle extends JApplet {
@Override
public void init() {
super.init();
FirstPanel firstPanel = new FirstPanel(this);
SecondPanel secondPanel = new SecondPanel(this);
add(firstPanel);
add(secondPanel);
synchronized (firstPanel.thread) {
firstPanel.thread.start();
try {
firstPanel.thread.wait();
System.out.println("Hello World");
} catch (InterruptedException e) {
}
secondPanel.thread.start();
}
}
}
class FirstPanel extends JPanel implements Runnable {
StarWarsTitle applet;
Thread thread;
int pos_x, pos_y, fontSize = 40;
public FirstPanel(StarWarsTitle applet) {
this.applet = applet;
thread = new Thread(this);
}
@Override
public void run() {
pos_x = applet.getWidth() / 2;
pos_y = applet.getHeight();
while (pos_y > 100) {
pos_y--;
System.out.println(pos_y);
if (pos_y % 20 == 0 && fontSize >= 0)
fontSize--;
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("in paint component");
Graphics2D g2d = (Graphics2D) g;
g2d.setFont(new Font("Cordia New", Font.PLAIN, fontSize));
g2d.drawString("Hello", pos_x, pos_y);
}
}
class SecondPanel extends JPanel implements Runnable {
StarWarsTitle applet;
Thread thread;
public SecondPanel(StarWarsTitle applet) {
this.applet = applet;
thread = new Thread(this);
}
@Override
public void run() {
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setFont(new Font("Cordia New", Font.PLAIN, 40));
g2d.drawString("Hello", 100, 100);
}
}