如何平滑圆角矩形的角落,Swing?

时间:2013-05-31 18:37:19

标签: java swing user-interface

当我尝试制作圆角矩形时,我会得到非常像素化的角落。有没有办法让它们顺利出来?

这是一张图片(注意角落):

enter image description here

这是Button的代码,我将其子类化并覆盖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();
    }
}

2 个答案:

答案 0 :(得分:7)

试试这个:

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

答案 1 :(得分:0)

我这样做了

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

我觉得它比Dave Jarvis的方法给我提供了更平滑的边缘,但是我可能是错的。