【问题标题】:How to set Image on rounded shape jLabel如何在圆形jLabel上设置图像
【发布时间】:2015-02-22 03:24:59
【问题描述】:

我想创建一个可以设置图像的圆形 JLabel。与在 Google+ 中一样,有一个圆形的个人资料相框。我遇到了一个问题,即我试图在 JLabel 中设置的图像出现在整个屏幕上,但不在所需的圆形 JLabel 中。我的代码是这样的。

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

【问题讨论】:

  • 这段代码对我有用。

标签: java swing jlabel


【解决方案1】:

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

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 2017-04-28
    • 2018-02-02
    相关资源
    最近更新 更多