2022년 2월 19일 토요일

Java Swing - Toast

 Java Swing - Toast

import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagLayout;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.RoundRectangle2D;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Toast {
    public static void main(String[] args) throws InterruptedException {
        ToastMessage toast = new ToastMessage("Toast Demo");
        toast.show();
        toast.showToMousePos();

        JFrame frame = new JFrame();
        frame.setSize(300, 300);
        frame.setLocation(600,600);
        frame.setVisible(true);
        toast.showToCenter(frame);
        
        toast.close();
    }
}

class ToastMessage {
    JFrame frame;
    public ToastMessage(final String message) {
        frame = new JFrame();
        frame.setUndecorated(true);
        frame.setLayout(new GridBagLayout());
        frame.setBackground(new Color(240,240,240,250));
        frame.setLocationRelativeTo(null);
        frame.setSize(300, 50);
        frame.add(new JLabel(message));
        frame.addComponentListener(new ComponentAdapter() {
           @Override
           public void componentResized(ComponentEvent e) {
              frame.setShape(new  RoundRectangle2D.Double(0,0,frame.getWidth(),frame.getHeight(), 20, 20));                      
           }
        });        
    }

    public void show() {
        try {
            frame.setOpacity(1);
            frame.setVisible(true);
            Thread.sleep(1000);
            for (double d = 1.0; d > 0.2; d -= 0.1) {
               Thread.sleep(100);
               frame.setOpacity((float)d);
            }
            frame.setVisible(false);
        }catch (Exception ignore) {
        }
    }
    
    public void show(int x, int y) {
        frame.setLocation(x, y);
        show();
    }
    
    public void showToMousePos() {
        Point p = MouseInfo.getPointerInfo().getLocation();
        show( p.x, p.y );
    }
    
    public synchronized void showToCenter(Component comp) {
        frame.setLocationRelativeTo(SwingUtilities.getRoot(comp));
        show();
    }
    
    public void close() {
        frame.dispose();
    }
}

댓글 없음:

댓글 쓰기