• Post Reply Bookmark Topic Watch Topic
  • New Topic

Jframe Object  RSS feed

 
salvador rcn
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sometimes i have seen in the example code
to write...



and also i have seen ....
[CODE]
class myclass extends Jframe
{
}
myclass jf = new myclass() // This also creates a Jframe object
// do stuffs using jf.
which one is good ?

i dont understand why there is two ways(like above) of creating a Jframe object. when should i use latter one and when the former one ?
thanks
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it's a matter of preference and use most of the time. I typically will extend JFrame to place alot of initialization code in it, and also whatever else I want. That way I can keep all the code that deals with the particular frame in the same place.
Otherwise, if you are continually creating the same frame with the same type of behavior, in order to eliminate duplicate code, you would need to create some sort of factory method, and go from there.
But either way is okay -- it just really depends on what the frame is doing.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It might help if you understand that there are two different issues involved here. Your first example creates a new instance of the JFrame class. The second creates a new class that extends (or inherits) JFrame. In the later approach, you still need to create an instance in order to do anything. This would look something like this:

As Nathaniel mentioned, this is typically done so that you can add initialization code, usually with your own constructor. You can also add your own methods and fields that add to the base functionality of the JFrame class. For instance, you may have several JPanel objects that you need to juggle, deciding when the appropriate times are to display them. I'm sure there are lots of other reasons, but I hope you get the idea here.
You can often accomplish the same tasks without extending JFrame. However, when you have several frames in an application that preform similar tasks, this is a good way to encapsulate those similarities and reduce the amount of code you have to type. I think Nathaniel mentioned something along these lines, too.
Typically, I prefer extending JFrame. It tends to afford more flexibility in how I create the window. Of course, this is just my own personal opinion. I'm sure that the other method works just as well for many types of programs.
Layne
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!