我使用以下代码在 JTextField 中创建占位符,但我的问题是占位符文本方向始终位于左侧
@Override
protected void paintComponent(final Graphics pG) {
super.paintComponent(pG);
if (placeholder.length() == 0 || getText().length() > 0) {
return;
}
final Graphics2D g = (Graphics2D) pG;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(new Color(phColor.getRed(),phColor.getGreen(),phColor.getBlue(),140));
g.drawString(placeholder, getMargin().right,(getSize().height)/2 + getFont().getSize()/2 );
}
如何在 JTextField 上创建文本方向向右的占位符?
这是我的问题的图片
最佳答案
使用 FontMetrics 类:
FontMetrics fM = g.getFontMetrics(/*The font that you're using*/);
g.drawString(/* Your Text */, rightEdge - fM.stringWidth(/* Your Text */), y);
通过将 x 位置添加到 JTextField 的宽度,可以获得右边缘。 您是否已经有一个方法:“getMargin.right()”?或者这是为了别的什么?
关于java - JTextField 中的占位符具有正确的方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60343837/