简体   繁体   中英

Why isnt my GUI showing anything?

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();

    }
}

Call setVisible(true) after adding all components

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);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    //create buttons
    for(int i = 0; i < buttonValues.length; i++){
        p.add(new JButton(buttonValues[i]));
    }
    add(p);

    setVisible(true);

}

For furture understanding, if you want to add components for example in an ActionListener, you can call revalidate() and repaint() after adding a component, this will also update the GUI. (Don't call setVisible(true) again)

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