我正在尝试制作适用于任何组件的淡入淡出动画
我覆盖了绘制组件 alphacomposite,但看起来它完全没有任何作用。
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package JAnimator;
import java.awt.AlphaComposite;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.Timer;
public class JAnimator {
public static class fade_animation extends JComponent{
private float opacity;
private Timer timer;
private Component target;
private int speed=100;
private boolean isIn = true;
public fade_animation(Component targetComponent, int SpeedMilisec) {
this.target = targetComponent;
this.speed = SpeedMilisec;
timer = new Timer(speed, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(isIn){
opacity += 0.1f;
if(opacity>=1.0f){
opacity = 1.0f;
timer.stop();
}
target.repaint();
}else{
opacity -=0.1f;
if(opacity<=0.0f){
opacity = 0.0f;
timer.stop();
}
target.repaint();
}
}
});
}
public void playIn(){
opacity = 0.0f;
target.repaint();
isIn = true;
try{
timer.stop();
}catch(Exception e){
}
timer.start();
}
public void playOut(){
isIn = false;
opacity = 1.0f;
target.repaint();
try{
timer.stop();
}catch(Exception e){
}
timer.start();
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, this.opacity));
super.paint(g2d);
super.update(g);
}
}
}
在我的主程序中我试图这样称呼它
JAnimator.fade_animation ani1 = new JAnimator.fade_animation(JPanel1, 100);
ani1.playOut();
此面板由设计师 Netbeans 16 制作
我尝试了目标组件的重新验证和更新 ui 方法,但这根本没有效果
两种方式...
直接透明度设置:
// without "extends"
static class fade_animation {
int transparency = 0;
private Timer timer;
private Component target;
private int speed = 100;
private boolean isIn = true;
public fade_animation( Component targetComponent, int SpeedMilisec ) {
target = targetComponent;
speed = SpeedMilisec;
timer = new Timer( speed, new ActionListener() {
@Override
public void actionPerformed( ActionEvent e ) {
if( isIn ) {
transparency++;
if( transparency > 255 ) {
transparency = 255;
timer.stop();
}
// we change transparency
target.setBackground( new Color( 100, 100, 100, transparency ) );
target.repaint();
}
else {
transparency--;
if( transparency < 0 ) {
transparency = 0;
timer.stop();
}
// we change transparency
target.setBackground( new Color( 100, 100, 100, transparency ) );
target.repaint();
}
}
} );
}
public void playIn() {
target.repaint();
isIn = true;
timer.start();
}
public void playOut() {
isIn = false;
target.repaint();
timer.start();
}
}
通过 paintComponent() 覆盖设置透明度。