1

I was used to do java swing programming with netbeans drag and drop, and never really cared too much about the code it generated. Now I am in the process of learning to code GUIs without drag and drops.

The fundamental problem occurred to me was, whether the window I am going to make IS_A JFrame or HAS_A JFrame. i.e whether to use inheritance or composition.

if MyWindow is a JFrame

public class MyWindow extends JFrame{

}

if MyWindow has a JFrame

 public class MyWindow{
     private JFrame frame; 
 }

Both seems fine to me. But I guess there should be a right way to do it out of these two. What is the correct way, and why?

DesirePRG
  • 6,122
  • 15
  • 69
  • 114

1 Answers1

0

If you want your class to behave as a window, then, you should extend it from JFrame (at least in my opinion). To my knowledge, this is how you should go about it.

If on the other hand, you want a class which has access to a window then you would go with the second option. That being said, you would still, at some point need to initialize a class which extends from JFrame.

EDIT: The answer to the question does say that, however it also says that it depends on what you are after. If I am understanding the answer correctly (maybe others could comment on this), if you have a scenario where you need a frame to print a list to a table, you could have a class which extends Frame and provides a utility method which takes in a list and prints it to a table. Your logic would then instantiate this class instead of the actual JFrame and use it to show the data.

My approach is that usually, I have a class which extends JFrame and provides a series of methods which make printing data easy. I would then have another class, which links logic and view layers. This class will have a reference to the JFrame extending class.

npinti
  • 51,780
  • 5
  • 72
  • 96
  • the question pointed out by @assylias states that composition is preffered. What are your thoughts about it? – DesirePRG Apr 14 '15 at 13:09
  • @DesirePRG: I have tried to amplify my answer. If you have any further queries, please let me know. – npinti Apr 14 '15 at 13:21