Haeri
Haeri

Reputation: 701

JPanel animation

Hy there. I am trying to make a JPanel which reacts to certain events and plays a little animation. For example if I click on a button, it should flash red.(I need this to indicate when a file was successfully saved(green flash), or a error occurred(red flash).

I found some tutorials on animations, but I'm having a hard time changing it to fit my needs. For example most of the tutorials instantiate a Timer at the beginning. But I only need the timer to be active for that short amount of time where the flash is played and than stop. Also I need different animation types.(red flash, green flash...)

This is what I have got so far, which is basically nothing:

package MainPackage;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.Timer;


public class StatusBar extends JPanel implements ActionListener{


Timer t = new Timer(10, this);
boolean stop = false;
Color color;

public void paintComponent (Graphics g) {
    super.paintComponent(g);

    setBackground(color);
}

public void confirm(){
    color = new Color(46, 204, 113);
    t.start();
}

public void warning(){
    color = Color.red;
    t.start();
}

@Override
public void actionPerformed(ActionEvent e) {
    repaint();
}
}

Thanks in advance!

Upvotes: 0

Views: 193

Answers (2)

Haeri
Haeri

Reputation: 701

So here is the finished class: New animations can be added easily. And they also do not interfere with each other. So multiple states can be triggered simultaneously.

The StatusBar.java

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JComponent;
import javax.swing.Timer;

public class StatusBar extends JComponent implements ActionListener{

int width;
int height;
boolean bLoad, bWarn, bConfirm, bError;
Timer timer;
Color bgColor;
int xPosLoad, alphaWarn, alphaConfirm, alphaError;
float cntWarn, cntConfirm, cntError;
int cntLoad;
final int barLength = 200;

public StatusBar(Color bg){     
    width = getWidth();
    height = getHeight();
    xPosLoad = -barLength; 
    alphaWarn = 0; 
    alphaConfirm = 0; 
    alphaError = 0;
    bgColor = bg;

    timer = new Timer(10, this);

    this.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent event) {
            width = getWidth();
            height = getHeight();
        }
    });
}

@Override
protected void paintComponent(Graphics g) {
    // Background
    g.setColor(bgColor);
    g.fillRect(0, 0, width, height);

    // loading
    Graphics2D g2d = (Graphics2D)g;
    GradientPaint gp = new GradientPaint(xPosLoad,0, new Color(0,0,0,0), xPosLoad+barLength, 0, new Color(200, 200, 255));
    g2d.setPaint(gp);
    g2d.fillRect(xPosLoad, 0, barLength, height);

    // Green
    g.setColor(new Color(20, 210, 60, alphaConfirm));
    g.fillRect(0, 0, width, height);

    // Yellow
    g.setColor(new Color(255, 223, 0, alphaWarn));
    g.fillRect(0, 0, width, height);

    // Red
    g.setColor(new Color(255, 0, 0, alphaError));
    g.fillRect(0, 0, width, height);

}

@Override
public void actionPerformed(ActionEvent e) {
    // step increase for all active components
    boolean toggle = false;
    if (bConfirm){
        if(cntConfirm < 1){
            cntConfirm += 0.01f;
            alphaConfirm = lerp(cntConfirm, 255, true);
        }else{ 
            bConfirm = false;
            cntConfirm = 0;
            alphaConfirm = 0;
        }
        toggle = true;
    }
    if (bWarn){
        if(cntWarn < 1){
            cntWarn += 0.01f;
            alphaWarn = lerp(cntWarn, 255, true);
        }else{
            bWarn = false;
            cntWarn = 0;
            alphaWarn = 0;
        }
        toggle = true;
    }
    if (bError){
        if(cntError < 1){
            cntError += 0.01f;
            alphaError = lerp(cntError, 255, true);
        }else{
            bError = false;
            cntError = 0;
            alphaError = 0;
        }
        toggle = true;
    }
    if (bLoad){
        if(cntLoad < 100){
            cntLoad += 1;
            xPosLoad = (cntLoad * (width + barLength)) / 100 - barLength;
        }else{ 
            cntLoad = 0;
            xPosLoad = -barLength;
        }
        toggle = true;
    }

    repaint();
    if (!toggle){
        timer.stop(); 
    }
}

