Java Swing – JPanel

Why hello there. So far we have learned about the basis of every Java Swing desktop application which was the JFrame (If you haven’t read it feel free to read that post before continuing). We learned many great things about the JFrame, but how do we start drawing and adding cool features to the JFrame? We should just be able to draw on the JFrame right? Well yes and no. Yes because as a matter of fact we actually can draw and add things directly on the JFrame; however, it isn’t always convenient especially for big applications. The application might crash if there are too many things going on the JFrame at the same time, and it would look really sloppy to try and cram everything into the Jframe. Instead of cramming everything on the JFrame we will actually put our graphics on JPanels, and then we just simply add the JPanels back on the JFrame. Sounds simple enough right. Depending on the type of application you are writing you might just have one JPanel, or you might have multiple JPanels.

JPanel Example:

 

* This is where we instantiate an object of the JPanel class, and in this case we will call it panel1.

– With JPanel:

– Without JPanel:

** This where we add the JPanel onto the JFrame; as you can see in the pictures above right now our JPanel is blank, so if you comment out this line of code you won’t see a difference.

This was a short post about the JPanel. Soon we will be adding some really cool things to our JPanels. Hopefully you stick around and continue to join me in this fun journey. Until next time.

Leave a comment