如何在 Java 中实现透明的 JDialog?

awtjavaobject oriented programmingprogrammingswing

JDialogDialog 类的子类,它不包含窗口右上角的 最小化最大化 按钮。对话框有两种类型,即 模态非模态。对话框的默认布局是 BorderLayout

在下面的程序中,我们可以通过自定义 AlphaContainer 类并重写 paintComponent() 方法来实现透明的 JDialog。

示例

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());
   }
}

输出


相关文章