JTextField自定义背景后重绘文本的跨字体y坐标适配问题
解决方案
核心是通过FontMetrics获取当前字体的排版参数计算基线坐标,不要使用硬编码的字号推导公式:
Graphics.drawString传入的y坐标是文本基线的位置,不是文本的顶部或底部坐标。不同字体系列的字符高度、基线到字符顶部的距离(Ascent)、基线到字符底部的距离(Descent)都存在差异,硬编码公式只能适配部分字体的参数,换字体自然会出现错位。- 直接读取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
相关产品推荐
相关产品推荐

