简体   繁体   中英

why JPanel is not being shown in JFrame?

New to java. I have two classes in two seperate java files.

Code for Grid.java is:

package grid;

import java.awt.*;
import javax.swing.*;

public class Grid {


    public static void main(String[] args){

        JFrame f = new JFrame("The title");

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(500,400);
        f.setResizable(false);
        f.setVisible(true);


        GridSupport g = new GridSupport();
        f.add(g); //getting error when i don't extends GridSupport to JPanel

    }

}

Code for GridSuppoer.java is:

package grid;

import java.awt.*;

import javax.swing.*;


public class GridSupport extends JPanel{

    private JPanel p;
    private JButton b;

    public GridSupport(){



        p = new JPanel();
        p.setBackground(Color.GREEN);
        p.setSize(100, 100);

        b = new JButton("Click me!");
        p.add(b);

    }

}

I want to know 1) why JPanel is not being shown ? 2) if i put both classes in a same file i don't need to extends GridSupport class to JPanel but when i put them in two seperate files i need to extends JPanel otherwise it is showing error .Why is that?

JFrame f = new JFrame("The title");
GridSupport g = new GridSupport();
f.add(g)
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,400);
f.setResizable(false);
f.setVisible(true);

Add the GridSupprt before you set frame visible. Generally, you should make sure to add all components to the frame before you make it visible

GridSupport itself is a JPanel. So when you create a new JPanel inside of GridSupport and just add everything inside that Panel, you still need to add the inside panel to the GridSupport

public class GridSupport extends JPanel{

    private JButton b;

    public GridSupport(){

        setBackground(Color.GREEN);
        setSize(100, 100);

        b = new JButton("Click me!");
        add(b);

    }
}

Because GridSupport extends JPanel you do not need to create a JPanel inside it (as it is a JPanel itself, with a few extra features. Your GridSupport class should look something like so:

package grid;

import java.awt.*;

import javax.swing.*;


public class GridSupport extends JPanel{

    private JButton b;

    public GridSupport(){
        this.setBackground(Color.GREEN);
        this.setSize(100, 100);

        b = new JButton("Click me!");
        this.add(b);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM