其实到不是很难,网上有很多的帖子啊,我给你找了一个,我编译了下,可以运行,自己读一下,改改,其实主要是下面思路:
1.利用Toolkit获得屏幕的size;
2.利用Robot获得当前窗口快照,也就是背景;
3.动态修改背景为快照即可;
import java.awt.Dimension;
import java.awt.*;
import javax.swing.*;
public class TransparentBackground extends JComponent {
private JFrame frame;
private Image background;
public TransparentBackground(JFrame frame) {
this.frame = frame;
updateBackground();
}
public void updateBackground() {
try {
Robot rbt = new Robot();
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dim = tk.getScreenSize();
background = rbt.createScreenCapture(new Rectangle(0, 0, (int) dim
.getWidth(), (int) dim.getHeight()));
} catch (Exception ex) {
//p(ex.toString( ));
ex.printStackTrace();
}
}
public void paintComponent(Graphics g) {
Point pos = this.getLocationOnScreen();
Point offset = new Point(-pos.x, -pos.y);
g.drawImage(background, offset.x, offset.y, null);
}
public static void main(String[] args) {
JFrame frame = new JFrame(" Transparent Window ");
TransparentBackground bg = new TransparentBackground(frame);
bg.setLayout(new BorderLayout());
JButton button = new JButton(" This is a button ");
bg.add(BorderLayout.NORTH, button);
JLabel label = new JLabel(" This is a label ");
bg.add(BorderLayout.SOUTH, label);
frame.getContentPane().add(BorderLayout.CENTER, bg);
frame.pack();
frame.setSize(150, 100);
frame.show();
}
}
上面的程序还有个不完美的地方就是,当窗口移动时候,并不能动态重新捕获快照,并修改背景,这个可以通过
重写画布的paint方法,调用repaint()方法去完善,自己试试。