"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Properly Repaint Translucent Swing Components?

How to Properly Repaint Translucent Swing Components?

Published on 2024-11-25
Browse:418

How to Properly Repaint Translucent Swing Components?

How to Handle Re-painting on a Translucent Frame/Panel/Component

Translucent components can present re-painting challenges when updating their content, leading to unappealing visual effects. This article explores a solution involving AlphaComposite and provides code examples to implement it.

Understanding AlphaComposite

AlphaComposite allows the manipulation of how graphics are composited onto the frame. By setting the appropriate rule, it becomes possible to control the transparency of rendered elements.

Implementing a Translucent Component

One approach is to extend JLabel and implement Icon. This enables the creation of a translucent component that can display text.

Modifying the Entire Frame to Be Translucent

To make the entire frame translucent, adjust the frame's background color to have a transparency component. However, it's important to note that this will also affect the content's opacity.

Code Examples

JLabel Example:

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JLabel;

public class TranslucentJLabel extends JLabel {

    public TranslucentJLabel() {
        setOpaque(false);
        setBackground(new Color(0f, 0f, 0f, 0.5f));
        setFont(new Font("Serif", Font.PLAIN, 48));
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setComposite(AlphaComposite.SrcOver);
        super.paintComponent(g2d);
    }

}

Translucent Frame Example:

import java.awt.AlphaComposite;
import java.awt.Color;
import javax.swing.JFrame;

public class TranslucentFrame extends JFrame {

    public TranslucentFrame() {
        setBackground(new Color(0f, 0f, 0f, 0.7f));
        setUndecorated(true);
        setSize(300, 200);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setComposite(AlphaComposite.SrcOver);
        super.paint(g2d);
    }
}

By implementing these techniques, you can create translucent frames and components with effective re-painting behavior.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3