Using NetBeans 7.3.1 i have created a JFrame.
A JLabel fills the bottom of the JFrame .
The JLabel displays an ImageIcon.
I want the ImageIcon automatically resize itself when JLabel resizes.

Generated Code from IDE :

jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Number_theory/resources/primes_ulam_spiral.gif"))); // NOI18N
        jLabel1.setDoubleBuffered(true);
        jLabel1.setOpaque(true);
        jLabel1.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                jLabel1ComponentResized(evt);
            }
        });

My way to change Icon's dimensions according to label's dimensions.

 private void jLabel1ComponentResized(java.awt.event.ComponentEvent evt) {                                         

        int labelwidth = jLabel1.getWidth();
        int labelheight = jLabel1.getHeight();

        ImageIcon Icon = new javax.swing.ImageIcon(getClass().getResource("/Number_theory/resources/primes_ulam_spiral.gif"));

         Image img = Icon.getImage();
         jLabel1.setIcon( new ImageIcon(img.getScaledInstance(labelwidth,labelheight ,Image.SCALE_FAST)));

    }     

The result is a slow adjustment to frame resizing.
Is there a better way ;

Don't reload the image file every time. Do it just once at startup and keep a copy.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.