我使用drawString()
方法使用Graphics绘制字符串,但我想将文本居中放在矩形中。我应该怎么做?矩形中的Java中心文本
回答
我用这个来中心的文本上一个JPanel
Graphics2D g2d = (Graphics2D) g;
FontMetrics fm = g2d.getFontMetrics();
Rectangle2D r = fm.getStringBounds(stringTime, g2d);
int x = (this.getWidth() - (int) r.getWidth())/2;
int y = (this.getHeight() - (int) r.getHeight())/2 + fm.getAscent();
g.drawString(stringTime, x, y);
垂直居中文本涉及很少,因为文本上升和文本呈现的方式。从内存来看,它应该更像y =((getHeight() - fm.getHeight())/ 2)+ fm.getAscent(); ...尝试在组件中心线上绘制一条线,并比较两种方法,如果我的记忆力很好,我相信这会更适合居中...... +1 – MadProgrammer
你说得对。我确定了我的答案。 –
您可能还想阅读[this](http://stackoverflow.com/questions/1055851/how-do-you-draw-a-string-centered-vertically-in-java) – MadProgrammer
居中文本有很多的“选项”。你是完全中心还是基于基线?
就个人而言,我更喜欢绝对的中心位置,但它取决于你在做什么?
public class CenterText {
public static void main(String[] args) {
new CenterText();
}
public CenterText() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int height = getHeight();
String text = "This is a test xyx";
g.setColor(Color.RED);
g.drawLine(0, height/2, getWidth(), height/2);
FontMetrics fm = g.getFontMetrics();
int totalWidth = (fm.stringWidth(text) * 2) + 4;
// Baseline
int x = (getWidth() - totalWidth)/2;
int y = (getHeight() - fm.getHeight())/2;
g.setColor(Color.BLACK);
g.drawString(text, x, y + ((fm.getDescent() + fm.getAscent())/2));
// Absolute...
x += fm.stringWidth(text) + 2;
y = ((getHeight() - fm.getHeight())/2) + fm.getAscent();
g.drawString(text, x, y);
}
}
}
+1作为对比。 – trashgod
- 1. java的旋转矩形围绕中心
- 2. 在核心文本中查找文本的边界矩形
- 3. Jointjs位置顶部的文本而不是中心的矩形
- 4. 查找矩形中心
- 5. 无法适应和中心文本在矩形SVG的javaScript
- 6. Fabricjs添加文本到矩形的中心
- 7. 战平叠加文本在矩形的中心(进度)
- 8. Delphi - 在矩形中心绘制文本多行
- 9. 获取离中心矩形最远的矩形
- 10. 中心在Java框架/面板中对齐矩形
- 11. 在java中打印矩形(中心有孔)
- 12. 以矩形为中心的textview
- 13. 获取矩形的旋转中心
- 14. 文本为中心的形状
- 15. 移动画布矩形触摸问题(矩形中心)
- 16. 矩形命中检测Java
- 17. 在Java中绘制矩形
- 18. 绘制矩形在Java中
- 19. 在Java中旋转矩形
- 20. 在网格上的矩形和矩形放置中居中文本
- 21. 中心矩形在新窗口
- 22. OpenCV从中心x,y绘制矩形
- 23. 围绕中心旋转矩形
- 24. JavaFX旋转矩形关于中心?
- 25. 矩形几何不包括RectF中心
- 26. D3将文本添加到矩形中
- 27. 文本在矩形 - Pygame的
- 28. 中心文本与背景CSS“形状”
- 29. 关于在Java中将矩形添加到矩形的建议
- 30. 矩形网格中矩形网格的最小数量[JAVA]
你的标题状态,使用了'JTextField',但不是你的题。那么这是真的吗? – Mordechai
您的标题是:*文本字段中的Java中心文本*,但您的文章说:*我使用'drawString()'方法在Graphics上绘制字符串,但我想将文本居中放在一个矩形中。我应该怎么做?*这是如何对应的 –
纠正我的问题: 我在JFrame的某个地方有一个矩形....我想绘制以矩形为中心的字符串。我应该怎么做? –