2013-05-31 53 views
2

當我嘗試製作圓角矩形時,出現非常像素化的邊角。有什麼方法可以使它們變得平滑?如何平滑圓角矩形中的拐角,Swing?

下面是一個圖像(注意拐角):

enter image description here

這裏是我子類並覆蓋paint方法(帶有像素化角落)按鈕的代碼:

public class ControlButton extends JButton { 

    public final static Color BUTTON_TOP_GRADIENT = new Color(176, 176, 176); 
    public final static Color BUTTON_BOTTOM_GRADIENT = new Color(156, 156, 156); 

    public ControlButton(String text) { 
     setText(text); 
    } 

    public ControlButton() { 
    } 

    @Override 
    protected void paintComponent(Graphics g){ 
     Graphics2D g2 = (Graphics2D)g.create(); 
     g2.setPaint(new GradientPaint(
       new Point(0, 0), 
       BUTTON_TOP_GRADIENT, 
       new Point(0, getHeight()), 
       BUTTON_BOTTOM_GRADIENT)); 
     g2.fillRoundRect(0, 0, getWidth(), getHeight(), 20, 20); 
     g2.dispose(); 
    } 
} 
+1

RenderingHints中,設置反鋸齒上。 – arynaq

+0

看看這個問題的答案 - http://stackoverflow.com/questions/15025092/border-with-rounded-corners-transparency – Ciphor

回答

6

試試這個:

RenderingHints qualityHints = new RenderingHints(
    RenderingHints.KEY_ANTIALIASING, 
    RenderingHints.VALUE_ANTIALIAS_ON); 
qualityHints.put(
    RenderingHints.KEY_RENDERING, 
    RenderingHints.VALUE_RENDER_QUALITY); 
g2.setRenderingHints(qualityHints); 

看看日出入口文件:

代碼:

import javax.swing.*; 

import java.awt.*; 

public class ControlButton extends JButton { 

    public final static Color BUTTON_TOP_GRADIENT = new Color(176, 176, 176); 
    public final static Color BUTTON_BOTTOM_GRADIENT = new Color(156, 156, 156); 

    public ControlButton(String text) { 
    setText(text); 
    } 

    public ControlButton() { 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
    Graphics2D g2 = (Graphics2D)g.create(); 
    RenderingHints qualityHints = 
     new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
    qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); 
    g2.setRenderingHints(qualityHints); 

    g2.setPaint(new GradientPaint(new Point(0, 0), BUTTON_TOP_GRADIENT, new Point(0, getHeight()), 
            BUTTON_BOTTOM_GRADIENT)); 
    g2.fillRoundRect(0, 0, getWidth(), getHeight(), 20, 20); 
    g2.dispose(); 
    } 

    public static void main(String args[]) { 
    JFrame frame = new JFrame("test"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().add(new ControlButton("Hello, World")); 
    frame.pack(); 
    frame.setVisible(true); 
    } 
} 
+0

它有一點幫助,但問題是大多仍然存在(仍然沒有關閉使光滑)。 –

+0

http://docs.oracle.com/javase/7/docs/api/java/awt/RenderingHints.html如果您仍然不滿意,您可以應用更多的抗鋸齒效果,但抗鋸齒效果的影響最大。 – arynaq

+0

完美的作品。非常感謝! –