gpt4 book ai didi

Java drawString 正在绘制超出范围的字符串

转载 作者:行者123 更新时间:2023-11-29 05:59:06 24 4
gpt4 key购买 nike

我有一个 Jpanel,例如宽度为 500,高度为 100。我有计算屏幕垂直中心 (y) 和水平中心 (x) 的公式。我用它来 drawString(myText, x, y) 但它将文本写在 jpanel 的边界之上。这是我正在使用的 paintComponent 代码。

  protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
String MenuString = Menu.get(MenuChannel);
fontMetrics = g2d.getFontMetrics(realFont);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setBackground(Color.PINK);
g2d.fillRect(0,0,getWidth(),getHeight());
g2d.setColor(Color.WHITE);
g2d.setFont(realFont);

java.awt.geom.Rectangle2D rect = fontMetrics.getStringBounds(MenuString, g2d);
int textHeight = (int)rect.getHeight();
int textWidth = (int)rect.getWidth();
int panelHeight = getHeight();
int panelWidth = getWidth();
int x = (panelWidth - textWidth) / 2;
int y = (panelHeight - textHeight) / 2;
System.out.println("tH:" + textHeight + "\ntW:" + textWidth + "\npH:" + panelHeight + "\npW:" + panelWidth);
g2d.drawString(MenuString,x,y);
}

最佳答案

是的 - 这很痛苦 - drawString 将使用 y 作为底线(或基本文本行)来绘制你的 String。如果你想在 Rectangle 中居中 String 你应该使用 FontMetrics

来实现它

关于Java drawString 正在绘制超出范围的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10839940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com