Java, setting layout to null

孤人 提交于 2019-11-27 16:25:16

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...

Using a GridBagLayout

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...

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!