2

Experimenting with Swing, I learnt that there are two ways of using JOptionPane and other classes from Swing:

1) Declare

private JOptionPane info1 = new JOptionPane();

before the class constructor and then use info1.showMessageDialog() in the relevant method (in this case I get message that showMessageDialog should be accessed in a static way) , or

2) In the relevant method use

JOptionPane.showMessageDialog()

without declaring the object of JOPtionPane class at all.

My question is, what are the differences, drawbacks and benefits of these two approaches? Does it extend to other Swing classes?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Alex
  • 944
  • 4
  • 15
  • 28

1 Answers1

3

The second option would be preferred because you really don't need to create a JOptionPane object when you're trying to merely project a MessageDialog to the user.

In fact if you open the tutorial: "How to Make Dialogs", this option happens to be the suggested mechanism to handle dialogs in Swing

Sujay
  • 6,753
  • 2
  • 30
  • 49
  • +1 - I'd also add that the factory methods will generally provide you with all the options you need. It makes it easier to quickly popup a dialog then going down the path of having to configure it yourself – MadProgrammer Aug 28 '12 at 01:25
  • thanks. In such case, is there any rule that specifies when objects shouldbe created at all? – Alex Aug 28 '12 at 01:36
  • @Alex: I'm sorry, I didn't fully understand your comment above. Which cases are we talking about? – Sujay Aug 28 '12 at 02:06
  • I'm sorry it was too vageue: if option 2 was better because the object was called only once, is this the case with the object of any other class called just once? – Alex Aug 28 '12 at 03:54
  • @Alex: I don't think there's a specific answer to that, however if there're `static` methods available (for example), you really don't have to instantiate an object to call that particular method. But I think comments're not a good place to discuss a question. So maybe you can consider posing this as a question in itself :) – Sujay Aug 28 '12 at 04:24
  • @Sujay: along these lines? http://stackoverflow.com/questions/2671496/java-when-to-use-static-methods – Alex Aug 28 '12 at 05:11