Search code examples
javabluej

Java: How to add a button to a frame?


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

Solution

  • Your button has been added to the frame. You'll notice a difference if you remove your frame.add() line. The 'problem' lies with the following.

    • You haven't specified a layout resulting in your frame using the default BorderLayout manager.
    • You haven't specified a constraint in frame.add(). Because of this the component has been added to whatever the default position is for the layout which is BorderLayout.CENTER. Components added to the center take up the much space as possible hence why your button is filling the entire frame.

    Here's some tutorials on layout managers. You might want to have a read through these at some point.