Here you can find the source of drawString(Graphics g, String s, int alignment, Rectangle r)
Parameter | Description |
---|---|
g | Graphics context to paint into |
s | Text to draw |
alignment | Text alignment ( #LEFT / #CENTER / #RIGHT ) |
r | Bounding rectangle (width has to be greater 0 when the alignment is CENTER or RIGHT) |
public static void drawString(Graphics g, String s, int alignment, Rectangle r)
//package com.java2s; /*/*from w w w . j av a 2 s .c o m*/ * Copyright 2007 skynamics AG * * 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.Graphics; import java.awt.Rectangle; public class Main { /** Flag for {@link #drawMultilineString(Graphics, String, int, Rectangle, boolean)}: Indicates that the text should be centered. */ public static final int CENTER = (1 << 1); /** Flag for {@link #drawMultilineString(Graphics, String, int, Rectangle, boolean)}: Indicates that the text should be right justified. */ public static final int RIGHT = (1 << 2); /** * Draws a string into a Graphics object. * * @param g Graphics context to paint into * @param s Text to draw * @param alignment Text alignment ({@link #LEFT}/{@link #CENTER}/{@link #RIGHT}) * @param r Bounding rectangle (width has to be greater 0 when the alignment is CENTER or RIGHT) */ public static void drawString(Graphics g, String s, int alignment, Rectangle r) { if (s == null) return; int x = r.x; if ((alignment & CENTER) != 0) { // Center text in line x += (r.width - g.getFontMetrics().stringWidth(s)) / 2; } else if ((alignment & RIGHT) != 0) { // Right-align text x += r.width - g.getFontMetrics().stringWidth(s); } g.drawString(s, x, r.y); } }