You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JTextField自定义背景后重绘文本的跨字体y坐标适配问题

解决方案

核心是通过FontMetrics获取当前字体的排版参数计算基线坐标,不要使用硬编码的字号推导公式:

  1. Graphics.drawString传入的y坐标是文本基线的位置,不是文本的顶部或底部坐标。不同字体系列的字符高度、基线到字符顶部的距离(Ascent)、基线到字符底部的距离(Descent)都存在差异,硬编码公式只能适配部分字体的参数,换字体自然会出现错位。
  2. 直接读取JTextField的内边距、当前字体的排版参数计算y坐标,可以适配所有字体系列和字号。

修改后的代码

只需替换SplitBackgroundTextField类的paintComponent方法即可:

@Override
protected void paintComponent(Graphics g) {
  super.paintComponent(g);
  FontMetrics fm = g.getFontMetrics(getFont());
  int iWidth= fm.stringWidth(initialText);
  g.setColor(inactiveBackground);
  g.fillRect(0, 0, iWidth+margin, getHeight());
  g.setColor(Color.BLACK);
  // 通用y坐标计算逻辑
  Insets insets = getInsets();
  int availableHeight = getHeight() - insets.top - insets.bottom;
  int textY = insets.top + (availableHeight - fm.getHeight()) / 2 + fm.getAscent();
  g.drawString(initialText, margin, textY);
}

替换后无论使用Font.DIALOG还是Font.MONOSPACED,10-20号所有字号都不会出现垂直错位问题。


内容的提问来源于stack exchange,提问作者Jörg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:15:01