Java Draw String drawString(Graphics2D g, String s, int x, int y, int width)

Here you can find the source of drawString(Graphics2D g, String s, int x, int y, int width)

Description

draw String

License

Apache License

Declaration

public static void drawString(Graphics2D g, String s, int x, int y, int width) 

Method Source Code

//package com.java2s;
/*/*  w w w.  j a  va2s  . c  om*/
 *
 * Copyright SHMsoft, Inc. 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

import java.awt.FontMetrics;
import java.awt.Graphics2D;

public class Main {
    public static void drawString(Graphics2D g, String s, int x, int y, int width) {
        // 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;

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

        for (String word : words) {
            // 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;
                curX = x;
            }

            g.drawString(word, curX, curY);

            // Move over to the right for next word.
            curX += wordWidth;
        }
    }
}

Related

  1. drawString(Graphics g, String text, int underlinedChar, int x, int y)
  2. drawString(Graphics g, String text, int underlinedChar, int x, int y)
  3. drawString(Graphics g, String text, int underlinedChar, int x, int y)
  4. drawString(Graphics g, String text, int x, int y)
  5. drawString(Graphics g2, String string, int x, int y, Font font, Color color)
  6. drawString(Graphics2D g, String string, double x, double y, Color color)
  7. drawString(Graphics2D g, String string, int x, int y)
  8. drawString(Graphics2D g, String string, int x, int y, boolean includeOutline)
  9. drawString(Graphics2D g2, String str, int x, int y, int halign, int valign)