1

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);
        g.dispose();
        repaint();
    }

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

I have this

El Micke
  • 151
  • 2
  • 13

1 Answers1

0

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) {

        super.paintComponent(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) {
            e.printStackTrace();
            return;
        }

        add(l, BorderLayout.CENTER);
    }

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

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
Community
  • 1
  • 1
guleryuz
  • 2,714
  • 1
  • 15
  • 19
  • Thank you, it worked, Im only use ´g.setClip(new java.awt.geom.Ellipse2D.Float(0f,0f, getWidth(),getHeight()/2));´ – El Micke Aug 14 '16 at 17:16