桌面應用常需右下角非侵入式提示。本範例利用 javax.swing.Timer(EDT 安全)每 100ms 遞增高度、同步更新位置,模擬「滑入」動畫;10 步後停止計時器,再延遲 1 秒自動關閉(範例邏輯)。核心類:MyDialog(無邊框視窗)、TimerAction(動畫邏輯)、Demo(啟動協調)。
Toolkit.getDefaultToolkit().getScreenSize() 取得解析度,視窗定位 (width-200, height-20-當前高度) 貼齊右下角任務列上方。JDialog 預設非模態,不阻塞主視窗;setDefaultCloseOperation(DISPOSE_ON_CLOSE) 僅銷毀自身。new Timer(0, actionListener) 0 延遲啟動,actionPerformed 中計算新尺寸/位置並 setSize/setLocation,Swing 自動重繪。class MyDialog extends JDialog {
private final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
public MyDialog() {
setUndecorated(true); // 無標題欄邊框
setLocation(screen.width - 200, screen.height - 20); // 初始最小化於右下角
setVisible(true);
}
}
class TimerAction implements ActionListener {
private MyDialog dialog; private int height = 0;
public void actionPerformed(ActionEvent e) {
dialog.setLocation(screen.width - 200, screen.height - 20 - height);
dialog.setSize(200, height);
}
}
// 啟動協調
MyDialog d = new MyDialog();
Timer timer = new Timer(100, new TimerAction(d)); // 100ms 間隔
timer.start();
for (int i=0; i<10; i++) { Thread.sleep(100); action.setHeight(50 + i*5); } // 主執行緒推進高度
timer.stop();
// 可再啟動一個 Timer 延遲關閉
Toast.show(message, duration, position) 靜態方法,內部複用單例對話框或對象池。JLabel + HTML `ConcurrentLinkedQueue 管理顯示序列。setOpacity(float) 配合 Timer 實現透明度動畫(需視窗支援透明度)。GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices() 判斷滑鼠所在螢幕。JavaFX 內建 PopupWindow、CSS 動畫、FXML 佈局,體驗更佳。Swing 專案可考慮 JXLayer 或 SwingX 庫的 JXToast。