2011-12-21 75 views
2

這是我到目前爲止的內容,但是該字段中的文本不是反鋸齒。我嘗試了一段時間使用Google搜索,但找不到任何線索討論它(很令我驚訝)。有誰知道如何做到這一點?Java:如何在JTextField中啓用文本消除鋸齒?

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); 
    } 
    } 
+0

在計算器上的幫助,也許這個問題:?如何使的JTextPane畫反鋸齒字體(http://stackoverflow.com/q/2266199/851432) – Jomoos 2011-12-21 09:16:33

+0

'g.fillRoundRect(0,0 ,fieldWidth,fieldHeight,4,4);'這聽起來像一個標準的'JTextField'上[自定義邊框](http://stackoverflow.com/a/8463742/418556)的工作。 – 2011-12-21 09:29:06

+0

如果一行簡單的代碼能夠實現這個技巧,而且它的效率足夠高,那麼爲什麼還要使用自定義邊框呢?但我必須承認,這是一個很好的觀點。 – rtheunissen 2011-12-21 09:41:40

回答

0

這是我決定要做的,直到我能找到一個更優雅的解決方案 - 效果很好。

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); 
    } 
} 
+1

不確定GraphicUtils來自哪裏,但是對於該行,可以執行以下操作:'g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);' – bobtheowl2 2012-02-13 15:32:26

+0

這是我寫的應用各種'RenderingHints'的類,但是謝謝。 :) – rtheunissen 2012-02-13 18:45:01