How to "paint" on JLabels on a JPanel?

meno picture meno · Feb 17, 2012 · Viewed 15.6k times · Source

I have a set of JLabels, each containing a letter (via seText()), opaque and background set to white, on a JPanel with a GridLayout so the labels are forming a table. I am doing a simple animation of highlighting certain rows and columns then there intersection. I can use the setBackground() of labels for this purpose, but thought I'd have more "choices" if a was able to use a Graphics object (maybe drawing a circle around intersection, then clearing it). I tried to extend JLabel, or drawing on the JPanel directly(using getGraphics() in a method) but it didn't work, I think the drawing is behind the labels in this case. I can't figure out where should the "painting" code be placed in either case, nothing appeared on the screen.

in short, a method like the following, can be used to draw on top of labels?
should it be a JLabel or a JPanel method?

public void drawsomething() {
    Graphics2D g2d = (Graphics2D) getGraphics();
    g2d.fillRect(100, 100, 100, 100);
    }

Answer

StanislavL picture StanislavL · Feb 17, 2012

What if you override paintChildren() ?

protected void paintChildren(Graphics g) {
  super.paintChildren(g);
//paint your lines here
}