2

I need some help with Java Swing components and its capabilities. I need to add a JPanel to a JFrame and paint an Ellipse2D on it. Onto the Ellipse2D I want to add another element, in my case it is a picture (right now I use an ImageIcon, maybe wrong). How can I achieve adding the Ellipse2D and the picture on the panel as shown in the image I attached?

The reason why I need the images separated is, because I need to change the filling color of the ellipse sometimes.

Thanks for any help.enter image description here

nyyrikki
  • 1,436
  • 1
  • 21
  • 32

3 Answers3

6

What you need is to create a custom JPanel implementation and override paintComponent method.

Inside it, you just do:

public void paintComponent(Graphics g) {

    super.paintComponent(g);

    // Draw ellipse here

    // Draw your image here. It will be drawn on top of the ellipse.

}

This way, you can hold the ellipse fill color in the CustomPanel class, and just call repaint() method after you change the color.

npe
  • 15,395
  • 1
  • 56
  • 55
2
  • your idea could be very good described (including code example) in the Oracles tutorial How to Decorate Components with the JLayer Class

  • notice JLayer is available only for Java7, but its based on (for Java6) JXLayer

  • you can use (I'm using) GlassPane too, with the same / similair output to the Swing GUI

EDIT

quite easy and nice output is by using OverlayLayout, there is possible to overlay J/Component(s) with Graphics e.g., a few examples

mKorbel
  • 109,525
  • 20
  • 134
  • 319
0

take the two images as image icons like

ImageIcon car=new ImageIcon("image path");
ImageIcon elipse=new ImageIcon("image path");

add those two image icons two label

JLabel carLabel=new JLabel(car);
JLabel ellipseLabel=new JLabel(ellipse);

and set the position of ellipse and car

carLabel.setBounds(0,0,50,50);
ellipseLabel.setBounds(10,10,50,50);
Thiem Nguyen
  • 6,345
  • 7
  • 30
  • 50
padman
  • 491
  • 1
  • 3
  • 14