This is the process when you want to set up the GUI separately from the main process.
For example, if you were writing a language processing system
When instructed to create a frame from a script processed by the processing system
The processing system must set up a frame.
This is a story that you only need to execute JFrame frame = new JFrame ();
,
The story is different when you are instructed to put a button on the Frame or draw it.
Suppose you add the Canvas class to frame. It overrides the canvas paint method, but the paint method is not called by the coder, but by the frame side when needed.
This is a little tricky. Actually, the processing system wants to give a depiction command to the frame, but the frame issues a depiction command to the canvas. In this flow, canvas will call the processing system.
Right now, I've only talked about language processing, but it may also apply if you want to operate the GUI from the CUI.
Override run in a class that inherits Thread. The GUI is generated in this run. And in main, I don't touch GUI classes, Start and use the class that inherits this Thread.
Class LinkedBlockingQueue When taking, this class can make the thread wait until the element comes, and can easily perform exclusive control. The GUI handles the process by looking at this queue.
The following program draws the coordinates of line in the order they arrived after waiting in the queue.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import javax.swing.JFrame;
public class Test {
public static LinkedBlockingQueue<int[]> drawQueue = null;
static {
drawQueue = new LinkedBlockingQueue<int[]>();
}
public static void main(String[] args) {
Thread canvasThread = new CanvasThread();
canvasThread.start();
Random rand = new Random(System.currentTimeMillis());
for (int i = 0; i < 120; i++) {
drawQueue.add(new int[] { rand.nextInt(CanvasThread.WIDTH),
rand.nextInt(CanvasThread.HEIGHT),
rand.nextInt(CanvasThread.WIDTH),
rand.nextInt(CanvasThread.HEIGHT) });
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
drawQueue.add(new int[]{});
}
}
class CanvasThread extends Thread {
public static final int HEIGHT = 400;
public static final int WIDTH = 600;
@Override
public void run() {
JFrame frame = new JFrame("test");
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
frame.add(new Canvas() {
@Override
public void paint(Graphics g) {
System.out.println("print start");
int[] x = null;
Random rand = new Random(System.currentTimeMillis());
try {
while ((x = Test2.drawQueue.take()).length == 4) {
g.setColor(new Color(rand.nextInt(256), rand
.nextInt(256), rand.nextInt(256)));
g.drawLine(x[0], x[1], x[2], x[3]);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("paint end");
}
});
}
}
Recommended Posts