Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào chúng ta có thể triển khai JDialog trong suốt trong Java?


A JDialog là một lớp con của Hộp thoại và nó không giữ thu nhỏ tối đa hóa ở góc trên cùng bên phải của cửa sổ. Có hai loại hộp thoại cụ thể là phương thức không moda l. Bố cục mặc định cho hộp thoại là BorderLayout.

Trong chương trình dưới đây, chúng ta có thể triển khai JDialog trong suốt bằng cách tùy chỉnh AlphaContainer và ghi đè paintComponent () phương pháp.

Ví dụ

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

Đầu ra

Làm cách nào chúng ta có thể triển khai JDialog trong suốt trong Java?