Graphics rendering in title bar

The problem is you’re not taking into consideration the frame’s border (and possibly the menu bar as well) when setting the size of the frame…

Instead of using this.setSize(680,581) which is will cause the image to rendered inside the frames borders (and beyond into non-visible space), you should simple call JFrame#pack and let the frame decide how best to size it self (based on the preferred size of it’s content)

enter image description hereenter image description here

Left, absolute sizing, right preferred sizing

public class SimpleImageLabel {

    public static void main(String[] args) {
        new SimpleImageLabel();
    }

    public SimpleImageLabel() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JLabel imageLabel = new JLabel();

                try {
                    imageLabel.setIcon(new ImageIcon(ImageIO.read(new File("/path/to/image"))));
                } catch (Exception e) {
                }


                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(imageLabel);
                frame.pack();  // <-- The better way
//                frame.setSize(imageLabel.getPreferredSize()); // <-- The not better way
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }


}

Leave a Comment