2017-03-14 24 views
0

這是我的第一個問題,所以如果存在任何錯誤,請糾正我的錯誤。我在Java(Eclipse)中創建了一個面板框架,應用程序在按下十字按鈕時不會關閉

這是代碼,我嘗試使用面板製作一個框架,但應用程序在按關閉按鈕時不退出。

當我試圖設置默認關閉操作退出時,它顯示我一個錯誤。

所以,請幫助我。

import java.awt.*; 

public class FramewithPanel { 

    private Frame f; 
    private Panel p; 

    public FramewithPanel(String title){ 
     f = new Frame(title); 
     p = new Panel(); 
    } 

    public void LaunchFrame() { 
     f.setSize(200,200); 
     f.setBackground(Color.blue); 
     f.setLayout(null); 

     p.setSize(100,100); 
     p.setBackground(Color.yellow); 

     f.add(p); 
     f.setVisible(true); 
    } 



    public static void main(String args[]) { 
     FramewithPanel guiWindow = 
      new FramewithPanel("Frame with Panel"); 

     guiWindow.LaunchFrame(); 
    } 
} 
+1

在你的問題你說的是一個錯誤。分享錯誤/堆棧跟蹤可能很有用。 – Nrzonline

回答

0

看到,因爲你提到你是使用Frame,而不是替代JFrame堅持,最簡單的解決方案是增加一個WindowListener像這樣:

f.addWindowListener(new WindowAdapter() { 
    @Override 
    public void windowClosing(WindowEvent e) { 
     System.exit(0); 
    } 
}); 

Et v oila!

+1

非常感謝您的回答! –

1

我猜你想使用JFrame代替Frame,爲Frame沒有默認的關閉操作。相反,它根本不會關閉,只會生成WindowEvent類型的WINDOW_CLOSING

所以你要麼

private JFrame f; 

// and in the constructor 
f = new JFrame(title); 
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); 

f = new Frame(title); 
f.addWindowListener(new WindowAdapter() { 

    @Override 
    public void windowClosing(WindowEvent e) { 
     f.dispose(); 
    } 

}); 
+0

非常感謝,但我已經知道,我只想使用一個框架。我相信,當JFrame不在時,Frame也被使用過。 –

+0

@Sarthak你完全正確。雖然我通常不推薦它,但您當然也可以使用「Frame」。 'WindowListener'和'defaultCloseOperation'完全一樣。只是它在稍微不同的時間被調用,但這對你的情況無關緊要。 – Izruo

+0

非常感謝,夥計! –

相關問題