Reputation: 1080
I'm trying to draw a line (Red line in the image) over multiple panels, but I can't seem to make it work. How can I make this possible? Any suggestions?
Upvotes: 11
Views: 2411
Reputation: 51535
JDK 7 added JLayer to support visual decorations on top of arbitrary components. For earlier versions, there's the project JXLayer at java.net which actually is its predecessor with very similar api
Here's a rudimentary example, using a custom LayerUI which draws a straight line from one component in a container to another component in a different container. The common parent of the two containers is decorated with a JLayer using that ui:
JComponent comp = Box.createVerticalBox();
final JComponent upper = new JPanel();
final JButton upperChild = new JButton("happy in upper");
upper.add(upperChild);
final JComponent lower = new JPanel();
final JButton lowerChild = new JButton("unhappy in lower");
lower.add(lowerChild);
comp.add(upper);
comp.add(lower);
LayerUI<JComponent> ui = new LayerUI<JComponent>() {
@Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
Rectangle u = SwingUtilities.convertRectangle(upper, upperChild.getBounds(), c);
Rectangle l = SwingUtilities.convertRectangle(lower, lowerChild.getBounds(), c);
g.setColor(Color.RED);
g.drawLine(u.x, u.y + u.height, l.x, l.y);
}
};
JLayer<JComponent> layer = new JLayer<JComponent>(comp, ui);
Upvotes: 6