2013-09-21 85 views
4

我在NetBeans中設計了兩個JFrame。當我點擊「規則」按鈕(即放置在JFrame1上),然後它打開第二個JFrame(但JFrame2打開JFrame1的窗口,這就是我不想要的)。 在第二個JFrame中有一個「關閉」按鈕。但是當我點擊這個按鈕時,我想要打開JFrame1並且它也在工作,但是JFrame2實際上並未關閉,並且JFrame1出現在JFrame2上。單擊JButton後關閉jFrame

總之主要形式是JFrame1。當我點擊JFrame1中的「規則」按鈕時,它將打開JFrame1,並在JFrame1上打開JFrame2,當它被點擊主窗體(即JFrame1)時,會有一個「關閉」按鈕,但它是通過JFrame2啓動的。

的之情況是JFframe1 - > JFrame2 - > JFrame1

現在的問題是點擊「規則」按鈕後,JFrame1應該被關閉,JFrame2顯示在屏幕上,反之亦然。

+2

使用'處置()'方法要關閉在框架上。但不建議使用多個「JFrames」,而應考慮多個對話框或內部框架。 – 2013-09-21 09:57:31

+2

你也可以考慮[使用多個JFrames,好/壞實踐?](http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-bad-practice)。使用幀進行表單切換本質上是非常糟糕的設計。我會考慮使用'JPanel'作爲應用程序的主容器,並使用'JTabbedPane'或'CardLayout'來允許用戶在它們之間切換 - 恕我直言... – MadProgrammer

回答

7

假設你的按鈕有一個ActionListener,點擊「規則按鈕」放於後:

 JFrame1.dispose(); //Remove JFrame 1 
     JFrame2.setVisible(true) //Show other frame 

然後reverese他們相反的反應

+1

此解決方案不起作用 –

3

Somethig這應該是在構造函數或方法它創建JFrame2:

btnCancel.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     //call another method in the same class which will close this Jframe 
     CloseFrame(); 
    } 
}); 

它的方法,它應該關閉JFrame2

public void CloseFrame(){ 
    super.dispose(); 
} 
+0

而不僅僅是代碼,嘗試也解釋爲什麼這段代碼需要在構造函數/方法上。 –

+0

對不起,我忘了解釋應該在哪裏應用CloseFrame方法。現在解釋。 –

0

我不是專家,但是,我也遇到了這個問題。如果您將第二個JFrame設置爲隱藏,當您點擊「取消」時,它將關閉第二個JFrame。

//this is the code for the "cancel" button action listener 
public void actionPerformed(ActionEvent e) { 
    setVisible(false);//hides the second JFrame and returns to the primary 
0

這個工作對我來說(Frame1RegScreenFrame2MainScreen):

RegScreen.this.setVisible(false); 

new MainScreen().setVisible(true); 

希望這有助於:) Regscreen是原來的框架在啓動時打開。

0

如果這不起作用,試試這個

JFrame1.dispose(); //Remove JFrame 1 
     JFrame2.setVisible(true) //Show other frame 
JFrame2.setVisible(true); 
this.dispose(); 
0
  1. 有一個MainClass帶有main()方法。
  2. 讓MainClass擁有main()方法來封裝您的JFrame1和JFrame2引用變量。除非有特定原因,否則不要讓JFrame1或JFrame2包含main()。
  3. 在某個JFrame對象中點擊某物後,實例化/使其他JFrame對象可見並通過您的MainProgram.JFrame對象方法處置其自身。

例子:

//btn event inside 1st JFrame/window 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           
     MainProgram.openResultsForm(); //MainProgram opens 2nd window 
     MainProgram.queryEntryForm.dispose(); //MainProgam closes this, 
               //the 1st window 
    }