[求助]JFrame背景透明化后的问题
代码如下:问题:我已经将JFrame背景透明化了,但是打开以后总是遇到阁一段时间就刷新一次的问题,到最后还会一闪一闪的。
很麻烦,请问下有没有能够解决的。我想大概是线程等待的问题吧。
两个类为两个不同文件。先编译第二个类后编译第一个类,编译后直接运行第一个类
*************************************************************
第一个类
import java.awt.*;
import javax.swing.*;
public class Logon extends JFrame
{
Logon(String title)throws Exception
{
super(title);
JFrameTransparent backgroundTransparent = new JFrameTransparent(this);
backgroundTransparent.setLayout(new BorderLayout());
this.setResizable(false);
JTextArea jtf=new JTextArea("this is a text");
backgroundTransparent.add(jtf,BorderLayout.NORTH);
this.add(backgroundTransparent);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(332,245);
Dimension frameSize = this.getSize();
this.setLocation((screenSize.width-frameSize.width)/2,(screenSize.height-frameSize.height)/2);
this.setVisible(true);
}
public static void main(String args[])throws Exception
{
Logon AL=new Logon("hello");
}
}
*************************************************
第二类
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class JFrameTransparent extends JComponent implements ComponentListener, WindowFocusListener,Runnable
{
JFrame frame;
Image background;
long lastupdate=0;
boolean refreshRequested = true;
public JFrameTransparent(JFrame frame)throws Exception
{
this.frame = frame;
update();
frame.addComponentListener(this);
frame.addWindowFocusListener(this);
new Thread(this).start();
}
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(); }
public void update()throws Exception
{
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()));
//createScreenCapture用于创建包含从屏幕中读取的像素的图像
}
public void paintComponent(Graphics g)
{
Point pos=this.getLocationOnScreen();
Point offset=new Point(-pos.x,-pos.y);//表示 (x, y) 坐标空间中的位置的点,以整数精度来指定
g.drawImage(background,offset.x,offset.y,null);
}
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.hide();
update();
frame.show();
frame.setLocation(location);
refresh();
}
lastupdate = now;
refreshRequested = false;
}
}
}
catch(Exception ee){
}
}
public void refresh()
{
if(frame.isVisible())
{
repaint();
refreshRequested = true;
lastupdate = new Date().getTime();
}
}
}
[此贴子已经被作者于2007-10-9 2:16:37编辑过]