You could create a custom Icon class:
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.net.*;
import javax.swing.*;
public class OvalImageIcon extends ImageIcon
{
private BufferedImage oval;
public OvalImageIcon()
{
super();
}
public OvalImageIcon(String fileName)
{
super(fileName);
}
public OvalImageIcon(URL url)
{
super(url);
}
@Override
public void setImage(Image image)
{
super.setImage(image);
oval = null;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y)
{
if (oval == null)
{
oval = new BufferedImage(getIconWidth(), getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D ovalGraphics = oval.createGraphics();
ovalGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
ovalGraphics.drawImage(getImage(), 0, 0, null);
// Use AlphaComposite to apply oval mask
Shape ovalMask = new Ellipse2D.Double(0, 0, getIconWidth(), getIconHeight());
Area imageArea = new Area( new Rectangle(0, 0, getIconWidth(), getIconHeight()) );
imageArea.subtract( new Area( ovalMask ) );
ovalGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN));
ovalGraphics.setColor( new Color(0, 0, 0, 0) );
ovalGraphics.fill(imageArea);
ovalGraphics.dispose();
}
g.drawImage(oval, x, y, null);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI()
{
Icon icon = new OvalImageIcon("mong.jpg");
JLabel label = new JLabel( icon );
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(label);
f.pack();
f.setLocationRelativeTo( null );
f.setVisible(true);
}
}
Above code should paint an oval of the image based on the width and height of the original image.