private void startTimer(){
    if (!timer.isRunning()) 
        timer.start();
}

public void setBG(Color bg){
    bgColor = bg;
    System.out.println("Color: " + bgColor);
    repaint();
}


// Green flash
public void confirm(){
    // set values
    bConfirm = true;        
    alphaConfirm = 255;
    cntConfirm = 0;

    startTimer();
}

//Yellow flash
public void warning(){
    // restart values
    bWarn = true;       
    alphaWarn = 255;
    cntWarn = 0;

    startTimer();
}

//Red Flash
public  void error(){
    // restart values
    bError = true;
    alphaError = 255;
    cntError = 0;

    startTimer();
}

//Blue load
public  void loadStart(){
    // restart values
    bLoad = true;
    xPosLoad = -barLength;
    cntLoad = 0;

    startTimer();
}

public  void loadEnd(){
    bLoad = false;
    xPosLoad = -barLength;
}

private int lerp(float progress, int max, boolean inverse){
    float x = progress;

    float x2 = (float) Math.pow(x, 4);
    float g = x + (1 - x);
    float y = (float) ((float) x2 / (float)(Math.pow(g, 4)));

    y = Math.min(y, 1);
    y = Math.max(y, 0);

    int res = (int) (y * max);

    if (inverse){
        res = max - res;
    }
    return res;
}
}

And the Example.java

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Example extends JFrame{

public static void main(String[] args){
    new Example("Stat Example");
}

public Example(String title){
    super(title);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    StatusBar stat = new StatusBar(Color.black);
    stat.setPreferredSize(new Dimension(0, 10));

    JPanel panel = new JPanel();

    JButton bConfirm = new JButton("Confirm");
    JButton bWarn = new JButton("Warning");
    JButton bErr = new JButton("Error");
    JButton bLoadS = new JButton("Start Loading");
    JButton bLoadE = new JButton("End Loading");
    panel.add(bConfirm);
    panel.add(bWarn);
    panel.add(bErr);
    panel.add(bLoadS);
    panel.add(bLoadE);

    this.getContentPane().add(stat, BorderLayout.CENTER);
    this.getContentPane().add(panel, BorderLayout.SOUTH);

    this.pack();
    this.setVisible(true);

    // Listener

    bConfirm.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            stat.confirm();
        }
    });

    bWarn.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            stat.warning();
        }
    });

    bErr.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            stat.error();
        }
    });

    bLoadS.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            stat.loadStart();
        }
    });

    bLoadE.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            stat.loadEnd();
        }
    });

}
}

Upvotes: 0

bonney
bonney

Reputation: 465

public class flashclass extends JFrame{
    Thread th;
    Color defaultColor, flashColor;
    int i;
    boolean success;
    JPanel p;

    public flashclass(){
    setSize(200, 200);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    success = false;
    defaultColor = new Color(214,217,223);

    p = new JPanel();

    JButton rbtn = new JButton("Red flash");
    JButton gbtn = new JButton("Green flash");
    rbtn.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
    success = false;
    flash(success);
    }
    });
    gbtn.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
    success = true;
    flash(success);
    }
    });

    p.add(rbtn);
    p.add(gbtn);
    getContentPane().add(p);
    }

    public void flash(boolean success){
    i=0;

    if(!success){
    flashColor = Color.red;
    }
    else{
    flashColor = Color.green;
    }

    th = new Thread(new Runnable() {
    @Override
    public void run() {
    while(i<10){
    p.setBackground(flashColor);
    i++;
    try {
    Thread.sleep(10);
    } catch (InterruptedException ex) {
    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
    p.setBackground(defaultColor);
    }
    }
    });
    th.start();

    }
    }

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

Upvotes: 1

Related Questions