要生成一個半透明的成形窗口
半透明窗口是大眾對Swing最為渴求的特性之一
仿造這樣一個的半透明窗口的過程
剛剛說到的部分只是小兒科
在開始我們的旅行之前
例
public class TransparentBackground extends Jcomponent {
private JFrame frame;
private Image background;
public TransparentBackground(JFrame frame) {
this
updateBackground( );
}
/**
* @todo 獲取屏幕快照後立即更新窗口背景
*/
public void updateBackground( ) {
try {
Robot rbt = new Robot( );
Toolkit tk = Toolkit
Dimension dim = tk
background = rbt
new Rectangle(
(int)dim
} catch (Exception ex) {
//p(ex
// 此方法沒有申明過
ex
}
}
public void paintComponent(Graphics g) {
Point pos = this
Point offset = new Point(
g
}
}
首先
我們可以通過下面這個main方法簡單的運行一下
public static void main(String[] args) {
JFrame frame = new JFrame(
TransparentBackground bg = new TransparentBackground(frame);
bg
JButton button = new JButton(
bg
JLabel label = new JLabel(
bg
frame
frame
frame
frame
}
通過這段代碼
圖
這段代碼相當簡單
誰也不想時不時地跑去更新screenshot
public class TransparentBackground extends JComponent
implements ComponentListener
Runnable {
private JFrame frame;
private Image background;
private long lastupdate =
public boolean refreshRequested = true;
public TransparentBackground(JFrame frame) {
this
updateBackground( );
frame
frame
new Thread(this)
}
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( ); }
首先
WindowFocusListener接口和Runnable接口
ComponentListener接口帶有四個component開頭的方法
public void refresh( ) {
if(frame
repaint( );
refreshRequested = true;
lastupdate = new Date( )
}
}
public void run( ) {
try {
while(true) {
Thread
long now = new Date( )
if(refreshRequested &&
((now
if(frame
Point location = frame
frame
updateBackground( );
frame
frame
refresh( );
}
lastupdate = now;
refreshRequested = false;
}
}
} catch (Exception ex) {
p(ex
ex
}
}
refresh()可以保證frame可見
除了每四分之一秒被喚醒一次
那麼我們為什麼要對用一個線程控制刷新如此長篇大論呢?一個詞
另外
另一件煩惱的事就是
接下來
public static void main(String[] args) {
JFrame frame = new JFrame(
frame
TransparentBackground bg = new TransparentBackground(frame);
bg
bg
JPanel panel = new JPanel( ) {
public void paintComponent(Graphics g) {
g
Image img = new ImageIcon(
g
}
};
panel
bg
frame
frame
frame
frame
frame
}
這段代碼通過繼承JPanel
圖
圖
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26738.html