All Downloads are FREE. Search and download functionalities are using the official Maven repository.

convex.gui.components.Toast Maven / Gradle / Ivy

There is a newer version: 0.7.15
Show newest version
package convex.gui.components;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.RoundRectangle2D;

import javax.swing.JComponent;
import javax.swing.JTextArea;
import javax.swing.JWindow;

/**
 * A simple class for implementing a "Toast" style notification.
 */
@SuppressWarnings("serial")
public class Toast extends JWindow {

	public static final Color SUCCESS = new Color(100,150,0);
	public static final Color FAIL = new Color(150,50,50);
	public static final Color INFO = new Color(50,100,150);

	public Toast(JComponent parent, JComponent component, Color color) {
		super();
		this.setLayout(new BorderLayout());
		this.setBackground(color);
		this.getContentPane().setBackground(color);
		add(component);
		
		Point pp=parent.getLocationOnScreen();
		
		int px=(int) pp.getX();
		int py=(int) pp.getY();
		int pw=parent.getWidth();
		int ph=parent.getHeight();
		int h=50;
		this.setLocation(px, py+ph-h);
		setSize(pw,h);
		
		addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				setShape(new RoundRectangle2D.Float(0, 0,getWidth(), getHeight(), 16, 16));
			}
		});
	}
	
	@Override
	public void paint(Graphics g) {
		super.paint(g);
	}

	private void doDisplay(final long millis) {
		setVisible(true);
		long start=System.currentTimeMillis();
		new Thread(()->{
			try {
				long time=start;
				while (time<(start+millis)) {
					Thread.sleep(100);
					time=System.currentTimeMillis();
					// drop opacity after 50% of time has elapsed
					double opac=Math.min(1.0,Math.max(0.0,(2*(1.0-(time-start)/(double)millis))));
					setOpacity((float)opac) ;
				}
			} catch (InterruptedException e) {
				// set interrupted flag, clear toast and return
				setOpacity(0.0f);
				Thread.currentThread().interrupt();
			} finally  {
				setVisible(false);
			}
		}).start();;
	}
	
	public static void display(JComponent parent, JComponent component, Color colour) {
		Toast toast=new Toast(parent,component,colour);
		toast.doDisplay(2000);
	}
	
	public static void display(JComponent parent, JComponent component) {
		display(parent,component,SUCCESS);
	}

	public static void display(JComponent parent, String message, Color colour) {
		JTextArea ta=new JTextArea(message);
		ta.setBackground(null);
		ta.setEditable(false);
		display(parent,ta,colour);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy