Home > Enterprise >  Setting an internal private panel opaque
Setting an internal private panel opaque

Time:09-17

Is there anyway i can set an internal private JPanel opaque? An example:

//Assuming I have no access rights to modify OuterPanel.java
class OuterPanel extends JPanel{

    private JPanel internalPanel = new JPanel();

    public OuterPanel(){
        setLayout(new BorderLayout());
        internalPanel.setOpaque(true);
        add(internalPanel, BorderLayout.CENTER);
    }
}

class MyClass{
    private OuterPanel myPanel;

    public MyClass(){
        panel = new OuterPanel();
        // is there anyway i can set myPanel's internalPanel to opaque(false)?
        // assuming OuterPanel is a library and i have no way to modify it.
    }
}

With the sample code above, assuming OuterPanel is a library class which I am unable to modify it's code, is there any way I could actually set it's internalPanel's opaque settings?

CodePudding user response:

As mentioned by maloomeister. I used the following code to resolve this.

class OuterPanel extends JPanel{

    private JPanel internalPanel = new JPanel();

    public OuterPanel(){
        setLayout(new BorderLayout());
        internalPanel.setOpaque(true);
        add(internalPanel, BorderLayout.CENTER);
    }
}

class MyClass{
    private OuterPanel myPanel;

    public MyClass(){
        panel = new OuterPanel();
        
        setAllOpaque(panel.getComponents());
    }
    
    // This method is called recursively to set ALL JPanels 
    private void setAllOpaque(Component[] comp){
        for (Component com : comp){
            if (com instanceof JPanel){
                JPanel p = (JPanel)com;
                p.setOpaque(false);
                
                setAllOpaque(p.getComponents());
            }
        }
    }
}

I used recursion as this current example of OuterPanel is simple but my actual actual JPanel is actually a form filled with many different JPanels within it. This resolved it.

It might not be the most refined method, so if anyone has a better solution please do share! :)

  • Related