Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "paint" on JLabels on a JPanel?

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);
    }
like image 361
meno Avatar asked Jan 17 '23 11:01

meno


1 Answers

What if you override paintChildren() ?

protected void paintChildren(Graphics g) {
  super.paintChildren(g);
//paint your lines here
}
like image 188
StanislavL Avatar answered Jan 25 '23 20:01

StanislavL