如何将由Graphics绘制的String放在java中的椭圆形顶部

时间:2012-08-21 07:52:50

标签: java string graphics

我需要在椭圆上写一个String,所以椭圆形的文字显示在它的中间。文本由g.drawString();方法绘制,椭圆由g.fillOval();绘制。如何将String置于最顶层?

1 个答案:

答案 0 :(得分:5)

enter image description here

import java.awt.*;
import javax.swing.*;

public class FrameTest {
    public static void main(String args[]) {
        JFrame f = new JFrame();
        f.add(new JComponent() {
            public void paintComponent(Graphics g) {

                // Some parameters.
                String text = "Some Label";
                int centerX = 150, centerY = 100;
                int ovalWidth = 200, ovalHeight = 100;

                // Draw oval
                g.setColor(Color.BLUE);
                g.fillOval(centerX-ovalWidth/2, centerY-ovalHeight/2,
                           ovalWidth, ovalHeight);

                // Draw centered text
                FontMetrics fm = g.getFontMetrics();
                double textWidth = fm.getStringBounds(text, g).getWidth();
                g.setColor(Color.WHITE);
                g.drawString(text, (int) (centerX - textWidth/2),
                                   (int) (centerY + fm.getMaxAscent() / 2));

            }
        });

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(300, 300);
        f.setVisible(true);
    }
}