vinnygray
vinnygray

Reputation: 171

How can I add an elliptical border to a JFrame

I have an undecorated JFrame in the shape of an ellipse, that I would like to add a border.

I am hoping I don't have to implement the rootPane.paintComponent method, and that I can just do this by adding a border.

Is this possible in Java 7 or 8?

Upvotes: 0

Views: 189

Answers (1)

trashgod
trashgod

Reputation: 205875

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

Also override getPreferredSize(), as shown here.

Upvotes: 2

Related Questions