gpt4 book ai didi

java - 如何在 Swing 中创建通知

转载 作者:IT老高 更新时间:2023-10-28 20:50:02 27 4
gpt4 key购买 nike

使用 Java 和 Swing,是否有任何(方便的)方法来创建通知?通过通知,我的意思是:

this, this
(来源:maketecheasier.com)
,或者 this
(来源:microsoft.com)

(有更正确的说法吗?)。如果它可以跨平台工作会很好,但我主要关心的是它在带有 Gnome 的 Ubuntu 下工作。如果可能的话,我想避免在系统托盘/通知区域中有一个图标。

如果一切都失败了,我总是可以使用来自 Sliding Notification bar in java (a la Firefox) 的滑动通知

最佳答案

您可能需要 translucent frame没有装饰。

快速演示

OSX

enter image description here ]

您可以利用 JLabel 显示简单的 HTML

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.util.Date;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;


/**
* Simple demo on how a translucent window
* looks like when is used to display the system clock.
* @author <a href="http://stackoverflow.com/users/20654/oscarryz">Oscar Reyes</a>
*/
class Translucent extends JPanel implements ActionListener {

private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
private final Date now = new Date();
private final Timer timer = new Timer(1000, this);
private final JLabel text = new JLabel();

public Translucent() {
super(true);
timer.start();
}


@Override
public void actionPerformed(ActionEvent e) {
now.setTime(System.currentTimeMillis());
text.setText(String.format("<html><body><font size='50'>%s</font></body></html>",sdf.format(now)));
}

public static void main(String[] args) {

JFrame f = new JFrame();
f.setUndecorated(true);
setTranslucency(f);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(new Color(0f, 0f, 0f, 1f / 3f));
JPanel p = new Translucent();
JLabel l = new JLabel("Hola");
l.setFont(new Font(l.getFont().getName(), Font.PLAIN, 128));
p.add(l);
f.add(p);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
// taken from: http://java.sun.com/developer/technicalArticles/GUI/translucent_shaped_windows/
private static void setTranslucency( Window window){
try {
Class<?> awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
Method mSetWindowOpacity = awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
if (!mSetWindowOpacity.isAccessible()) {
mSetWindowOpacity.setAccessible(true);
}
mSetWindowOpacity.invoke(null, window, Float.valueOf(0.75f));
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
} catch (SecurityException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
}
}
}

关于java - 如何在 Swing 中创建通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3240415/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com