先写一个类public class la extends JComponent {
private JFrame frame; private Image background; public la(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); repaint(); } public static void main(String[] args) { JFrame frame = new JFrame("Transparent Window"); la bg = new la(frame); bg.setLayout(new BorderLayout( )); JButton button = new JButton("This is a button"); JLabel label = new JLabel("This is a label"); bg.add("South",label); frame.setUndecorated(true); frame.getContentPane( ).add("Center",bg); frame.setSize(500,400); frame.setLocation(400,400); frame.setVisible(true); } }
在其它类里调用
public static void main(String[] args) {
JFrame frame1 = new JFrame(); la bg = new la(frame1); bg.setLayout(new BorderLayout( )); JPanel donghua = new JPanel(){ public void paintComponent(Graphics g) { g.setColor(Color.blue); Image img = new ImageIcon("res/b3.png").getImage( ); g.drawImage(img,0,0,null); } }; donghua.setOpaque(false); bg.add(donghua); frame1.getContentPane( ).add("Center",bg); frame1.setSize(500,380); frame1.setLocation(580,240); frame1.setUndecorated(true); frame1.setVisible(true); //中间代码 try{ Thread.sleep(1500); frame1.setVisible(false);//启动面关闭 }catch(Exception e){ } }