摆动darwn rect有空隙

时间:2019-03-05 07:23:08

标签: java swing user-interface

我正在完成作业,但是在使用秋千时遇到了问题。我在连续的像素上使用了drawRect,希望可以产生控制阴影的效果,但是绘制的矩形之间存在间隙,即使它们的像素是连续的,我也想知道如何修复它。

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;

class DropShadowPanel extends JPanel {

    private static final long serialVersionUID = 1L;

    public int pixels;

    public DropShadowPanel(int pix) {
        setOpaque(false);
        this.pixels = pix;
        Border border = BorderFactory.createEmptyBorder(pixels, pixels, pixels, pixels);
        this.setBorder(BorderFactory.createCompoundBorder(this.getBorder(), border));
        this.setLayout(new BorderLayout());
    } 

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        int shade = 0;
        int topOpacity = 60;
        for (int i = 0; i <= pixels; i++) {
            g2d.setColor(Color.black);
            g2d.drawRect(i, i, this.getWidth() - ((i * 2)), this.getHeight() - ((i * 2)));  // Originally i*2+1,but i fix it the problem also appears.
       }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }
}

public class  Main {
    public static void main(String[] args) {
        JFrame jFrame = new JFrame("Test");
        JPanel panel = new JPanel();
        panel.add(new DropShadowPanel(20));
        jFrame.add(panel);
        jFrame.pack();
        jFrame.setVisible(true);
    }
}

现在,我已经更新了完整的代码。为了使问题更清楚,我将代码中的颜色更改为黑色。

这些是问题图像: enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

您正在跳过一个像素。在方法for的{​​{1}}循环中。

paintComponent()为0(零)时,对i的呼叫为...

drawRect()

并且当drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1); 等于1(一)时,对i的呼叫是...

drawRect()

换句话说,您正在跳过2(两)。