When to use JFrame, JLabel, and JPanel

18,814

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.

Share:
18,814
Mike Warren
Author by

Mike Warren

I am a software developer in test, with an affinity for other things such as math.

Updated on June 04, 2022

Comments

  • Mike Warren
    Mike Warren almost 2 years

    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?

  • GHC
    GHC over 10 years
    This doesn't seem to answer the question fully, can you expand?
  • Mike Warren
    Mike Warren over 10 years
    And why did you name the class JFrame? Doesn't that already cause problems?