如何在圆形jLabel上设置图像

时间:2015-02-21 17:22:23

标签: java swing jlabel

我想创建一个圆形JLabel,我可以在其中设置图像。与在Google+中一样,有一个圆形的个人资料相框。我遇到一个问题,我试图在JLabel中设置的图像来自整个屏幕而不是所需的圆形JLabel.my代码就是这个。

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;  
public class OverJLabel extends JLabel{    
public int intX,intY,w,h;   
  public OverJLabel(int x,int y,int width,int height,Icon image) {
        super(image);
        intX=x;
        intY=y;
        w=width;
        h=height;
  }
@Override  
 public void paintComponent(Graphics g){
   super.paintComponent(g);
   g.setColor(Color.RED);
   g.drawOval(intX, intY, w, h);
 }// end of the overriden label
}// end of the rounded shape JLabel class

1 个答案:

答案 0 :(得分:3)

paintComponent()的实现中,使用所需的背景颜色填充组件,并在调用Ellipse2D之前将图形上下文的剪辑区域限制为适当大小的drawImage()。例如,

private Ellipse2D.Double border = new Ellipse2D.Double();
…
@Override
public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setPaint(Color.RED);
    g2d.fillRect(0, 0, width, height);
    border.setFrame(0, 0, width, height);
    g2d.setClip(border);
    g2d.drawImage(image, 0, 0, width, height, this);
}