다음은 예입니다. 텍스트 그림은 구성 요소의 중앙에 그리기 대신 지정된 좌표를 사용하기 위해 Software Monkey가 나열한 대답을 수정 한 버전입니다.
전체 구성 요소를 포함하지 않는 원을 그리려면 원의 중심을 계산하고 drawCenteredText
에 전달해야합니다.
Random
클래스의 비즈니스는이 방법이 모든 글꼴 크기에서 어떻게 작동하는지 보여줍니다.
public class LabledCircle {
public static void main(String args[]) {
JFrame frame = new JFrame();
// Create and add our demo JPanel
// I'm using an anonymous inner class here for simplicity, the paintComponent() method could be implemented anywhere
frame.add(new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw a circle filling the entire JPanel
g.drawOval(0, 0, getWidth(), getHeight());
Random rad = new Random();// For generating a random font size
// Draw some text in the middle of the circle
// The location passed here is the center of where you want the text drawn
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) {
// Create a new font with the desired size
Font newFont = g.getFont().deriveFont(size);
g.setFont(newFont);
// Find the size of string s in font f in the current Graphics context g.
FontMetrics fm = g.getFontMetrics();
java.awt.geom.Rectangle2D rect = fm.getStringBounds(text, g);
int textHeight = (int) (rect.getHeight());
int textWidth = (int) (rect.getWidth());
// Find the top left and right corner
int cornerX = x - (textWidth/2);
int cornerY = y - (textHeight/2) + fm.getAscent();
g.drawString(text, cornerX, cornerY); // Draw the string.
}
}
정말 쉬운 방법이 아니다. [글꼴 메트릭스] (http://docs.oracle.com/javase/tutorial/2d/text/measuringtext.html) –
[텍스트 측정] (http://docs.oracle.com/javase/tutorial/2d/) text/measuringtext.html)이 시작일 수 있습니다. – asgs
나는 보통 ['GlyphVector'] (http://stackoverflow.com/a/6296381/418556)를 사용하지만이 고양이를 다듬는 데는 12 가지 방법이 있어야합니다. –