Java: How to add a button to a frame?

user3105629 picture user3105629 · Dec 16, 2013 · Viewed 35.9k times · Source

I try to just use a add.method to add a button to a frame. But only the frame pops up. I don't see any buttons.

import javax.swing.*;
public class okd {
    public static void main() {
        JFrame frame = new JFrame();
        JButton b1 = new JButton();
        frame.setSize(500,500);
        frame.add(b1);
        b1.setSize(400,400);
        b1.setVisible(true);
        frame.setVisible(true);
    }
}

Answer

ChiefTwoPencils picture ChiefTwoPencils · Dec 16, 2013

There is a button there. Add some text to it and it will magically appear.

public static void main(String[] args){
    JFrame frame = new JFrame();
    JButton b1 = new JButton();
    frame.setSize(500,500);     
    b1.setSize(400,400);
    b1.setVisible(true);
    b1.setText("HelloWorld");
    frame.add(b1);
    frame.setVisible(true);
}//SSCCE1