0

I have an algorithm that displays pretty fractals on a JPanel. I want to be able to show gridline 'crosshairs' on the fractal panel whenever a user hovers his mouse on the panel.

I have achieved this with a quick, simple method for drawing on stuff which goes like this (fractal is the name of the fractal JPanel):

@Override
public void mouseMoved(MouseEvent e) {
    Graphics g = fractal.getGraphics();
    // <problematic part>
    //   This is computationally expensive to do. It takes a good 0.2 seconds.
    //   This must be done to clear 'old' crosshairs
    fractal.repaint();
    // </problematic part>
            
    Color c = fractal.getColourScheme().getGridlineColour();
    g.setColor(new Color(c.getRed(), c.getGreen(), c.getBlue(), 50));
            
    // Draw crosshairs around the mouse's current point
    g.drawLine(e.getX(), 0, e.getX(), fractal.getHeight());
    g.drawLine(0, e.getY(), fractal.getWidth(), e.getY());
}

As illustrated, I have to repaint() in order to clear any old crosshairs.

I have a feeling I need to paint my crosshairs on something like a Glass Pane to go on top of my JPanel - however, JPanel doesn't provide a Glass Pane. JRootPane does though - can I use this instead?

P.S.

Currently I'm painting the fractal pixel by pixel with lots of little Line2Ds. I will eventually change this to producing a BufferedImage - in which case, would this problem even matter?

Community
  • 1
  • 1
Chris Watts
  • 6,197
  • 7
  • 49
  • 98

1 Answers1

1

I think your idea of using a glass pane would solve your problem permanently. It would no longer matter how you choose to draw the fractal itself, or whether it is displayed in a JPanel or any other type of component. Each object should really be responsible for it's own data and actions, so a different object really would probably be a good design choice.

That being said, you will still need to repaint the glass pane. You should be able to use the public void repaint(long tm, int x, int y, int width, int height) method to only repaint certain parts of the panel, instead of repainting the whole thing.

The JavaDoc states:

Adds the specified region to the dirty region list if the component is showing. The component will be repainted after all of the currently pending events have been dispatched.

RudolphEst
  • 1,240
  • 13
  • 21