Set up a Java GUI in a separate thread to keep the main

I want to use the GUI for sub processing

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.

Set up GUI in a separate thread from the main thread

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.

Use Linked Blocking Queue to exchange data

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.

sample

The following program draws the coordinates of line in the order they arrived after waiting in the queue.

WS000044.JPG

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

Set up a Java GUI in a separate thread to keep the main
Two ways to start a thread in Java + @
[Android / Java] Set up a button to return to Fragment
Create a method to return the tax rate in Java
How to set up a proxy with authentication in Feign
The milliseconds to set in /lib/calendars.properties of Java jre is UTC
Java reference to understand in the figure
[Java] How to set the Date time to 00:00:00
What is the main method in Java?
Steps to set a favicon in Rails
How to get the date in java
[Java Bronze] 5 problems to keep in mind
The story of forgetting to close a file in Java and failing
A memorandum to clean up the code Ruby
How to display a web page in Java
Measure the size of a folder in Java
Code to escape a JSON string in Java
Try to create a bulletin board in Java
Set the time of LocalDateTime to a specific time
Set HTTP Keep Alive Timeout in Java HTTP Client
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
Set the source of the library set as a dependency in IntelliJ as a separate module of the project
[Java] Read the file in src / main / resources
Set up a webhook in Shopify's custom app
Pass the condition to be used in the Java8 lambda expression filter () as a parameter
How to save a file with the specified extension under the directory specified in Java to the list
[Android Studio] I want to set restrictions on the values registered in EditText [Java]
[Rails] I want to display the link destination of link_to in a separate tab
Summary of how to use the proxy set in IE when connecting with Java
How to create a Java environment in just 3 seconds
How to set the display time to Japan time in Rails
[Java] How to omit the private constructor in Lombok
Source used to get the redirect source URL in Java
I tried to create a Clova skill in Java
How to create a data URI (base64) in Java
A note for Initializing Fields in the Java tutorial
[Ruby / Rails] Set a unique (unique) value in the class
I tried to make a login function in Java
Steps to set up a VNC server on CentOS 8.3
Java classes and instances to understand in the figure
How to convert A to a and a to A using AND and OR in Java
How to convert a file to a byte array in Java
Try to solve a restricted FizzBuzz problem in Java
[Rails 6] How to set a background image in Rails [CSS]
I tried to implement the Euclidean algorithm in Java
How to get the class name / method name running in Java
A quick explanation of the five types of static in Java
Let's make a calculator application in Java ~ Display the application window
How to set chrony when the time shifts in CentOS7
Convert a Java byte array to a string in hexadecimal notation
[Beginner] I made a program to sell cakes in Java
[Android, Java] Convenient method to calculate the difference in days
How to create a placeholder part to use in the IN clause
I just wanted to make a Reactive Property in Java
How to store a string from ArrayList to String in Java (Personal)
Set up Gradle multi-project in IntelliJ to build JAR file
How to add the same Indexes in a nested array
I tried to convert a string to a LocalDate type in Java
How to develop and register a Sota app in Java
How to simulate uploading a post-object form to OSS in Java
How to derive the last day of the month in Java