我有一个线程#1。它显示了MainFrame。
然后,我启动一个线程池以执行一些任务。 线程#1应该等待线程池完成。我需要显示PopupDialog,它通知现在任务正在进行中。 PopupDialog应该总是仅位于我程序的顶部。
所有任务完成后,应关闭PopupDialog,线程1可以继续执行。
我该怎么做?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
/**
* @see https://stackoverflow.com/questions/24361899/frame-always-on-top-of-my-program-only
*/
public class TopTest {
private static JFrame mainFrame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
mainFrame = new JFrame("test");
mainFrame.setSize(800, 600);
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainFrame.setVisible(true);
final PopupDialog popupDialog = new PopupDialog();
mainFrame.addWindowListener(new WindowAdapter() {
/**
* {@inheritDoc}
*/
@Override
public void windowDeactivated(WindowEvent e) {
popupDialog.setAlwaysOnTop(false);
}
/**
* {@inheritDoc}
*/
@Override
public void windowActivated(WindowEvent e) {
popupDialog.setAlwaysOnTop(true);
}
});
startOtherThreads();
WindowEvent windowClosing = new WindowEvent(popupDialog, WindowEvent.WINDOW_CLOSING);
popupDialog.dispatchEvent(windowClosing);
}
});
}
public static void startOtherThreads() {
int NUM_THREADS = 8;
ExecutorService es = Executors.newFixedThreadPool(NUM_THREADS);
for (int i = 0; i < 5; i++) {
Task task = new Task();
es.execute(task); // submit that to be done
}
awaitTerminationAfterShutdown(es);
}
static class Task implements Runnable {
public Task() {
}
@Override
public void run() {
System.out.println("Each thread waiting for 10 sec");
try {
Thread.sleep(10000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
public static void awaitTerminationAfterShutdown(ExecutorService threadPool) {
threadPool.shutdown();
try {
if (!threadPool.awaitTermination(300, TimeUnit.SECONDS)) {
threadPool.shutdownNow();
}
} catch (InterruptedException ex) {
threadPool.shutdownNow();
Thread.currentThread().interrupt();
}
}
public static class PopupDialog extends JDialog {
public PopupDialog() {
super(mainFrame);
JLabel label = new JLabel("Waiting for thread pool completion...");
getContentPane().add(label, BorderLayout.CENTER);
setAlwaysOnTop(true);
setFocusable(false);
setPreferredSize(new Dimension(300, 100));
pack();
setLocationRelativeTo(mainFrame);
setVisible(true);
}
}
}
目前,PopupDialog位于所有程序的顶部(当所有其他线程正在执行时,我无法监听线程#1)。而且PopupDialog没有显示它的内容。