📄 trans_three.java
字号:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.event.*;
import java.awt.event.*;
import java.util.*;
class TransparentBackground extends JComponent
implements ComponentListener, WindowFocusListener,Runnable {
private JFrame frame;
private Image background;
private long lastupdate = 0;
public boolean refreshRequested = true;
public TransparentBackground(JFrame frame) {
this.frame = frame;
updateBackground( );
frame.addComponentListener(this);
frame.addWindowFocusListener(this);
new Thread(this).start( );
}
/**
* @todo 获取背景图片
*
*/
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) {
ex.printStackTrace( );
}
}
/**
* @todo 通过当前frame的大小和位置在 background背景中截取图
* 作为当前frame的背景图片
*/
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 void componentShown(ComponentEvent evt) { repaint( ); }
public void componentResized(ComponentEvent evt) { repaint( ); }
public void componentMoved(ComponentEvent evt) { repaint( ); }
public void componentHidden(ComponentEvent evt) { }
public void windowGainedFocus(WindowEvent evt) { refresh( ); }
public void windowLostFocus(WindowEvent evt) { refresh( ); }
/**
* @todo 用上面获取的图片更新背景
*
*/
public void refresh( ) {
if(frame.isVisible( )) {
repaint( );
refreshRequested = true;
lastupdate = new Date( ).getTime( );
}
}
public void run( ) {
try {
while(true) {
Thread.sleep(250);
long now = new Date( ).getTime( );
if(refreshRequested &&
((now - lastupdate) > 1000)) {
if(frame.isVisible( )) {
Point location = frame.getLocation( );
frame.setVisible(false );
updateBackground( );
frame.setVisible(true );
frame.setLocation(location);
refresh( );
}
lastupdate = now;
refreshRequested = false;
}
}
} catch (Exception ex) {
ex.printStackTrace( );
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -