Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToolTip for own drawings

my java application contains a JPanel on which I draw certain shapes. Now I would like to label these shapes with some kind of tooltips.

Therefore I tried to create my own "Tooltips" by using the drawString, setBackground, setColor method.:

public void drawToolTip(Graphics2D graphics, String text, Point2D position) {
    graphics.setBackground(Color.RED);
    graphics.setColor(Color.GREEN);
    graphics.drawString(text, (float) position.getX(), (float) position.getY());
}

Unfortunately the setBackground method does not seem to work. The text background remains transparent although I set it to red. setColor and drawString just work fine.

My questions are:

  • What could be the reason that the setBackground method does not work?
  • Is there a possibility to draw a boarder arround the text without drawRect?
  • If I want to use "drawRect" method as a substitude to draw the text background and border: How can I make it automatically fit to the written text? Or in other words how can I get the dimensions of a specific text?

Regards Marc

like image 567
Marc Avatar asked Dec 21 '25 11:12

Marc


1 Answers

  • Graphics2D.drawString() does not draw a background by default. You will have to do this yourself.

  • You can use drawRect() to draw a line border or fillRec() to draw a solid rectangle.

  • Oracle has a great tutorial on measuring String widths. Essentially, you need to create a java.awt.Font then get its FontMetrics and use that to calculate the width and height of your string.

like image 165
ulmangt Avatar answered Dec 23 '25 23:12

ulmangt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!