Java Swing: Transparent PNG permanently captures original background

前端 未结 2 1257
没有蜡笔的小新
没有蜡笔的小新 2020-12-12 05:35

I have the following code:

import javax.swing.JWindow;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import java.awt.Graphics;
import java.aw         


        
2条回答
  •  情话喂你
    2020-12-12 06:35

    Don't override the paint() method of a top level container, especially when you don't invoke super.paint(). This will cause painting problems. If you ever do need to do custom painting then you should override the paintComponent() method of JPanel (or JComponent) and then add the panel to the window/frame. Read the Swing tutorial on Custom Painting. This advice is given daily, I don't know why people still try to override paint()???

    However this is only one of your problems. The better solution is to add your image to a JLabel and then add the label to the window. You will also need to make the window background transparent:

    import javax.swing.*;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.Image;
    import java.awt.Toolkit;
    
    public class Stuff extends JWindow
    {
        //Get transparent image that will be use as splash screen image.
        Image bi=Toolkit.getDefaultToolkit().getImage("transparent.png");
        ImageIcon ii=new ImageIcon(bi);
        public Stuff()
        {
            try
            {
                setBackground( new Color(0, 0, 0, 0) );
                setSize(ii.getIconWidth(),ii.getIconHeight());
                setLocationRelativeTo(null);
                JLabel label = new JLabel(ii);
                add(label);
                show();
                //Thread.sleep(10000);
                //dispose();
                //JOptionPane.showMessageDialog(null,"This program will exit !!!","<>",JOptionPane.INFORMATION_MESSAGE);
            }
            catch(Exception exception)
            {
                exception.printStackTrace();
            }
        }
    
    /*
        //Paint transparent image onto JWindow
        public void paint(Graphics g)
        {
            super.paint(g);
            g.drawImage(bi,0,0,this);
        }
    */
        public static void main(String[]args)
        {
            Stuff tss=new Stuff();
        }
    }
    

提交回复
热议问题