0

I want to draw string on jpanel but I do not know the number of string I am going to pass the panel in some cases there are four string in some cases there are five string in some cases there are three. Now how can I draw strings on panel and how many numbers of string will I have to pass to jPanel because they varies in each case.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Sarah
  • 370
  • 1
  • 7
  • 25

1 Answers1

3

What do you mean by the "number of string"? You mean it will be an array of Strings and you don't know the length ahead of time? Does each String need to go on a "line" by itself?

You could use the drawString method from the Graphics class.

Are you creating a class that extends JPanel. If so, then when you override paintComponent, the Graphics object is passed as a parameter.

This post contains information about how to determine the size of the String in pixels.

This link on measuring text and this link on displaying multiple lines of text may also be useful.

Cheers!

Community
  • 1
  • 1
Mike Scott
  • 296
  • 3
  • 12
  • Why are you recommending calling `getGraphics()` for a JComponent such as a JPanel? You do understand that the Graphics object returned is short-lived and that anything drawn with it will disappear when the JVM or the OS requires a repaint. This shouldn't be an option. If you need to draw on a JPanel, you should extend it and draw in the paintComponent method. – Hovercraft Full Of Eels Jul 29 '11 at 22:23
  • 1
    Thanks for the edit, and I'll change my down-vote to an up-vote. – Hovercraft Full Of Eels Jul 29 '11 at 22:40
  • 1
    -1 custom painting is done by overiding paintComponent(), not paint() as has already been suggested by suggested by Hoevercraft. – camickr Jul 30 '11 at 01:05
  • @Mike yes it is array of string and I do not know the length ahead of times.yes each string will have to do to a line by itself – Sarah Jul 30 '11 at 13:32