Search code examples
javaimageswingjbutton

JButton image rendering badly


I'm making a application with Swing, and I want to add to the main panel a button with a cross icon on it. But when I draw an image on it, the image is rendering weirdly.

I've already tried several things like resizing the image outside the application, and the cross is made with IllustratorCC so I don't think it's the quality of the source image that's the issue.

import javax.imageio.*;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

public class ImageRenderingBadly extends JPanel
{
    BufferedImage cross;

    public ImageRenderingBadly()
    {
        try {
            URL url = new URL("https://i.sstatic.net/bWO4o.png");
            cross = ImageIO.read(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void paintComponent(Graphics g)
    {
        g.drawImage(cross,0,0,null);
    }

    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setSize(new Dimension(200,200));
        frame.setBackground(new Color(0));

        ImageRenderingBadly panel = new ImageRenderingBadly();

        frame.setContentPane(panel);
        frame.setVisible(true);
    }
}

Source:

Rendering badly:

FOUND THE SOLUTION

Use antialiasing in paintComponent :(https://docs.oracle.com/javase/tutorial/2d/advanced/quality.html)

@Override
    public void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D)g;
        RenderingHints rh = new RenderingHints(
                RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        g2.setRenderingHints(rh);
        g2.drawImage(cross,0,0,null);
    }

Result


Solution

  • I figured out that the "drawImage" render badly image and that' the problem I think :

    
    public class Panel extends JPanel
    {
        BufferedImage image;
    
        public Panel() {
            super();
    
            try {
                image = ImageIO.read(new File("images/BMW-TA.jpg"));
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
        @Override
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, null);
        }
    }
    
    

    Source : https://i.sstatic.net/qlLIA.jpg

    Rendering : https://i.sstatic.net/BDg3v.png

    FOUND THE SOLUTION

    Use antialiasing in paintComponent :

    @Override
        public void paintComponent(Graphics g)
        {
            Graphics2D g2 = (Graphics2D)g;
            RenderingHints rh = new RenderingHints(
                    RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
            g2.setRenderingHints(rh);
            g2.drawImage(cross,0,0,null);
        }