Why my Swing GUI is not showing all the buttons added?

Viewed 191

Can someone please tell me why my Java Swing GUI is not showing all the added buttons on the frame? When I add 5 buttons, it shows only 4 of them and if I add 4 buttons, it shows only 3 of them.

Please let me know what the problem is with this.

I also tried to add them on the panel but then the GUI didn't show a single one.

package p2;
import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Gui extends JFrame {
    
    public Gui(){
    //Frame 
        JFrame fr=new JFrame("Calculator");
    //Panel
        JPanel p=new  JPanel();
        p.setBounds(10, 10, 200, 200);
        p.setBackground(Color.cyan);
    //Button    
        JButton b1=new JButton("Button 1");
        b1.setBounds(20, 20, 40, 30);
        JButton b2=new JButton("Button 2");
        b2.setBounds(20, 80, 40, 30);
        
        fr.add(p);
        p.add(b1);p.add(b2);
        fr.setVisible(true);
        fr.setSize(300, 400);
        fr.setLayout(null);
        
    }



    public static void main(String[] args) {
        new Gui();
    }
}
2 Answers

It is because of the following line:

fr.setLayout(null);

Just remove it and it will work.

First of all: don't use the "null" layout. But when you use any layout, you must set it before any component is added.

To fix your issue you simply need move up fr.setLayout(null)

import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Gui extends JFrame {

    public Gui() {
        // Frame
        JFrame fr = new JFrame("Calculator");
        // Panel
        JPanel p = new JPanel();
        p.setBounds(10, 10, 200, 200);
        p.setBackground(Color.cyan);
        // Button
        JButton b1 = new JButton("Button 1");
        b1.setBounds(20, 20, 40, 30);
        JButton b2 = new JButton("Button 2");
        b2.setBounds(20, 80, 40, 30);

        fr.setLayout(null); // set layout before adding of components.
        fr.add(p);
        p.add(b1);
        p.add(b2);
        fr.setVisible(true);
        fr.setSize(300, 400);

    }

    public static void main(String[] args) {
        new Gui();
    }
}
Related