2014-03-07 34 views
1

這是場景, 我的JFrame有一個按鈕,它會在點擊它時打開JDialog,它是一個模型對話框。 JDialog有另一個按鈕,我想打開另一個JFrmae點擊它時打開。從JDialog打開JFrame,它顯示在JDialog頂部

結果:另一個Jframe打開,但它不會到達頂部。它顯示在對話框下方。我想在該對話框的頂部打開第二個JFrame

可以使用secondFrame.setAlwaysOnTop(true);但我沒有控制權將其關閉或移動。

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JDialog; 
import javax.swing.JFrame; 
public class FrameTest 
{ 
    public static void main(String args[]) 
    { 
     JFrame firstFrame = new JFrame("My 1st Frame"); 
     JButton button = new JButton("Frame Click"); 

     button.addActionListener(new ActionListener() 
     { 

      @Override 
      public void actionPerformed(ActionEvent e) 
      { 
       JDialog dialog = new JDialog(); 
       dialog.setSize(100, 100); 
       dialog.setModal(true); 
       JButton button1 = new JButton("Dialog Click"); 

       button1.addActionListener(new ActionListener() 
       { 
        @Override 
        public void actionPerformed(ActionEvent e) 
        { 
         JFrame secondFrame = new JFrame("My 2nd Frame"); 
         secondFrame.setVisible(true); 
         secondFrame.setSize(400, 200); 
         secondFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
         secondFrame.setAlwaysOnTop(true); 
        } 
       }); 

       dialog.add(button1); 
       dialog.setVisible(true); 
      } 
     }); 

     firstFrame.add(button); 
     firstFrame.setVisible(true); 
     firstFrame.setSize(400, 200); 
     firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 
} 
+0

調查模態類型。另外,你有沒有考慮過不使用jdialog,而只是使用框架?你有更多的控制框架(在我看來)。 – TheOneWhoPrograms

+1

請參閱[使用多個JFrames,好/壞實踐?](http://stackoverflow.com/q/9554636/2587435)。查看一些更好解決方案的接受答案。 –

+0

你知道'dialog.setModal(true);'是什麼意思嗎? –

回答

4

的JDialog還有一個按鈕,我想打開另一個JFrmae打開時 點擊它。

不要那樣做。典型的Swing應用程序有一個主要的JFrame和幾個JDialog s。請參閱本主題The Use of Multiple JFrames, Good/Bad Practice?

結果:另一個JFrame的開放,但它不會來的top.It顯示 下dialog.I想開上對話框頂部的第二JFrame中。

當然,這是因爲對話框是模態的。

可以使用secondFrame.setAlwaysOnTop(true);但我沒有控制到 關閉它或移動它。

它不會解決任何問題,因爲問題與對話中的模態有關。看到這篇文章:How to Use Modality in Dialogs瞭解模態如何工作。 this answer也有解釋。