Java examples for java.awt:Graphics2D
draw String At
//package com.java2s; import java.awt.*; import java.awt.geom.*; public class Main { public static final int TEXT_TOPLEFT = 0; public static final int TEXT_TOP = 1; public static final int TEXT_TOPRIGHT = 2; public static final int TEXT_LEFT = 3; public static final int TEXT_CENTER = 4; public static final int TEXT_RIGHT = 5; public static final int TEXT_BOTTOMLEFT = 6; public static final int TEXT_BOTTOM = 7; public static final int TEXT_BOTTOMRIGHT = 8; public static void drawStringAt(String s, Font font, int xRef, int yRef, int aligned, Graphics context) { FontMetrics fm = context.getFontMetrics(font); Rectangle2D strBound = fm.getStringBounds(s, context); int xDraw, yDraw; if (aligned == TEXT_TOPLEFT) { xDraw = xRef;//from www . ja v a 2 s. c om yDraw = yRef + (int) strBound.getHeight(); } else if (aligned == TEXT_TOP) { xDraw = xRef - (int) strBound.getWidth() / 2; yDraw = yRef + (int) strBound.getHeight(); } else if (aligned == TEXT_TOPRIGHT) { xDraw = xRef - (int) strBound.getWidth(); yDraw = yRef + (int) strBound.getHeight(); } else if (aligned == TEXT_LEFT) { xDraw = xRef; yDraw = yRef + (int) strBound.getHeight() / 2; } else if (aligned == TEXT_CENTER) { xDraw = xRef - (int) strBound.getWidth() / 2; yDraw = yRef + (int) strBound.getHeight() / 2; } else if (aligned == TEXT_RIGHT) { xDraw = xRef - (int) strBound.getWidth(); yDraw = yRef + (int) strBound.getHeight() / 2; } else if (aligned == TEXT_BOTTOMLEFT) { xDraw = xRef; yDraw = yRef; } else if (aligned == TEXT_BOTTOM) { xDraw = xRef - (int) strBound.getWidth() / 2; yDraw = yRef; } else if (aligned == TEXT_BOTTOMRIGHT) { xDraw = xRef - (int) strBound.getWidth(); yDraw = yRef; } else { //default alignment: bottomleft xDraw = xRef; yDraw = yRef; } Font tmpFont = context.getFont(); context.setFont(font); context.drawString(s, xDraw, yDraw); context.setFont(tmpFont); //return to original font } }