Here is an example. A text drawing is a modified version of the answer specified in Software Monkey to use coordinate data instead of drawing in the center of the component.
, , drawCenteredText.
Random , .
public class LabledCircle {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.add(new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(0, 0, getWidth(), getHeight());
Random rad = new Random();
drawCenteredText(g, getWidth() / 2, getHeight() / 2, rad.nextFloat() * 30f, "Hello World!");
}
});
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void drawCenteredText(Graphics g, int x, int y, float size, String text) {
Font newFont = g.getFont().deriveFont(size);
g.setFont(newFont);
FontMetrics fm = g.getFontMetrics();
java.awt.geom.Rectangle2D rect = fm.getStringBounds(text, g);
int textHeight = (int) (rect.getHeight());
int textWidth = (int) (rect.getWidth());
int cornerX = x - (textWidth / 2);
int cornerY = y - (textHeight / 2) + fm.getAscent();
g.drawString(text, cornerX, cornerY);
}
}