我必須在橢圓形或圓圈上寫下文字 我有這段代碼(我在Stackoverflow上找到它),但我不明白一些觀點。在橢圓上繪製字符串
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Panneau extends JPanel {
@Override
public void paintComponent(Graphics g){
// Declaration
String text = "test";
int x = 100, y = 50;
int ovalWidth = 50, ovalHeight = 50;
// Draw circle
g.setColor(Color.blue);
g.fillOval(x-ovalWidth/2, y-ovalHeight/2,ovalWidth, ovalHeight);
// I don't understand why x-ovalwidth/2 and y-ovalheight/2
// Put text into circle
FontMetrics fm = g.getFontMetrics();
double textWidth = fm.getStringBounds(text, g).getWidth();
// What is the job of getstringbounds
g.setColor(Color.white);
g.drawString(text, (int) (x - textWidth/2),(int) (y + fm.getMaxAscent()/2));
}
}
,並感謝
我不明白我們爲什麼寫:x-ovalWidth/2而不只是x,我不知道getstringbounds的工作 – HinoHara
是的抱歉,剛剛注意到您的意見 – DoubleDouble
請確保您正在調用'super.paintComponent '否則你最終會得到不需要的油漆文件 – MadProgrammer