Search code examples
javaswingjframejlabelimageicon

JLabel ImageIcon not smoothing properly


I created a JLabel containing an ImageIcon and inserted it into a JFrame with a grid layout after smoothing it to a preferred size.

It mostly worked, but the blank horizontal areas around the JLabel hogged up most of the frame as seen in this image: Outcome

Why is the JLabel ImageIcon not giving me the following outcome?

Desired Outcome

This is my renderer:

ImageIcon imageIcon = new ImageIcon(baseDir + dash + "ErrIco.png");
Image image = imageIcon.getImage();
Image newimg = image.getScaledInstance(35, 35,  java.awt.Image.SCALE_SMOOTH);
imageIcon = new ImageIcon(newimg);

Solution

  • Try using a different layout, like BorderLayout. GridLayout will force all the cells to have the same size.

    frame.setLayout(new BorderLayout());
    ...
    frame.add(new JLabel(imageIcon), BorderLayout.WEST);
    frame.add(label,                 BorderLayout.CENTER);
    

    edit:

    I see you already accepted my answer but I had put this together in the mean-time, just to see if the JLabel with a scaled image added some additional factor. (Which it didn't. It works fine.)

    image example

    import java.awt.*;
    import javax.swing.*;
    import java.net.*;
    import javax.imageio.*;
    
    class ImageExample implements Runnable {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new ImageExample());
        }
    
        @Override
        public void run() {
            JFrame frame = new JFrame();
            JPanel content = new JPanel();
            content.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
            content.setBackground(Color.white);
            frame.setContentPane(content);
            //
            frame.setLayout(new BorderLayout(20, 20));
            JLabel icon = new JLabel(new ImageIcon(img));
            JLabel text = new JLabel("<html>" +
                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "<br>" +
                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + "<br>" +
                "cccccccccccccccccccccccccccccccccccccccccc" + "</html>");
            text.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
            frame.add(icon, BorderLayout.WEST);
            frame.add(text, BorderLayout.CENTER);
            //
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        static final Image img;
        static {
            try {
                URL url = new URL("https://i.sstatic.net/7bI1Y.jpg");
                img = ImageIO.read(url).getScaledInstance(48, 48, Image.SCALE_SMOOTH);
            } catch (Exception x) {
                throw new RuntimeException(x);
            }
        }
    }