1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class FadingChart extends JWindow implements ActionListener {
float alpha = 1.0f; // current opacity of button
Timer timer; // for later start/stop actions
int animationDuration = 10000; // each animation will take 2 seconds
long animationStartTime; // start time for each animation
BufferedImage charImage = null;
JPanel chart;
public FadingChart() {
super();
timer = new Timer(100, this);
chart = new JPanel();
chart.setBackground(Color.red);
this.getContentPane().add(chart);
this.setLocation(100, 100);
}
public void go() {
if (!timer.isRunning()) {
animationStartTime = System.nanoTime() / 1000000;
// this.setText("Stop Animation");
timer.start();
}
}
public void paint(Graphics g) {
// Create an image for the button graphics if necessary
if (charImage == null || charImage.getWidth() != getWidth()
|| charImage.getHeight() != getHeight()) {
charImage = getGraphicsConfiguration().createCompatibleImage(
getWidth(), getHeight());
System.out.println("create once");
}
Graphics gch = chart.getGraphics();
Graphics gButton = charImage.getGraphics();
gButton.setClip(gch.getClip());
// Have the superclass render the button for us
// super.paint(gButton);
super.paint(gButton);
// Make the graphics object sent to this paint() method translucent
System.out.println("alpha" + (1 - alpha));
Graphics2D g2d = (Graphics2D) g;
g2d.setComposite(AlphaComposite.SrcOver.derive(1 - alpha));
g2d.drawImage(charImage, 0, 0, null);
}
public void actionPerformed(ActionEvent ae) {
// timer event
// calculate the elapsed fraction
long currentTime = System.nanoTime() / 1000000;
long totalTime = currentTime - animationStartTime;
if (totalTime > animationDuration) {
animationStartTime = currentTime;
}
float fraction = (float) totalTime / animationDuration;
fraction = Math.min(1.0f, fraction);
// This calculation will cause alpha to go from 1 to 0 and back to 1
// as the fraction goes from 0 to 1
alpha = Math.abs(1 - (2 * fraction));
repaint();
}
private static void createAndShowGUI() {
FadingChart fc = new FadingChart();
fc.setSize(200, 200);
fc.setVisible(true);
fc.go();
}
public static void main(String args[]) {
Runnable doCreateAndShowGUI = new Runnable() {
public void run() {
createAndShowGUI();
}
};
SwingUtilities.invokeLater(doCreateAndShowGUI);
}
} |
Partager