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 ;

Edited 3 Years Ago by nikolaos

This article has been dead for over six months. Start a new discussion instead.