non resizable window border and positioning

What are the problems with settings bounds on non-resizable containers?

Suppose you adjust the bounds to look good on your platform. Suppose the user’s platform has a font with different, say larger, FontMetrics. This example is somewhat contrived, but you get the idea. If you change the bounds of a non-resizable container, be sure any text is visible regardless of the host platform’s default font.

image

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 * @see http://stackoverflow.com/a/12532237/230513
 */
public class Evil extends JPanel {

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

    public Evil() {
        this.add(label);
    }

    private void display() {
        JFrame f = new JFrame("Evil");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this, BorderLayout.WEST);
        f.pack();
        int w = SwingUtilities.computeStringWidth(
            label.getFontMetrics(label.getFont()), s);
        int h = f.getHeight();
        f.setSize(w, h);
        f.setResizable(false);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

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

            @Override
            public void run() {
                new Evil().display();
            }
        });
    }
}

Leave a Comment