0

In a desktop application created using java and spring, the GUI forms are created as singleton beans and therefore whenever a form is displayed, all the preveously entered values are there. Is there a better way to get a fresh form than clearing each form field through java code? Thanks in advance

Dilini Rajapaksha
  • 2,610
  • 4
  • 30
  • 41
  • is it common practice to use singleton beans in GUI apps? And, is it common to use springframework to create GUI apps? It seems sort of surprising to me, because GUI & spring doesn't seem like a good fit. But perhaps what you want is to use prototype scope beans rather than the default singleton scope. – Kevin Mar 22 '12 at 15:25
  • Is there a reason you chose singleton scope for this form object? – Roy Truelove Mar 22 '12 at 15:29
  • This is an half way developed application that I have to work with. Is there any better way to implement the same? – Dilini Rajapaksha Mar 26 '12 at 13:44

3 Answers3

2

You could force a new singleton to be instantiated like this

public class MyForm {
    // The instance
    private static MyForm instance = new MyForm();
    // Private constructor prevents instantiation from other classes
    private MyForm() { }
    // Get the singleton
    public static MyForm getInstance() { return instance; }

    // Force a new instance to be created         
    public static void resetInstance() {
           instance = new MyForm();
    }
}

But this is not really singleton behaviour anymore and maybe you should just use a new instantiated class. Something like:

myPanel.removeAll();
myPanel.add(new MyForm());

(the constructor should become public of course)

Joost
  • 3,169
  • 2
  • 22
  • 40
  • Thanks, I'll try your second sugession. – Dilini Rajapaksha Mar 29 '12 at 03:06
  • I think I found a better solution, but not sure whether it is the correct way. I override the `dispose` method and called `init` method after `super.dispose()`, in the `init` method, added the following line at the begining: `getContentPane().removeAll();`. It works well for my requirement, when I want the data to remain in the form, I simply hide the form and when I want a fresh form, I dispose the form and show the form again. If you find any faults in this method, please comment. – Dilini Rajapaksha Apr 04 '12 at 05:32
1

I would suggest a simpler alternative, please use singleton=false. If you want to retain some of the initialization snippets, then use init method or bean post processors.

questzen
  • 3,260
  • 18
  • 21
0

I override the dispose method and called init method after super.dispose(), in the init method, added the following line at the begining: getContentPane().removeAll();. It works well for my requirement, when I want the data to remain in the form, I simply hide the form and when I want a fresh form, I dispose the form and show the form again.

Dilini Rajapaksha
  • 2,610
  • 4
  • 30
  • 41