在半透明組件上重新繪製
問題:當嘗試在macOS 上用Java 創建半透明視窗並且添加一個JLabel帶有動態文本,組件不重繪
解決方案:要解決此問題,可以擴展自定義的JLabel並實現Icon接口以達到所需的半透明效果。以下是使用AlphaComposite 的範例:
import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JLabel; public class TranslucentLabel extends JLabel { private Image image; private AlphaComposite alphaComposite; public TranslucentLabel() { super(); setBackground(new Color(0f,0f,0f,0.3f)); alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f); } @Override public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); image = createImage(getWidth(), getHeight()); Graphics2D imageGraphics = (Graphics2D) image.getGraphics(); imageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); super.paintComponent(imageGraphics); g2d.setComposite(alphaComposite); g2d.drawImage(image, 0, 0, null); g2d.dispose(); } }
在此方法中,建立自訂JLabel (TranslucentLabel),並應用AlphaComposite 技術在半透明框架背景上合成半透明背景,確保組件正確重新繪製半透明。
以上是如何在 macOS 上用 Java 正確地在半透明視窗上重新繪製 JLabel?的詳細內容。更多資訊請關注PHP中文網其他相關文章!