Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

swing - What is the purpose of using Java Layout Managers?

It seems like whenever I am trying to create a program I always wind up using the setLayout(null); command in Java because I like to absolutely position whatever it is I'm putting onto my swing components. From what I read everyone keeps saying to use layout managers to simply the coding process, but how does it simplify it? What is the problem that arises with absolute positioning between platform systems?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you use a layout, invoking pack() "Causes this Window to be sized to fit the preferred size and layouts of its subcomponents." When you don't, you have to try to calculate the bounds yourself. If (when) you get it wrong, as shown in the somewhat contrived example below, users will blame you—and not without some justification. A related example regarding non-resizable containers is seen here.

image

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, 1, 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, 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();
            }
        });
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...