Why I should use a JPanel?

后端 未结 6 1715
你的背包
你的背包 2021-01-13 15:32

What\'s the difference between:

public class Test {

    public static void main(String[] args) {
        JButton button= new JButton(\"1\");
        button.         


        
6条回答
  •  生来不讨喜
    2021-01-13 15:56

    Why I should use a JPanel?

    You use a JPanel for one or more of the following benefits:

    • To group components together.
    • To better organize your components.
    • To enable us to use multiple layouts and combine their effects. (For example a GridLayout for number pad, a CardLayout for display panel where you can switch drawings).
    • To break down a large problem into sub-problems. So instead of implementing everything in one big frame, you can concentrate implementing the properties of each individual panels (such as layout, dimension, background image, background color..etc)
    • For reusability if you have customized panels. A common panel can be used by different classes.
    • For easy debugging, since you can test each panel individually.
    • For scalability.
    • For maintainability.

    Usually I perceive a JFrame like a real life painting frame and JPanel like a piece of blank paper. We don't paint directly onto the frame. Instead, we paint on a piece of paper, and insert the paper into the frame. Painting directly on the frame is possible, but no one does that.

    The same goes with JFrame and JPanel. We can add components directly to the frame, but usually we add it to the panel, then add the panel to the frame.

提交回复
热议问题