Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);

}
like image 277
Anonymous181 Avatar asked May 04 '12 04:05

Anonymous181


People also ask

How do you extend a JFrame?

The class myFrame extends the class JFrame . The paint() method of a JFrame object is called by the Java system (not by you) to finish the display. Most of the graphic is done; paint() just finishes it. If you override the paint() method, you can display your own components in the frame.

Should you extend JFrame?

Avoid extending JFrame as it ties your GUI to being, well a JFrame. If instead you concentrate on creating JPanels instead, then you have the freedom to use these JPanels anywhere needed -- in a JFrame, or JDialog, or JApplet, or inside of another JPanel, or swapped with other JPanels via a CardLayout.

Can you extend JFrame on a JPanel?

You can't do it. Jpanel and jframe are both classes and java doesn't support multiple inheritance of classes. Only one class and many interfaces. Don't extend frame or other top level containers.

Can you add a JFrame to a JFrame?

You can't put one JFrame inside another. Change your design so that the Game window content is on a JPanel and the Menu is on another JPanel .


2 Answers

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.

like image 85
MByD Avatar answered Oct 04 '22 00:10

MByD


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.
like image 45
Hovercraft Full Of Eels Avatar answered Oct 04 '22 00:10

Hovercraft Full Of Eels