What is the purpose of using java layout manager?

It seems that whenever I try to create a program, I always use setlayout (null); Commands in Java because I like to absolutely locate the swing component I'm placing Everyone I've read has been talking about using layout manager to simplify the coding process, but how does it simplify it? What is the problem of absolute positioning between platform systems?

Solution

When you use layout, call pack() "to fit the size of this window to the preferred size and layout of its subcomponents." If you do not, you must try to calculate the boundary yourself If (when) you make a mistake, as shown in the somewhat artificial example below, users will blame you - and there is no reason Examples of non resizable containers can be found here

import java.awt.EventQueue;
import java.awt.FontMetrics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

/**
 * @see https://stackoverflow.com/a/37801762/230513
 * @see https://stackoverflow.com/a/12532237/230513
 */
public class Evil {

    private static final String S = "Tomorrow's winning lottery numbers: 42,";
    private final JLabel label = new JLabel(S + "3,1,4,5,9");

    private void display() {
        JFrame f = new JFrame("Evil");
        f.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(null);
        FontMetrics fm = label.getFontMetrics(label.getFont());
        int w = SwingUtilities.computeStringWidth(fm,S) + 8;
        int h = fm.getHeight();
        label.setBounds(0,w,h);
        f.add(label);
        f.setSize(w,h * 3);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokelater(new Runnable() {

            @Override
            public void run() {
                new Evil().display();
            }
        });
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>