AWT自定义窗口形状使用透明图像

时间:2013-08-20 01:16:01

标签: java swing awt transparency

我正在尝试使用AWT创建UI。我想只使用图像和透明组件。现在我无法理解如何制作一个主窗口,它应该是一个自定义形状的PNG图像。图像中透明的所有区域都用黑色替换。这是我使用的代码:

public class Test {
static Image image;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        //switch to the right thread

        image = ImageIO.read(Test.class.getClassLoader().getResource("resources/images/panel.png").openStream());

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Frame frame = new Frame("Test");
                frame.setUndecorated(true);
                frame.setBackground(new Color(0,0,0,0));
                frame.add(new BackGround(image,image.getWidth(frame),image.getHeight(frame)));
                frame.pack();
                frame.setSize(image.getWidth(frame), image.getHeight(frame));
                frame.setVisible(true);
                frame.setLocationRelativeTo(null);
            }
        }
        );
    }
    private static class BackGround extends Component {
        private Image img;
        private int wid, hgt;
        public BackGround(Image img, int wid, int hgt){
            this.img=img;
            this.wid=wid;
            this.hgt=hgt;

        }
        @Override
        public void paint(Graphics graphics) {
                graphics.drawImage(image,0,0,wid,hgt,0,0,wid,hgt,null);
        }
    }
}

1 个答案:

答案 0 :(得分:6)