图形不会在透明的JPanel上清除

时间:2016-07-28 16:10:40

标签: java swing paintcomponent graphics2d

我正在创建一个空白的透明JPanel,然后绘制线条以在其上形成框。我想增加盒子的大小,但是当我这样做的时候,我最终会留下一条线路,这些线条曾经是以前的线条 我在线搜索了很多,但似乎无法找到适合我的解决方案。 任何帮助将不胜感激!

public class AVTBox extends JPanel {

private int boxSize = 100;
private boolean started = false, stopped = true, track = false;
private final int center = 150;
private final int maxBoxSize = 300, minBoxSize = 25;
private final int lockBoxSize = 30;

public AVTBox() 
{
    this.setOpaque(false);
    this.repaint();
}

@Override
protected void paintComponent(Graphics g)
{
    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D)g.create();

    g2.setStroke(new BasicStroke(3.0f));
    g2.setColor(Color.BLACK);

    g2.draw(new Line2D.Double(center - (boxSize/2), center - (boxSize/2) + (boxSize*0.3), 
                              center - (boxSize/2), center + (boxSize/2) - (boxSize*0.3))
    );
    g2.draw(new Line2D.Double(center + (boxSize/2), center - (boxSize/2) + (boxSize*0.3), 
                              center + (boxSize/2), center + (boxSize/2) - (boxSize*0.3))
    );
    g2.draw(new Line2D.Double(center - (boxSize/2) + (boxSize*0.3), center - (boxSize/2), 
                              center + (boxSize/2) - (boxSize*0.3), center - (boxSize/2))
    );
    g2.draw(new Line2D.Double(center - (boxSize/2) + (boxSize*0.3), center + (boxSize/2), 
                              center + (boxSize/2) - (boxSize*0.3), center + (boxSize/2))
    );
    g2.dispose();
}

public void setBoxSize(String change)
{
    switch (change) {
        case "add":
            if(boxSize < maxBoxSize)
            {
                boxSize++;
            }   break;
        case "sub":
            if(boxSize > minBoxSize)
            {
                boxSize--;
            }   break;
    }
    this.revalidate();
    this.repaint();
}
}

编辑:当面板具有完全不透明的背景但是在透明背景上移动这些线条时,所有内容都能正常工作。我需要找到一种让这个“动画”在透明背景上工作的方法。

This image显示当用户增加框大小(绿色箭头)和当前发生的情况(红色箭头)时会发生什么。

抱歉可怕的MSpaint图像!

1 个答案:

答案 0 :(得分:0)

所以我明白了;我将这个JPanel添加到另一个JPanel而不是JFrame。不完全确定原因,但直接添加到JFrame后,一切都运行良好。