一。代码


package org.bruce.vertices.extra.experiments;

/* *
* 淡入淡出窗口,淡出时,如果鼠标移进去了,则中止渐变。
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;

public class GCFrame {
protected static Timer timer;
static JFrame jf;
static float value = 1.0f;
boolean isClicked = false;

public GCFrame() {
jf = new JFrame();
JPanel jp = new JPanel();
JButton jb = new JButton("淡出");
jp.add(jb);
jf.add(jp);
jf.setSize(320, 240);
jf.setVisible(true);
// 添加按钮的监听事件
timer = new Timer(100, new Tim1());
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.start();
isClicked = true;
// 当鼠标移入窗口时,中止线程,当点击了“淡出”按钮后添加事件监听代码
if (isClicked == true) {
jf.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
timer.stop();
value = 1.0f;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
com.sun.awt.AWTUtilities.setWindowOpacity(jf, value);
}
});
}

public void mouseExited(MouseEvent e) {
timer.start();
}
});
}
}
});
}

static class Tim0 implements ActionListener {// 控制窗口打开时透明度的渐变
public void actionPerformed(ActionEvent e) {
}
}

static class Tim1 implements ActionListener {// 控制窗口关闭时透明度的渐变
public void actionPerformed(ActionEvent e) {
value -= 0.02f;
if (value >= 0.02f) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
com.sun.awt.AWTUtilities.setWindowOpacity(jf, value);
}
});
} else {
System.exit(0);
}
}
}

public static void main(String[] args) {
new GCFrame();
}
}



二。效果图

Java实现淡入淡出窗口_java