/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package swingqueueexample;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ConcurrentLinkedQueue;
public class SwingQueueExample {
private JTextArea outputArea;
private ConcurrentLinkedQueue<String> messageQueue;
public SwingQueueExample() {
JFrame frame = new JFrame("Queue Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
outputArea = new JTextArea();
outputArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(outputArea);
frame.add(scrollPane);
JButton startButton = new JButton("Start Task");
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
startBackgroundTask();
}
});
frame.add(startButton, java.awt.BorderLayout.SOUTH);
messageQueue = new ConcurrentLinkedQueue<>();
startQueueProcessor(); // Start a thread to process the queue
frame.setVisible(true);
}
private void startBackgroundTask() {
new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000); // Simulate a long-running task
messageQueue.offer("Task progress: " + (i + 1));
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
messageQueue.offer("Task completed!");
}).start();
}
private void startQueueProcessor() {
new Thread(() -> {
while (true) {
if (!messageQueue.isEmpty()) {
String message = messageQueue.poll();
SwingUtilities.invokeLater(() -> outputArea.append(message + "\n"));
}
try {
Thread.sleep(100); // Check queue periodically
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
break;
}
}
}).start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(SwingQueueExample::new);
}
}
Tidak ada komentar:
Posting Komentar