2010-07-13 31 views
17

Usando Java y Swing, ¿hay alguna forma (conveniente) de crear una notificación? Mediante notificación, quiero decir algo como:Cómo crear una notificación en swing

this http://productivelinux.com/images/notify-osd-screenshot.png, this http://images.maketecheasier.com/2010/01/kfirefox-notify-indexed.png, o this

(¿Existe un término más correcto para eso?). Sería bueno si funcionara multiplataforma, pero principalmente me preocupa que funcione bajo Ubuntu con Gnome. Si es posible, me gustaría evitar tener un icono en la bandeja del sistema/área de notificación.

Si todo lo demás falla, siempre podía usar la notificación de deslizamiento Sliding Notification bar in java (a la Firefox)

+0

¿Cómo hacer lo mismo usando Libgdx? –

Respuesta

26

Es posible que necesite un translucent frame sin decoraciones.

demostración rápida

OSX

enter image description here]

Puede aprovechar JLabel muestra HTML simple

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(); 
      } 
    } 
} 
+0

Esa es la mejor apariencia que he visto hasta ahora, así que ' Iremos con él (-: Es una lástima que no haya (hasta donde yo sé) una forma de utilizar las notificaciones nativas de swing. – Jeremy

+3

Java ahora lo admite de forma nativa. http://docs.oracle.com/ javase/tutorial/uiswing/misc/trans_shaped_windows.html – kazanaki

+0

Gran respuesta. Lo más importante, funciona en todas las plataformas. – kazy

14

Una forma estándar de hacerlo es utilizar Swing TrayIcon API. Esa sería probablemente la forma más conveniente también :)

+1

Supongo que displayMessage generará el estilo que se muestra en la tercera captura de pantalla. En Windows, de todos modos. – Powerlord

+0

En mi sistema, eso termina luciendo así: http://i.imgur.com/tfTkv.png (Esperaba algo más parecido a la notificación de gnome nativo) – Jeremy

+1

Es posible crear una ventana de notificación personalizada, pero sería menos "conveniente". Básicamente se trata de crear una ventana con FocusListener para que la ventana se cierre cuando pierde el foco. Obviamente, podrás hacer tus propios jadeos. Para efectos de animación, sugeriría la biblioteca Trident encontrada en http://kenai.com/projects/trident/pages/Home –

4

No he usado esto, pero JToaster parece que podría ser una buena combinación. Además, ¿está abierto a usar SWT? Esto podría darle algunas opciones adicionales (here's an example).

+0

Buen punto. Probablemente debería dejar de usar Swing. – Jeremy

+0

@Jeremy, probablemente solo necesites trabajar más con swing, es muy poderoso (cuando llegues a saberlo, lo que por cierto, puede llevar un tiempo) – OscarRyz

Cuestiones relacionadas