How to make Java singleton from .form?

I need to create a swing GUI using IDEA tool "UI Designer" and make it a Singleton.
I already have a ServerFace.form that is binded to class ServerFace.java I also have a class Index.java that makes the first initialization of ServerFace.

See the code of both classes below (there is no code in ServerFace.form):

ServerFace.java(class binded to 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 (class that gets instance of ServerFace.java):

import javax.swing.*;

public class Index{

    private static ServerFace _gui;

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

When I try to compile it throws an Exception "failed to create UI: java.lang.NullPointerException | null"
What's wrong and how to get it right?

2 comments
Comment actions Permalink

Most likely the exception happens because you've set the "custom create" flag for one of the components on your form and didn't provide any code in createUIComponents() to create the instance. Removing the "custom create" flag should fix the issue.

0
Comment actions Permalink

Thank you for the solution? it works!

PS: I had a "custom create" flag at "panel1"

0

Please sign in to leave a comment.