且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何向JFrame添加椭圆形边框

更新时间:2023-12-05 22:14:58

在实现paintComponent()时,使用setClip(),其大小为Ellipse2D以匹配图像的widthheight.

In your implementation of paintComponent(), use setClip() with an Ellipse2D sized to match the image's width and height.

private Ellipse2D.Double border = new Ellipse2D.Double();
…
public void paintComponent(Graphics g) {
    super.paintComponent()
    Graphics2D g2d = (Graphics2D) g;
    …
    int width = getWidth();
    int height = getHeight();
    g2d.setPaint(…);
    g2d.fillRect(0, 0, width, height);
    border.setFrame(0, 0, width, height);
    g2d.setClip(border);
    g2d.drawImage(image, 0, 0, width, height, this);
}

也请覆盖getPreferredSize(),如此处所示.