2011-04-12 95 views
4

我有一个swing应用程序,基本上,可以弹出一个模式对话框的主框架。 当模式对话框显示时,如果我切换到另一个窗口,如Firefox。然后切换回摆动应用程序。 JDialog不再在前面。模式对话框隐藏在主框架后面swich焦点

我不想将对话框AlwaysOnTop设置为true。因为那时对话框将在所有窗口之上包含其他进程中的窗口。

那么我应该怎么做,以便当我回头时,模态对话框仍然是最重要的?

BTW:这是一个小程序,所以主框架实际上以这种方式设置:

private static Frame findParentFrame(Container owner){ 
    Container c = owner; 
    while(c != null){ 
     if (c instanceof Frame) 
      return (Frame)c; 
     c = c.getParent(); 
    } 
    return (Frame)null; 
} 

回答

1

我不确定对话的形式是否是这里的关键问题。我已经测试过这种行为,并且当应用程序被最大化时,对话框总是弹出,而与模态无关。

import java.awt.event.ActionEvent; 
import javax.swing.JApplet; 
import javax.swing.SwingUtilities; 
import java.awt.Color; 
import java.awt.Container; 
import java.awt.FlowLayout; 
import java.awt.Frame; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JDialog; 

public class AppletTest extends JApplet 
     implements ActionListener 
{ 
    private static final long serialVersionUID = 1L; 
    private Frame findParentFrame() 
    { 
     Container c = this; 
     while(c != null) 
     { 
      if(c instanceof Frame) 
       return (Frame) c; 

      c = c.getParent(); 
     } 
     return (Frame) null; 
    } 
    private void createGUI() 
    { 
     Container content = getContentPane(); 
     content.setBackground(Color.white); 
     content.setLayout(new FlowLayout()); 
     content.add(new JButton("Button 1")); 
     content.add(new JButton("Button 2")); 
     content.add(new JButton("Button 3")); 
     JDialog d = new JDialog(findParentFrame()); 
     d.setModal(true); 
     d.setVisible(true); 
    } 

    public void init() 
    { 
     try 
     { 
      SwingUtilities.invokeAndWait(new Runnable() 
      { 
       public void run() 
       { 
        createGUI(); 
       } 
      }); 
     }catch(Exception e) 
     { 
      System.err.println("createGUI didn't successfully complete"); 
     } 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) 
    { 
    } 
} 

查看我提供的示例。您可以用d.setModal(true);对该行进行注释,结果将完全相同。 我建议你再次检查一下你的代码,或者把它展示给我们,因为看起来你可能错过了那里的东西。

PS:我在网上发现了一些其他类似破解的解决方案http://www.codeguru.com/forum/showthread.php?t=41536 我仍然专注于检查你的代码。

Oi &祝你好运,博罗。

2

确保JDialog实际上是模态。还可以尝试将主框架设置为所有者。

+0

哦,我刚刚注意到车主并不是主车架,我只是编辑了问题 – Leon 2011-04-12 18:31:17

+0

@Leon,我想我的答案仍然适用。将所有者设置为您想要附加JDialog的框架。另外,确保它实际上是模态的。 – jzd 2011-04-12 18:35:06

0

我想你所要求的是一个对话框,该对话框对于它的父应用程序/框架是模态的。当父母重新获得焦点时,可以使用Toolkit.getDefaultToolkit()。getSystemEventQueue()。 postEvent(AWTEvent e)将事件触发到对话框,使其弹回顶部。

0

感谢Boro的link

我有同样的问题,我需要解决。带有摇摆小程序的浏览器。弹出对话框,我点击浏览器,点击对话框,对话框消失在浏览器后面。我试了一切,但只有一件事帮助:

WindowListenerDialog并呼吁toFront()在听众的windowDeactivated()为我工作。