I’ve just started coding video games and I’ve heard that doing all your drawing on a JPanel and attaching that panel onto a JFrame is better than simply drawing onto the JFrame. I was just wondering why is this better?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It is better for various reasons, including:
paintComponent(Graphics)method. Top-level Swing containers (e.g.JFrame,JApplet,JWindow) have onlypaint(Graphics). 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. 😉JComponentcan be added to aJFrame, or aJApplet, or aJDialog, or a constraint of a layout in aJPanel, or aJInternalFrame, 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 & offer it as an applet as well?” TheJComponentapproach adapts easily to that.JFrameto be ‘exactly the right size’ to contain the GUI (usingpack()). That is especially the case when other components are added as well.Now, two minor disagreements with the advice offered.
If the entire component is custom painted, it might be better to simply put a
BufferedImageinside anImageIcon/JLabelcombo. Here is an example of painting to an image.When it comes time to update it:
getGraphics()for aGraphicsorcreateGraphics()for aGraphics2Drepaint()on the label.