Java 如何在矩形内书写文字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22628357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write text inside a rectangle
提问by user3456343
Hi I am creating a java desktop application where I am drawing rectangle. I want to write some text inside rectangle.
嗨,我正在创建一个 Java 桌面应用程序,我在其中绘制矩形。我想在矩形内写一些文本。
How can I achieve this?
我怎样才能做到这一点?
Here is my code:
这是我的代码:
class DrawPanel extends JPanel {
private void doDrawing(Graphics g) {
int a=90;
int b=60;
int c=10;
int d=15;
ArrayList<Graphics2D> g1 = new ArrayList<Graphics2D>();
for(int i=0;i<=9;i++){
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(212, 212, 212));
g2d.drawRect(c, d, a, b);
d+=65;
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
采纳答案by user1803551
Use your Graphics2D
object and call drawString(String str, int x, int y)
. Something like
使用您的Graphics2D
对象并调用drawString(String str, int x, int y)
. 就像是
g2d.drawRect(c, d, a, b);
g2d.drawString("Hi", (a+c)/2, (b+d)/2);
Note that the Javadoc specifies
请注意,Javadoc 指定
Draws the text given by the specified string, using this graphics context's current font and color. The baseline of the leftmost character is at position (x, y) in this graphics context's coordinate system.
使用此图形上下文的当前字体和颜色绘制由指定字符串给出的文本。最左边字符的基线位于此图形上下文坐标系中的 (x, y) 位置。
so you would need to take into account the space the font takes on screen. Use FontMetrics
for that.
所以你需要考虑字体在屏幕上的空间。FontMetrics
为此使用。