1

I am Looking if we can add Height element in the given Example.

So that i can Specify

public void drawString(Graphics g, String s, int x, int y, int width,int height)

Now if my text is more than height it is overlapping on next text.

Community
  • 1
  • 1
Code Hungry
  • 3,930
  • 22
  • 67
  • 95
  • What are you trying to do? – maloney Dec 21 '12 at 11:06
  • You want to draw string which occupies more than one line..? – Sorceror Dec 21 '12 at 11:07
  • I am drawing string which occupies more than one line. But i want to restrict String if last line crosses specified height. – Code Hungry Dec 21 '12 at 11:12
  • One way is to use HTML formatting in a `JLabel` & set the desired width as a style. See the [`LabelRenderTest`](http://stackoverflow.com/a/5853992/418556) source for an example. Once the width and string is set, the label should be able to report the preferred size (including height). – Andrew Thompson Dec 21 '12 at 15:32

1 Answers1

0

I didn't test that, but that might help you with your problem..

public void drawString(Graphics g, String s, int x, int y, int width, int height) {
    // FontMetrics gives us information about the width,
    // height, etc. of the current Graphics object's Font.
    FontMetrics fm = g.getFontMetrics();

    int lineHeight = fm.getHeight();

    int curX = x;
    int curY = y;
    int totalHeight = 0;

    String[] words = s.split(" ");

    String word = "";
    // end of words array wasn't reached and still some space left
    for(int i = 0; i < words.length && totalHeight <= height; i++) {

        // Find out thw width of the word.
        int wordWidth = fm.stringWidth(word + " ");

        // If text exceeds the width, then move to next line.
        if (curX + wordWidth >= x + width) {
            curY += lineHeight;
            totalHeight += lineHeight;
            curX = x;
        }

        g.drawString(word, curX, curY);

        // Move over to the right for next word.
        curX += wordWidth;
    }
}
Sorceror
  • 4,835
  • 2
  • 21
  • 35