Java – When to use JFrame, JLabel, and JPanel


I have been, for a long time, wondering when to use JFrame and JPanel. I was told by textbook, in-person, and via internet search some reasons, but of course, it took me looking at the Java documentation to figure out that a JPanel has the paintComponent(Graphics); method, which allows you to specify what to do to the object itself, unlike JFrame. Also, JPanels are nestable, allowing for more complex graphics than you could achieve with just one container. I also stumbled upon the fact that a JLabel is also a container. (It even has a freaking layout!) Now my question is: when should I be using a JLabel and when should I be using a JPanel?

//I know that you can put JLabels inside a JPanel, and by accident, that a JPanel is more expensive than a JLabel. I, in the long run, plan on making a cashier game that involves some lightweight container for the "money" that moves to the customer's hand upon clicking. I was thinking about using JLabels for the monetary amounts (dollar bills and coins), and the JPanel to serve as the overhead view of the transaction(s). I was also thinking about invoking repaint() (which, to my understanding, can simulate animation) on the "money labels" themselves. This is a double-question, but would you see this as the least expensive way to go about it?

Best Solution

For the most part, JPanel is a container that allows for better organization. When you need to organize your components of your gui, you should use a JPanel and define a layout for the JPanel. You can also nest JPanels within each other and etc. JLabels don't have the capability of defining layouts for further components to be displayed inside the JLabel.