Anonymous181
Anonymous181

Reputation: 1873

Extending a JFrame

What are the pros and cons of extending a JFrame rather than create a new JFrame?

For example:

public class Test extends JFrame {

setVisible(true);

}

or

public class Test {

JFrame test = new JFrame():

test.setVisible(true);

}

Upvotes: 11

Views: 10700

Answers (4)

Jasonw
Jasonw

Reputation: 5064

If extending JFrame, I would want to modify/customize my current Jframe class and so subclass can use this customized implementation.

If there nothing that I want to do change in the JFrame class, just use the existing like in second snippet that you've given in your code. By use, I mean by creating other JComponent (button/label for examples), etc, in a JPanel and create an object Test and set the JFrame contentPane to this object. Something like

public class Test extends JPanel {

   public class() {
    // add buttons/label here
   }
   ...

   private static void createAndShowGUI() {
       JFrame frame = new JFrame();

       Test object = new Test();
       frame.setContentPane(object.setOpaque(true));

       frame.setVisible(true);
   }
...
}

Upvotes: 2

Aligus
Aligus

Reputation: 1605

One of the rules of OOD: If you can not inherit (extend) the classes you do not inherit their.

Inheritance increases the complexity and connectedness of the program and potentially lead to new errors. In your case there are not any reasons to extend class.

You should extends classes only when you need to get access to protected members and/or or get polymorphic behavior (override virtual methods).

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

pros of not extending JFrame (or any Swing component for that matter):

  • Avoid unintentional method overrides. I've stepped into this several times, first when I gave my class int getX() and int getY() methods. Try it and you'll see some not so funny abnormal behaviors.
  • Simplify the method options available when using Eclipse or NetBeans to only those methods you've created. This is actually my favorite advantage.
  • Gearing your GUI's to create JPanels rather than JFrames which increases deployment flexibility 100-fold.
  • And most importantly, exposing only that which needs exposing.

Upvotes: 10

MByD
MByD

Reputation: 137272

You should not extend a class, unless you want to actually extend its functionality, in the example you've shown, you should use option 2, as option 1 is an abuse of the extending feature.

In other words - as long as the answer to the question is Test a JFrame? is NO, it should not extend JFrame.

Upvotes: 11

Related Questions