javaswingjframejpaneljcomponent

Adding a JButton to a JPanel to a JFrame


I am trying to learn how to use JFrames. I have a JFrame, that has a JPanel, that has a JButton. I add the JButton to the JPanel, which is added to the JFrame. My code is below, I cannot figure out why this won't work. It should not matter if I do not have a layout set correct? I'm just trying to figure this out to help me solve a larger problem using layouts, any help is appreciated. Thanks

public class one {
    public static void main(String[] args) {

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().setLayout(null);
        f.setBounds(10, 10, 500, 500);

        JPanel p = new JPanel();
        p.setVisible(true);
        p.setBackground(Color.BLACK);

        JButton b = new JButton("Testing");
        b.setBounds(60, 60, 100, 100);
        b.setVisible(true);



        p.add(b);

        f.add(p);

        f.setVisible(true);
    }
}

Instead running this code only opens a blank JFrame.


Solution

  • If the JPanel contains all the Components you should set the JPanel as ContentPane for the JFrame.

    So you need to change this

    f.add(p);
    

    to

    f.setContentPane(p);
    

    If the JPanel is just for specific Components you should set bounds for the JPanel and add it.

    Example for BorderLayout:

    f.add(p, BorderLayout.CENTER);