Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีสร้าง JDialog โปร่งใส (Transparent) ใน Java


JDialog เป็นคลาสย่อยของ Dialog ไม่มีปุ่ม minimize และ maximize ที่มุมขวาบน มี 2 ประเภท: modal และ non-modal Layout เริ่มต้นคือ BorderLayout

ในโปรแกรมนี้ เราสร้าง transparent JDialog โดยปรับแต่งคลาส AlphaContainer และ override เมธอด paintComponent()

ตัวอย่าง

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

ผลลัพธ์

วิธีสร้าง JDialog โปร่งใส (Transparent) ใน Java