如何在同一个线程中创建JFrame以阻止它? [英] How to create JFrame in the same thread so that it blocks?

查看:270
本文介绍了如何在同一个线程中创建JFrame以阻止它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于调试目的,我需要在一个简单的窗口中在屏幕上绘制图像。

For debug purposes, I need to draw image on the screen in a simple window.

Swing在一个单独的消息循环线程中处理它的所有事件。这意味着,如果我执行以下操作:

Swing handles all it's events in a separate message loop thread. That means that if I do the following:

   while(true) {
     //Get screenshot
     BufferedImage screenshot = MSWindow.screenshot();
     //Create JFrame
     JFrame frame = new JFrame();
     Container main = frame.getContentPane();
     //This layout should force the JLabel as large as the window, am I right?
     main.setLayout(new GridLayout(1,1));
     //Create JLabel to display the screenshot
     JLabel label = new JLabel(new ImageIcon(screenshot));
     main.add(label);
     frame.pack();
     frame.setVisible(true);
     //Delay is allways good when meddling up with dangerous things
     Thread.sleep(2000);
   }

...我最终得到了很多JFrame。

... I end up with many many JFrames.

我以前使用JDialog阻塞并停止线程直到你按OK:

I used to use JDialog which is blocking and stops thread until you press OK:

JOptionPane.showMessageDialog(null, scrollPane, message, javax.swing.JOptionPane.INFORMATION_MESSAGE);

这有一个缺陷 - 你无法在任务栏上看到调试窗口。有时候,很难找到窗户最终的位置。这就是我想切换到JFrame的原因。

This has a flaw though - you can't see the debug window on the taskbar. Sometimes, it's hard to find where the window ended up. This is why I want to switch to JFrame.

我的问题是直截了当:如何让当前线程等到JFrame关闭

My question is straight up this: How to make current thread wait until JFrame is closed?

推荐答案


如何在同一个线程中创建JFrame以阻止它?

How to create JFrame in the same thread so that it blocks?

使用模态JDialog。

Use a modal JDialog.

JOptionPane.showMessageDialog(null, scrollPane, message, javax.swing.JOptionPane.INFORMATION_MESSAGE);




这有一个缺陷 - 你看不到调试窗口在任务栏上。

This has a flaw though - you can't see the debug window on the taskbar.

不要为对话框所有者使用null。确保指定所有者JFrame。每当您单击任务栏图标时,框架和子对话框都会显示。

Don't use null for the dialog owner. Make sure you specify the owner JFrame. Whenever you click on the taskbar icon the frame and child dialog will both show up.

这篇关于如何在同一个线程中创建JFrame以阻止它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