Miguel Osorio Miguel Osorio - 1 year ago 114
Java Question

How draw oval image in JLabel

I want to draw a oval image in a JLabel, using Graphics. This is my code, but a dont know about Graphics.

class imagePanel extends JLabel {
//private PlanarImage image;

private BufferedImage buffImage = null;

private void drawFingerImage(int nWidth, int nHeight, byte[] buff) {
buffImage = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_BYTE_GRAY);
buffImage.getRaster().setDataElements(0, 0, nWidth, nHeight, buff);
Graphics g = buffImage.createGraphics();
g.drawImage(buffImage, 0, 0, 140, 150, null);

public void paintComponent(Graphics g) {
g.drawImage(buffImage, 0, 0, this);

I have this

Answer Source

you need the help of setClip() method as mentioned here and here.

when it comes to code it should look like this

public class OvalImageLabel extends JLabel {

    private Image image;

    public OvalImageLabel(URL imageUrl) throws IOException {
        image = ImageIO.read(imageUrl);

    public void paintComponent(Graphics g) {


        g.setClip(new java.awt.geom.Ellipse2D.Float(0f,0f, getWidth(),getHeight()/2));
        g.drawImage(image, 0, 0, this);


and a running application that using this class

public class UsageExample extends JPanel {

    public UsageExample() {
        super(new BorderLayout());
        OvalImageLabel l;
        try {
            l = new OvalImageLabel(new File("/path/to/image.png").toURI().toURL());
        } catch (Exception e) {

        add(l, BorderLayout.CENTER);

    private static void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setContentPane(new UsageExample());
        frame.setSize(200, 200);

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download