我正在使用向JFrame添加重量级(Canvas)的应用程序。画布是第3方组件,因此我必须保持其重量级。我想为用户添加在画布上绘制并绘制选择矩形的功能。

我认为我无法使用玻璃窗格执行此操作,因为重量级画布将显示在玻璃窗格上方。我尝试将鼠标侦听器添加到画布上并直接在其图形上绘制,但这似乎具有“闪烁”效果,因为它不是轻量级的双缓冲组件。

有没有办法在重量级组件上实现这种平滑绘制?

这是我当前尝试的重量级组件的绘制方法,但是仍然有闪烁。

    @Override
    public void paint(Graphics g)
    {
        super.paint(g);
        if (showUserSelection)
        {
            Point startDrawPoint = new Point(Math.min(startSelectPoint.x,
                    endSelectPoint.x), Math.min(startSelectPoint.y,
                    endSelectPoint.y));
            Point endDrawPoint = new Point(Math.max(startSelectPoint.x,
                    endSelectPoint.x), Math.max(startSelectPoint.y,
                    endSelectPoint.y));
            int w = endDrawPoint.x - startDrawPoint.x;
            int h = endDrawPoint.y - startDrawPoint.y;
            if (w > 0 && h > 0)
            {
                BufferedImage img = new BufferedImage(w, h,
                        BufferedImage.TYPE_INT_ARGB);
                Graphics2D imgGraphics = img.createGraphics();
                imgGraphics.fillRect(0, 0, w, h);
                g.drawImage(img, startDrawPoint.x, startDrawPoint.y, w, h,
                        null);

            }
        }
    }

最佳答案

我不知道“ Swing中的主机AWT / SWT”组件有所减少,但是您应该能够围绕自己进行工作。

您是否考虑过自己实现双重缓冲?

一目了然,您完成代码的90%。

@Override
public void paint(Graphics g)
{
    BufferedImage buffer = new BufferedImage(COMPONENT_WIDTH, COMPONENT_HEIGHT, BufferedImage.TYPE_INT_ARGB);

    Graphics bufferG = buffer.getGraphics();

    super.paint(bufferG);
    if (showUserSelection)
    {
        Point startDrawPoint = new Point(Math.min(startSelectPoint.x,
                endSelectPoint.x), Math.min(startSelectPoint.y,
                endSelectPoint.y));
        Point endDrawPoint = new Point(Math.max(startSelectPoint.x,
                endSelectPoint.x), Math.max(startSelectPoint.y,
                endSelectPoint.y));
        int w = endDrawPoint.x - startDrawPoint.x;
        int h = endDrawPoint.y - startDrawPoint.y;
        if (w > 0 && h > 0)
        {
            bufferG.fillRect(startDrawPoint.x, startDrawPoint.y, w, h);

        }
    }

    g.drawImage(buffer, 0, 0, null);
}

10-05 19:35