I am trying to make a calculator using JFrame
. JPanel
doesn't display anything after I create more than 5 buttons. Here is my code:
JFrame:
package graphics;
import java.awt.*;
import javax.swing.*;
public class Driver01 {
public static void main(String[] args) {
JFrame frame = new JFrame("Basic Calculator");
frame.setContentPane(new Panel01());
frame.setSize(400, 500);
frame.setLocation(850, 100);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(new Panel01());
frame.setAlwaysOnTop(true);
}
}
And JPanel:
package graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
public class Panel01 extends JPanel {
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b0;
GridBagConstraints gbc = new GridBagConstraints();
public Panel01() {
setLayout(new GridBagLayout());
b1 = new JButton("1");
gbc.gridx = 2;
gbc.gridy = 2;
add(b1, gbc);
b2 = new JButton("2");
gbc.gridx = 3;
gbc.gridy = 2;
add(b2, gbc);
b3 = new JButton("3");
gbc.gridx = 4;
gbc.gridy = 2;
add(b3, gbc);
b4 = new JButton("4");
gbc.gridx = 2;
gbc.gridy = 3;
add(b4, gbc);
b5 = new JButton("5");
gbc.gridx = 3;
gbc.gridy = 3;
add(b5, gbc);
// b6 = new JButton("6");
// gbc.gridx = 4;
// gbc.gridy = 3;
// add(b6, gbc);
// b7 = new JButton("7");
// gbc.gridx = 2;
// gbc.gridy = 4;
// add(b7, gbc);
// b8 = new JButton("8");
// gbc.gridx = 3;
// gbc.gridy = 4;
// add(b8, gbc);
// b9 = new JButton("9");
// gbc.gridx = 4;
// gbc.gridy = 4;
// add(b9, gbc);
// b0 = new JButton("0");
// gbc.gridx = 2;
// gbc.gridy = 5;
// add(b0, gbc);
}
}
I can see the first 5 buttons when I comment out the last 5.
5 buttons
none
Just change your
frame.setContentPane(new Panel01());
to
Panel01 p1 = new Panel01();
frame.setContentPane(p1);
I am not sure why it works, but what is important is that it works !
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.