2014-01-17 27 views
0

問題是從Java類中生成單例,該單例在IntellijIDEA中綁定到.form。如何從IntellijIDEA中的.form生成Java單例?

SSCCE: 我們需要使用IDEA工具「UI Designer」創建一個swing GUI,並將其設置爲Singleton。

我們已經有了綁定到類ServerFace.java的ServerFace.form 我們還有一個類Index.java,它使ServerFace的第一次初始化。

參見下面兩個類的代碼(有在ServerFace.form沒有代碼):

ServerFace.java(類綁定到ServerFace.form):

import javax.swing.*; 
public class ServerFace { 
    private JPanel panel1; 
    private JButton startServerButton; 
    private JButton stopServerButton; 
    private JButton clearLogButton; 
    private JTextArea textArea1; 

//Make it Singleton-------------------------------------- 
    private static volatile ServerFace instance; 

    public static ServerFace getInstance(){ 

     if (instance==null){ 
      synchronized (ServerFace.class){ 
       if(instance==null){ 
        try{ 
         instance=new ServerFace(); 
        }catch (Exception e){ 
         System.out.println("failed to create UI: "+e+" | "+e.getMessage()); 
        } 
       } 
      } 
     } 
     return instance; 
    } 

    private ServerFace() throws Exception{ 

    } 
    private void createUIComponents() { 
     // TODO: place custom component creation code here 
    } 
} 

Index.java(類這得到ServerFace.java的實例):

import javax.swing.*; 

public class Index{ 

    private static ServerFace _gui; 

    public static void main(String[] args){ 
     _gui = ServerFace.getInstance(); 
    } 
} 

當我嘗試編譯它拋出一個異常 「無法創建UI:顯示java.lang.NullPointerException | NULL」

我做錯了什麼,怎麼弄對吧?

+1

看起來'ServerFace'構造函數觸發'NullPointerException',你是向我們展示完整的代碼嗎? – BackSlash

+0

這裏有一個私人構造函數:private ServerFace()拋出異常{ } – DadUndead

+0

我完全知道這一點。但是在你向我們展示的代碼中,我看不到拋出'NullPointerException'的可能性,那麼你真正的代碼是什麼?如果您在編寫問題時刪除了構造函數中的代碼,請添加它 – BackSlash

回答

0

我終於找到了解決方案。問題是我的一個組件(panel1)有「自定義創建」標誌,但我沒有在createUIComponents()中提供任何代碼。當旗子被移除時它開始工作。 PS:感謝來自IDEA社區的Dmitry Jemerov。