Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It is better for various reasons, including:</p> <ul> <li>In most Swing components, custom painting is achieved by overriding the <code>paintComponent(Graphics)</code> method. Top-level Swing containers (e.g. <code>JFrame</code>, <code>JApplet</code>, <code>JWindow</code>) have only <code>paint(Graphics)</code>. As a result of the common method for painting, people who answer often forget about this difference between common and top-level components, and therefore suggest silly advice. ;)</li> <li>A <code>JComponent</code> can be added to a <code>JFrame</code>, or a <code>JApplet</code>, or a <code>JDialog</code>, or a constraint of a layout in a <code>JPanel</code>, or a <code>JInternalFrame</code>, or a.. Just when you think your GUI is complete, the client says "Hey, wouldn't it be great to throw in a tool-bar &amp; offer it as an applet as well?" The <code>JComponent</code> approach adapts easily to that.</li> <li>As explained (complete with code!) by Richante, it is easier to calculate the co-ordinates required for painting the custom component, and if it has a preferred size, to size the <code>JFrame</code> to be 'exactly the right size' to contain the GUI (using <code>pack()</code>). That is especially the case when other components are added as well.</li> </ul> <hr> <p>Now, two minor disagreements with the advice offered.</p> <p>If the entire component is custom painted, it might be better to simply put a <code>BufferedImage</code> inside an <code>ImageIcon</code>/<code>JLabel</code> combo. Here is an example of <a href="https://stackoverflow.com/a/10055672/418556">painting to an image</a>.<br> When it comes time to update it:</p> <ol> <li>Call <code>getGraphics()</code> for a <code>Graphics</code> or <code>createGraphics()</code> for a <code>Graphics2D</code></li> <li>Draw the custom painting to that graphics instance</li> <li>Dispose of the graphics instance</li> <li>Call <code>repaint()</code> on the label.</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload