Otanan
Otanan

Reputation: 448

Dimension Object Advantages & Disadvantages?

When using a JFrame, I noticed some people spent their time doing

 setSize(new Dimension(400,400));

rather than simply

setSize(400,400);

Are there any particular advantages to using the prior rather than the latter if not storing the object in a variable?

Also, can I not draw directly in JFrame? do I need a canvas for it? is it simply best to extend Canvas? no JComponent alternative to Canvas?

Upvotes: 1

Views: 178

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347214

When using a JFrame, I noticed some people spent their time doing

setSize(new Dimension(400,400));

rather than simply

setSize(400,400);

Are there any particular advantages to using the prior rather than the latter if not storing the object in a variable?

No. Basically it's just a connivance so you don't need to do something like...

Dimension dim = new Dimension(400, 400);
setSize(dim.width, dim.height);

You could just do

setSize(dim);

Having said that, you shouldn't rely on it, as pack will produce better results, if you've build you base components properly...

Also, can I not draw directly in JFrame? do I need a canvas for it?

Generally, no, you shouldn't paint directly to the frame, there are a number of important reasons why, to start with, JFrame (and other top level containers) are not double buffered, so repaints will flicker, also, the frame decorations are painted WITHIN the frame, so if you paint directly to the frame, you run the risk of painting under the decorations...

For example...

And just because I can't be bothered typing it again...

is it simply best to extend Canvas? no JComponent alternative to Canvas?

This depends on your needs. Canvas is a heavy weight component, so adding it to a JFrame can cause problems. It is also not double buffered, so either you need to implement a BufferStrategy or implement your own double buffering...

And no, there is no Swing alternative to Canvas, but remember, Swing components are double buffered already and (at least since Java 6...I think), support hard ware acceleration through either Direct3D or OpenGL where available...

Upvotes: 4

Related Questions