11

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?

Drawing of required functionality

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
charmae
  • 1,080
  • 14
  • 38

2 Answers2

10

Draw onto the glass pane.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • personally, I don't quite understand bare pointers to the glassPane: it's a (btw, hard to handle) property of the rootPane, that is the direct child of a top-level container. So what are you (and others recently, you are the unfortunate today :-) really suggesting: manage the glassy overpaints on a per-frame basis? use a rootPane elsewhere? copy the part of the rootPane's code that is managing the glassPane to another container? Really curious ... – kleopatra Feb 11 '12 at 11:35
  • Umm.. Really clueless (on this one). Just remember it being mentioned in lots of situations such as this. Personally I prefer your suggestion. +1 – Andrew Thompson Feb 11 '12 at 11:50
  • 1
    @kleopatra for your question is only yes, and there are four correct ways (I really don't undestand your comments and why without any additional code, description or whatever else), `1)` Rob's http://tips4java.wordpress.com/2009/07/26/overlap-layout/, `2)` J(X)Layer, `3)` JViewport `4)` GlassPane, – mKorbel Feb 11 '12 at 12:23
6

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);
kleopatra
  • 51,061
  • 28
  • 99
  • 211