I've very limited knowledge with overriding JComponent
objects and painting in Java. What I'm trying to do is to create a function that I can call to set the transparency and avoid getting artifacts when buttons are clicked inside a panel. Basically I'm gonna be using this on a JPanel
inside another panel. Like,
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);
}
How do I correct this method? I get errors when I tried to include it as method in 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));
}
I'd appreciate any help. I would just like to know the simplest way to make Panels transparent without any risk of artifacts. I need a method that I can call. Also, I tried UIManager.put()
but doesn't seem to apply properly without any artifacts.
I'd appreciate the simplest solution to applying transparency to my project so I can focus on creating the tables.
You can't use a method like setPanelTransparency() to override a method.
That panel needs to be a class on its own to override the paintComponent(...) method:
//public void setPanelTransparency(JPanel myPanel){
public class TransparentPanel extend JPanel
{
TransparentPanel()
{
setOpaque( false );
}
@Override
protectect void paintComponent(...)
...
}
Then you just use the panel like:
TransparentPanel panel = new TransparentPanel();
panel.setBackground(...);
panel.add( new JTestField(10) );
frame.add( panel );
See Background With Transparency for more information on this approach and a different solution.