Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to add a button to a frame?

Tags:

java

bluej

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);
    }
}
like image 945
user3105629 Avatar asked Mar 18 '26 17:03

user3105629


2 Answers

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
like image 74
ChiefTwoPencils Avatar answered Mar 20 '26 07:03

ChiefTwoPencils


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.

like image 26
PakkuDon Avatar answered Mar 20 '26 06:03

PakkuDon