Silva
Silva

Reputation: 13

Dynamically displaying swing components in a transparent JPanel

I'm dealing with a very specific issue. When I remove all the components of a transparent JPanel (background color with 0 alpha) and add new components, the removed elements are still displayed in the JPanel. Here is an example of the behavior.

And here is the code to generate it:

class MyPanel extends JPanel {
    public MyPanel() {
        this.setLayout(new FlowLayout());
        this.setBackground(new Color(0, 0, 0, 0));
    }

    public void updateComponents() {
        this.removeAll();
        this.revalidate();

        int n = new Random().nextInt(10);

        for (int i = 0; i < n; i++) {
            this.add(new JButton("Dummy Button"));
        }
    }
}

public class Runner {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1280, 720);

        MyPanel panel = new MyPanel();

        JButton btUpdate = new JButton("Update");
        btUpdate.addActionListener(actionEvent -> {
            panel.updateComponents();
        });

        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(btUpdate, BorderLayout.NORTH);
        frame.getContentPane().add(panel, BorderLayout.SOUTH);

        frame.setVisible(true);
    }
}

Can somebody help me?

Upvotes: 1

Views: 58

Answers (1)

camickr
camickr

Reputation: 324147

this.revalidate();

The point of invoking revalidate() is to invoke the layout manager.

You need to invoke that method AFTER you add all the components to the panel.

You also need to make sure the components are painted so the code should be:

this.revalidate();
this.repaint();

I have even tried using the AlphaContainer

How? Post your code showing what you attempted.

The usage should be:

//frame.getContentPane().add(panel, BorderLayout.SOUTH);
frame.getContentPane().add(new AlphaContainer(panel), BorderLayout.SOUTH);

Upvotes: 1

Related Questions