Im在这段代码中,我有一个窗口,其中一个角落有一个蓝色的框。
我需要在此框中对齐文本中心。
public class drawComponent extends JComponent {
public void paintComponent(Graphics g){ //called on window update
int clueHeightDiff= 0;
int gap = 5;
int border = 10;
Font font = new Font("Ariel", Font.PLAIN, 30);
Color blue = new Color(0,0,255);
Color white = new Color(255,255,255);
int winH = Jeopardy.window.getBounds().getSize().height;
int winW = Jeopardy.window.getBounds().getSize().width;
int width = (winW - ((2 * border) + (5 * gap))) / 6 ;
int height = ((winH - ((4*border) + (5 * gap) + clueHeightDiff ))) / 6;
int clueHeight = height + clueHeightDiff;
int Fx = border + (5* width) + (5*gap);
int foY = border + (2*gap) + (2*height) + clueHeightDiff;
Rectangle F2 = new Rectangle(Fx,foY, width , height);
Graphics2D g2f2 = (Graphics2D) g;
g2f2.draw(F2);
g2f2.fill(F2);
g2f2.setColor(blue);
FontMetrics metrics = g2f2.getFontMetrics(font);
int height = metrics.getHeight();
int width = metrics.stringWidth(text);
Dimension size = new Dimension(width+2, height+2);
考虑到这个盒子的X和Y边界,我需要文字舒适地贴合在里面。我根本无法找到一种有效的方法,因为根据documentation,stringwidth()只返回第一个字符的值。
答案 0 :(得分:2)
FontMetrics#stringwidth
会返回渲染文本所需的像素数量
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane(new Rectangle(150, 150, 50, 50)));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Rectangle boxIn;
public TestPane(Rectangle boxIn) {
this.boxIn = boxIn;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
String text = "Hello";
FontMetrics fm = g2d.getFontMetrics();
int x = boxIn.x + ((boxIn.width - fm.stringWidth(text)) / 2);
int y = boxIn.y + (((boxIn.height - fm.getHeight()) / 2) + fm.getAscent());
g2d.setColor(Color.BLUE);
g2d.fill(boxIn);
g2d.setColor(Color.WHITE);
g2d.drawString(text, x, y);
g2d.dispose();
}
}
}
您也可以使用TextLayout
,这有点复杂,但会为您提供一个边界框,表示渲染文本所需的区域。这对于属性文本更有用,但仍然有用