Java, setting layout to null

痴心易碎 提交于 2019-12-17 14:57:18

问题


I have been using a null layout and I alot of people will say it shouldn't be done this way. Is there a better way?

Some code as example:

import javax.swing.*;

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(null); //<<---- Is this correct?
    frame.add(panel);

    //JButton, button
    button.setBounds(25, 25, 100, 60); //<<---- Is this correct?
    panel.add(button);

   }
}

回答1:


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



来源:https://stackoverflow.com/questions/33249871/java-setting-layout-to-null

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