How can we implement transparent JDialog in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

A JDialog is a subclass of Dialog class and it does not hold minimize and maximize buttons at the top right corner of the window. There are two types of dialog boxes namely, modal and non-modal. The default layout for a dialog box is BorderLayout.

In the below program, we can implement a transparent JDialog by customizing the AlphaContainer class and override the paintComponent() method.

Example

import java.awt.*;
import javax.swing.*;
public class TransparentDialog {
   public static void main (String[] args) {
      JDialog dialog = new JDialog();
      dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      dialog.getRootPane().setOpaque(false);
      dialog.setUndecorated(true);
      dialog.setBackground(new Color (0, 0, 0, 0));
      JPanel panel = new JPanel(new BorderLayout ());
      panel.setBackground(new Color (0, 0, 0, 64));
      dialog.add(new AlphaContainer(panel));
      JSlider slider = new JSlider();
      slider.setBackground(new Color(255, 0, 0, 32));
      panel.add (new AlphaContainer(slider), BorderLayout.NORTH);
      JButton button = new JButton("Label text");
      button.setContentAreaFilled(false);
      panel.add(button, BorderLayout.SOUTH);
      dialog.setSize(400, 300);
      dialog.setLocationRelativeTo(null);
      dialog.setVisible(true);
   }
}
class AlphaContainer extends JComponent {
   private JComponent component;
   public AlphaContainer(JComponent component){
      this.component = component;
      setLayout(new BorderLayout());
      setOpaque(false);
      component.setOpaque(false);
      add(component);
   }
   @Override
   public void paintComponent(Graphics g) {
      g.setColor(component.getBackground());
      g.fillRect(0, 0, getWidth(), getHeight());
   }
}

Output

raja
Published on 22-Aug-2019 18:21:29
Advertisements