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.
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.
One approach is to extend JLabel and implement Icon. This enables the creation of a translucent component that can display text.
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.
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); } }
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.
The above is the detailed content of How to Properly Repaint Translucent Swing Components?. For more information, please follow other related articles on the PHP Chinese website!