我想为JPanel设置一个动画渐变背景。效果起作用,但我希望在重新开始时顺利过渡。以下是我目前的实施。当xvalue2达到极限集时,我交换颜色并重新开始。平滑渐变背景动画java
public class GradientAnimation {
static class GradientPanel extends JPanel {
private static final long serialVersionUID = -4185583782901846967L;
private Timer timer;
private float Xend;
private final float MAXVALUE = 800f;
private Color color1 = new Color(128,62,153,255);
private Color color2 = new Color(192,201,200,255);
GradientPanel() {
Xend = 0f;
setOpaque(true);
ActionListener action = new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
if (Xend < MAXVALUE) Xend+=2f;
else{
Color aux = color1;
color1 = color2;
color2 = aux;
Xend = 0f;
}
revalidate();
repaint();
}
};
timer = new Timer(5, action);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
final BufferedImage image = new BufferedImage(
getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
g2d = image.createGraphics();
GradientPaint prim = new GradientPaint(0f, 0f, color1,
Xend, 0f, color2);
g2d.setPaint(prim);
g2d.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(image, 0, 0, null);
}
}
private static void createAndShowUI() {
try {
JFrame frame = new JFrame("Gradient Animation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
GradientPanel imagePanel = new GradientPanel();
frame.add(imagePanel);
frame.setSize(400, 400);
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
再一次,我想隐藏一段时间,我交换颜色有一个完美的梯度动画循环。如果代码看起来正确,请告诉我,我如何提高质量。
请不要为填料张贴废话作为击败限制的目的,而不是玩公平与我们的志愿者谁还会帮你。相反,请告诉你的问题的细节,代码的作用,它应该做什么。 –
是的,我明白了。但是与代码相比,我的解释太短了,我想发布一个工作代码而不是代码片段,因此可以对其进行测试。抱歉。 –
因此,添加更多的解释,而不是废话。帮助我们理解你写的代码,描述它。再一次,你的帮助我们只会帮助你。 –