Frage

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);
    }
}
War es hilfreich?

Lösung 2

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.

Andere Tipps

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

To remove the Large appearance of the button, You need to add a layout Manager to the Code Like this:

import javax.swing.*;
import java.awt.*;
public static void main(String[] args)
{
    JFrame frame = new JFrame();
    JButton b1 = new JButton();
    frame.setSize(500,500); 
    b1.setVisible(true);
    b1.setText("HelloWorld");
    frame.setLayout(new FlowLayout());
    frame.add(b1);
    frame.setVisible(true);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top