簡體   English   中英

為什么此計時器中的 alpha 會在此 Java Swing 面板中自行繪制?

[英]Why does the alpha in this timer draw on top of itself in this Java Swing Panel?

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.Timer;

    public class Main {
        
        
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setLayout(new FlowLayout());
            frame.setSize(new Dimension(100, 100));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            TestPanel panel = new TestPanel();
            panel.setPreferredSize(new Dimension(50,50));
            frame.add(panel);
            frame.setVisible(true);
        }
        
        static class TestPanel extends JPanel implements ActionListener{
            
            private static final long serialVersionUID = 8518959671689548069L;
            
            public TestPanel() {
                super();
                Timer t = new Timer(1000, this);
                t.setRepeats(true);
                t.start();
            }
            
            int opacity = 10;
            @Override
            public void actionPerformed(ActionEvent e) {
                if(opacity >= 250) {
                    opacity = 0;
                }
                else {
                    this.setBackground(new Color(255, 212, 100, opacity));
                    this.repaint();
                    opacity+=10;
                    System.out.println("opacity is " + opacity);
                }
            }
            
        }
    }

alpha 變化的速度比它應該的要快。 達到某個點后,不透明度下降,而控制台中打印的不透明度小於 250。調整 window 的大小“重置”它,使 alpha 正確。

我如何讓它真正正確地繪制阿爾法?

this.setBackground(new Color(255, 212, 100, opacity));

Swing 不支持半透明背景。

Swing 期望組件是:

  1. opaque - 這意味着組件將在進行自定義繪制之前先用不透明顏色重新繪制整個背景,或者
  2. 完全透明 - 在這種情況下 Swing 將首先繪制第一個不透明父組件的背景,然后再進行自定義繪制。

setOpaque(...)方法用於控制組件的 opaque 屬性。

在任何一種情況下,這都可以確保刪除任何繪畫工件,並且可以正確完成自定義繪畫。

如果要使用透明度,則需要自己進行自定義繪畫以確保清除背景。

面板的自定義繪畫將是:

JPanel panel = new JPanel()
{
    protected void paintComponent(Graphics g)
    {
        g.setColor( getBackground() );
        g.fillRect(0, 0, getWidth(), getHeight());
        super.paintComponent(g);
    }
};
panel.setOpaque(false); // background of parent will be painted first

每個使用透明度的組件都需要類似的代碼。

或者,您可以查看自定義 class 的透明背景,該自定義 class 可用於為您完成上述工作的任何組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM