So I'm trying to find a way to modify an image in Java. In other words, if user clicks on the image, a mark will be put at the point where the user just clicked. I have an ImageIcon which I put in a JLabel. So far, the approach I took was to use JLayeredPanel to put another JPanel on top of the JLabel and draw on this JPanel:
//...
ImageIcon icon = new ImageIcon("foo.jpg");
JLabel lb = new JLabel(icon);
JPanel glass = new JPanel();
lb.setBounds(0, 0, 100, 100);
glass.setBounds(0, 0, 100, 100);
glass.setOpaque(false);
LayeredPane container = new LayeredPane();
container.add(lb, 1);
container.add(glass, 2);
//...
But this way doesn't seem to work. I never see the background image (the image in lb). So I was wondering if I'm even on the right track at all? Or is there a cleaner way to achieve this?
You're on the right track with wanting to use another pane. In Java, there actually already is a glass pane that is designed for just this purpose. Read through this tutorial http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html and it should help you understand.
There's nothing wrong with using a
JLayeredPane
or the glass pane for something like this, personally, I find it troublesome, because in a large application, you tend to want to use these layers for any number of things, so it becomes very complicated very fast.I prefer to keep it "in the family" so to speak...
Personally, I would use a custom component. This isolates the work flow to a very particular location and makes it easier to provide the customisations that you might like...
I'd also consider using
JXLayer
(AKAJLayer
in Java 7). This is best described as a glass pane for components (on steroids). Check out How to decorate components for more details...Updated with JLayer Example
This is an example using Java 7's
JLayer
. There are some slight differences betweenJLayer
andJXLayer
, but it wouldn't take much to convert it...(Sorry, couldn't resist the temptation of having ago)
The blue border is renderer as part of the layer, this gives you a guide as to where you can click - I did this for testing and demonstration purposes