I am trying to display a calculator with buttons but the only thing that shows up is an empty JFrame.
The only thing that I can think of is because I am doing all of the work in the constructor and that my main only creates the object and does nothing else. However, if that is the case, then why would it still display an empty GUI rather than nothing? Or am I just doing this completely wrong?
import java.awt.GridLayout;
import java.awt.TextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
public class MyFrame extends JFrame{
private GridLayout grid;
private final String ADD = "+";
private final String SUB = "-";
private final String MULT = "*";
private final String DIV = "/";
private final String CLR = "C";
private final String EQ = "=";
private TextField textOnScreen;
private final String[] buttonValues= {
"7", "8", "9", ADD,
"4", "5", "6", SUB,
"1", "2", "3", MULT,
"0", CLR, EQ, DIV
};
MyFrame(){
super("Calculator");
JPanel p = new JPanel();
grid = new GridLayout(4, 4, 3, 3);//row, col, hor gap, vert gap
p.setLayout(grid);
setSize(400, 500);
setResizable(true);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//create buttons
for(int i = 0; i < buttonValues.length; i++){
p.add(new JButton(buttonValues[i]));
}
add(p);
}
public static void main(String[] args){
MyFrame f = new MyFrame();
}
}