无伪影的透明面板

Transparent Panel with no artifacts

我对覆盖 JComponent 对象和在 Java 中绘制的知识非常有限。我想要做的是创建一个函数,我可以调用它来设置透明度并避免在面板内单击按钮时出现伪影。基本上我将在另一个面板内的 JPanel 上使用它。喜欢,

class panel1 extends JPanel(){
public panel1(){
    this.add(new panel2())
    //call the setPanelTransparency(this);
}

class panel2 extends JPanel(){
    this.setPreferredSize(new Dimension(500,500));
    this.setBorder(BorderFactory.createLineBorder(2,Color.RED);
}

如何更正此方法?当我尝试将其作为方法包含在 panel1 class.

中时出现错误
 public void setPanelTransparency(JPanel myPanel){

    protected void paintComponent ( Graphics g )
    {
        g.setColor ( getBackground () );
        g.fillRect ( 0, 0, getWidth (), getHeight () );
        super.paintComponent ( g );
    }

    });
    myPanel.setOpaque(false);
    myPanel.setBackground(new Color(49,43,31,60));
}

如有任何帮助,我将不胜感激。我只想知道使面板透明而没有任何伪影风险的最简单方法。我需要一个可以调用的方法。另外,我尝试了 UIManager.put(),但似乎没有任何伪影就无法正确应用。

我希望能有最简单的解决方案来将透明度应用到我的项目中,这样我就可以专注于创建表格。

您不能使用类似 setPanelTransparency() 的方法来覆盖方法。

该面板本身需要 class 才能覆盖 paintComponent(...) 方法:

//public void setPanelTransparency(JPanel myPanel){
public class TransparentPanel extend JPanel 
{
    TransparentPanel()
    {
        setOpaque( false );
    }

    @Override
    protectect void paintComponent(...)
    ...
}

那么您只需像这样使用面板:

TransparentPanel panel = new TransparentPanel();
panel.setBackground(...);
panel.add( new JTestField(10) );
frame.add( panel );

有关此方法和不同解决方案的详细信息,请参阅 Background With Transparency