【问题标题】:Graphics won't clear on a transparent JPanel透明 JPanel 上的图形无法清除
【发布时间】:2016-07-28 16:10:39
【问题描述】:

我正在创建一个空白的透明 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 图像!

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖 minimal reproducible exampleShort, Self Contained, Correct Example。但是this.setLayout(null); 不是好兆头..
  • 这段代码有问题吗??我不这么认为,如果你给我们不相关的代码,你不会得到帮助!
  • 不要在 paintComponent() 方法中使用 setOpaque(false)。绘画方法仅用于绘画,您不应在绘画方法中更改组件的属性。在构造函数中设置属性。
  • @gpasch 是的,这是有问题的代码。它在不透明的背景下工作得很好。当我在透明背景上尝试时,我遇到了问题。

标签: java swing paintcomponent graphics2d


【解决方案1】:

所以我想通了;我将此 JPanel 添加到另一个 JPanel 而不是 JFrame。不完全确定原因,但在直接添加到 JFrame 后一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多