why is this button still filling the whole frame?

java, jbutton, jframe, swing

Solution

The default Layout for `JFrame` is `BorderLayout`. That's why when you are adding a `JButton` to it , It is adding the `JButton` to the `center` and expanding it to cover entire window. `BorderLayout` doesn't respect the `setSize(..)` method of components being added to them. If you still want to give a preferred size to the component being added to `JFrame` you should change the layout to be `FlowLayout` or `GridLayout` or others.. and then use `setPreferredSize(..)` method with the component while adding it to the `JFrame`. For example Your code could be modified in following way.

import java.awt.*;
import javax.swing.*;

public class MainForm {

    protected  JFrame window = new JFrame("Test Form");
    protected  JButton btnOK = new JButton("OK!");

    public static void main(String st[]) {
        SwingUtilities.invokeLater( new Runnable()
        {
            public void run()
            {
                MainForm mf = new MainForm();
                mf.load();
            }
        });

    }
    public void load() {
    Container c = window.getContentPane();
    c.setLayout(new FlowLayout());//Set layout to be FlowLayout explicitly.
    btnOK.setPreferredSize(new Dimension(100,50));//use set PreferredSize
    c.add(btnOK);
    c.setSize(500, 500);
    c.setVisible(true);
    }

}

Problem

I have this code ``` package com.net.Forms; import javax.swing.JButton; import javax.swing.JFrame; public class MainForm { protected static JFrame window = new JFrame("Test Form"); protected static JButton btnOK = new JButton("OK!"); public static void Main() { load(); return; } public static void load() { window.setSize(500, 500); window.setVisible(true); //btnOK.setSize(50, 50); //here window.add(btnOK); btnOK.setEnabled(true); btnOK.setVisible(true); } } ``` Why is the button still filling the frame instead of being 50 X 50 like i stated above Any help would be appreciated

Original source

Related problems