Java:如何在JTextField中启用文本抗锯齿?

Java:如何在JTextField中启用文本抗锯齿?,java,swing,fonts,antialiasing,Java,Swing,Fonts,Antialiasing,这是我到目前为止得到的,但是字段中的文本没有抗锯齿。我在谷歌上搜索了一段时间,但找不到任何讨论它的帖子(令我大吃一惊)。有人知道怎么做吗 public class SearchField extends JTextField{ public SearchField(){ super(); this.setOpaque(false); this.setPreferredSize(new Dimension(fieldWidth, fieldHeig

这是我到目前为止得到的,但是字段中的文本没有抗锯齿。我在谷歌上搜索了一段时间,但找不到任何讨论它的帖子(令我大吃一惊)。有人知道怎么做吗

public class SearchField extends JTextField{
    public SearchField(){
       super();
       this.setOpaque(false);
       this.setPreferredSize(new Dimension(fieldWidth, fieldHeight));
       this.setBorder(new EmptyBorder(4,8,4,8));
       this.setFont(fieldFont);
     }

    public void paintComponent(Graphics paramGraphics){
          Graphics2D g = (Graphics2D) paramGraphics;
          g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                             RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

          g.setColor(ColorConstants.LIGHT_GRAY);
          g.fillRoundRect(0,0,fieldWidth,fieldHeight,4,4);
          super.paintComponent(g);
     }
  }

如图所示,我发现使用它很有帮助,因为可以同时使用
isatariased
usesFractionalMetrics


示例中使用的
buffereImage
是巧合。

在找到更优雅的解决方案之前,我决定这样做——效果很好

private class SearchField extends JTextField{

   private final int fieldWidth = 375;
   private final int fieldHeight = 30;
   private final Font fieldFont = FontLoader.getCustomFont("Gotham-Bold.ttf", 15);
   private final Color foreground = ColorConstants.SEARCH_FIELD_FOREGROUND;
   private final Color background = ColorConstants.SEARCH_FIELD_BACKGROUND;

   public SearchField(){
      super();
      this.setOpaque(false);
      this.setPreferredSize(new Dimension(fieldWidth, fieldHeight));
      this.setBorder(new EmptyBorder(5,5,5,5));
      this.setFont(fieldFont);
      this.setForeground(new Color(0,0,0,0));
      this.setSelectedTextColor(new Color(0,0,0,0));
   }

   @Override
   public void paintComponent(Graphics paramGraphics){
      Graphics2D g = (Graphics2D) paramGraphics.create();
      GraphicUtils.enableAntiAliasing(g); //RenderingHints
      g.setColor(background);
      g.fillRoundRect(0, 0, fieldWidth, fieldHeight, 4, 4);
      super.paintComponent(g);
      g.setColor(foreground);
      g.drawString(this.getText(), 5, 20);
   }
}

关于StackOverflow的这个问题可能有帮助:
g.fillRoundRect(0,0,fieldWidth,fieldHeight,4,4)
这听起来像是一个标准
JTextField
上的工作。如果一行简单的代码就可以做到这一点,而且效率很高,为什么还要麻烦自定义边框呢?但我必须承认,这是一个很好的观点。为什么要费心呢?因为从长远来看,如果你遵循你正在使用的任何框架的风格(而不是绕道而行),你将是最有效率的。边境之风是。。。使用边界为什么不使用我们可以使用的工具来构建我们需要的组件?边框也是另一个类,因此在本例中,
RoundRectangle
的效率/效果非常好。不过没有争论-有很多方法可以做到这一点。不确定GraphicUtils来自何处,但对于该行,可以执行以下操作
g.setRenderingHint(renderingHits.KEY\u ANTIALIASING,renderingHits.VALUE\u ANTIALIAS\u ON)这是我编写的一个类,用于应用各种
渲染提示
,但谢谢。:)