nyyrikki
nyyrikki

Reputation: 1486

How to add multiple layers onto JPanel

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

Upvotes: 2

Views: 3251

Answers (3)

padman
padman

Reputation: 501

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

Upvotes: 0

mKorbel
mKorbel

Reputation: 109813

  • 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

Upvotes: 2

npe
npe

Reputation: 15709

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.

Upvotes: 6

Related Questions