边角圆角

时间:2015-06-02 16:43:27

标签: java awt

这里我有一小段代码用于使用AWT获取矩形框。但我希望边框应该是圆角。你能建议我吗?

int width = 150;
        int height = 50;

        BufferedImage bufferedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g2d = bufferedImage.createGraphics();

        Font font = new Font("Georgia", Font.BOLD, 18);
        g2d.setFont(font);

        RenderingHints rh = new RenderingHints(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        rh.put(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);

        g2d.setRenderingHints(rh);

        GradientPaint gp = new GradientPaint(0, 0,
                Color.decode("#24777D"), 0, height / 2, Color.decode("#008080"), true);

        g2d.setPaint(gp);
        g2d.fillRect(0, 0, width, height);

        g2d.setColor(new Color(255, 255, 255));

        g2d.dispose();

1 个答案:

答案 0 :(得分:1)

除了fillRoundRect()方法之外,还使用Graphics2D类的drawRoundRect()方法绘制边框.Follow API文档。这是一个试用的示例代码。

 JFrame f = new JFrame();
 f.setLayout(null);
 f.setDefaultCloseOperation(3);
 f.setSize(500, 500);
 f.setLocationRelativeTo(null);
 JPanel p = new JPanel() {
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    int width = getWidth();
    int height = getHeight();
    Graphics2D graphics = (Graphics2D) g;
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);


    //Draws the rounded opaque panel with borders.
    graphics.setColor(getBackground());
    //paint background
    graphics.fillRoundRect(0, 0, width, height, 17, 17);
    graphics.setColor(getForeground());
    //paint border
    graphics.drawRoundRect(0, 0, width, height, 17, 17);
 }
 };
 p.setBounds(20,20,150,50);
 p.setOpaque(false);
 f.getContentPane().setBackground(Color.BLUE);
 f.add(p);
 f.setVisible(true);