Java, setting layout to null

Is there a better way?

Layout managers, layout managers, layout managers. If the default provided layout managers aren’t doing what you want, either use a combination of layout managers or maybe try some of the freely available layout managers, like MigLayout (and use them in combination with other layout managers as required)

With your code…

Without Layout Manager

Using a GridBagLayout

With Layout Manager

The button is slightly bigger, because it’s taking into account the actual requirements of the button (text and font size), but will always add an additional 100 pixels to the width and 60 pixels to the height.

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {

    public static void main(String args[]) {

        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        JButton button = new JButton("Click");

        //JFrame, frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setSize(500, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        //JPanel, panel
        panel.setLayout(new GridBagLayout());
        frame.add(panel);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.ipadx = 100;
        gbc.ipady = 60;
        gbc.insets = new Insets(25, 25, 0, 0);
        gbc.weightx = 1;
        gbc.weighty = 1;
        gbc.anchor = GridBagConstraints.NORTHWEST;

        panel.add(button, gbc);

    }
}

Now, if all I do is add button.setFont(button.getFont().deriveFont(64f)); we end up with…

Your code on the left, my code on the right…

Wow to null layouts

And if you think that’s been overly dramatic, different OS’s will do worse things to you then that

Leave a Comment