Translucent panel Java swing

38 views Asked by At

I tried to create a translucent panel in java swing covering and underlying panel, but I've a problem: If, for example, there is a jtextfield in the panel below and the text of this component is subsequently changed, it is brought back to the foreground and 'breaks' the upper translucent panel. How can I do?

Thank you in advance!

Below is an example code.

 private static void createAndShowUI()
    {
        JTextField textField = new JTextField("Testo di esempio");
        textField.setSize(200, 60);
        textField.setEnabled(false);
        
        JButton button = new JButton("Premi");
        button.setBounds(40, 30, 200, 60);
        button.setEnabled(false);
        
        JPanel mainPanel = new JPanel();
        mainPanel.setPreferredSize(new Dimension(400, 400));
        mainPanel.add(textField, new AbsoluteConstraints(10, 10, 200, 60));
        mainPanel.add(button,  new AbsoluteConstraints(10, 90, 200, 60));
        
        JPanel translucentPanel = new JPanel();
        translucentPanel.setBackground(new Color(204, 241, 17, 180));
        translucentPanel.addMouseListener(new MouseAdapter() {
        });

        JLayeredPane layeredPane = new JLayeredPane();
        layeredPane.setLayout(new AbsoluteLayout());
        layeredPane.setPreferredSize(new Dimension(400, 400));
        layeredPane.add(mainPanel, new AbsoluteConstraints(0, 0, 400, 400), JLayeredPane.PALETTE_LAYER);
//        layeredPane.add(button,  new AbsoluteConstraints(10, 90, 200, 60), JLayeredPane.PALETTE_LAYER);
        layeredPane.add(translucentPanel,  new AbsoluteConstraints(0, 0, 400, 400), JLayeredPane.DEFAULT_LAYER);

        JFrame frame = new JFrame("Esempio di JLayeredPane");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(layeredPane);
        frame.pack();
        frame.setVisible(true);
        
        
        
        textField.requestFocus();

        // Aggiorna il JTextField dopo 5 secondi
        Timer timer = new Timer(5000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textField.setText("Testo aggiornato");
            }
        });
        timer.setRepeats(false);
        timer.start();
}

I have also tried disabling the jtextfield without success as well as using a jlayeredpane and setting different layers. I would like the jtextfield to always remain below the translucent panel or alternatively not be redrawn as long as the top translucent panel is present even if I setText.

0

There are 0 answers