2011-12-01 68 views
20

Estoy usando JOptionPane para mostrar cierta información del producto y necesito agregar algunos enlaces a páginas web.enlaces clicables en JOptionPane

He descubierto que puede usar un JLabel que contenga html, así que he incluido un enlace <a href>. El enlace aparece azul y subrayado en el cuadro de diálogo, sin embargo, no se puede hacer clic.

Por ejemplo, esto también debería funcionar:

public static void main(String[] args) throws Throwable 
{ 
    JOptionPane.showMessageDialog(null, "<html><a href=\"http://google.com/\">a link</a></html>"); 
} 

¿Cómo consigo hacer clic en enlaces dentro de un JOptionPane?

Gracias, Paul.

EDITAR - por ejemplo, solución

public static void main(String[] args) throws Throwable 
{ 
    // for copying style 
    JLabel label = new JLabel(); 
    Font font = label.getFont(); 

    // create some css from the label's font 
    StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";"); 
    style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";"); 
    style.append("font-size:" + font.getSize() + "pt;"); 

    // html content 
    JEditorPane ep = new JEditorPane("text/html", "<html><body style=\"" + style + "\">" // 
      + "some text, and <a href=\"http://google.com/\">a link</a>" // 
      + "</body></html>"); 

    // handle link events 
    ep.addHyperlinkListener(new HyperlinkListener() 
    { 
     @Override 
     public void hyperlinkUpdate(HyperlinkEvent e) 
     { 
      if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) 
       ProcessHandler.launchUrl(e.getURL().toString()); // roll your own link launcher or use Desktop if J6+ 
     } 
    }); 
    ep.setEditable(false); 
    ep.setBackground(label.getBackground()); 

    // show 
    JOptionPane.showMessageDialog(null, ep); 
} 
+4

en la solución publicadas no puedo encontrar la clase ProcessHandler. ¿De dónde viene? – alexandre1985

Respuesta

15

Usted puede añadir cualquier componente a un JOptionPane.

Agregue un JEditorPane que muestre su HTML y admita un HyperlinkListener.

+1

sí, esta es de lejos la solución más fácil que he encontrado. no es difícil y publicaré mi solución, por ejemplo, en mi pregunta para otros. – pstanton

+0

aw maaaan! Lo publiqué como un comentario en la otra respuesta! –

5

Parece que fue discutido con bastante profundidad aquí How to add hyperlink in JLabel

+0

showmessagedialog toma un objeto, y si se trata de un control simplemente lo pondrá en el cuadro de diálogo, por lo que podría pasar el jlabel en lugar del texto mismo. o incluso podría usar un jeditorpane de solo lectura que tenga una gran cantidad de enlaces y contenido html en lugar de una sola etiqueta. –

3

La solución propuesta debajo de la respuesta no funciona con Nimbus Look and Feel. Nimbus anula el color de fondo y hace que el fondo sea blanco. La solución es establecer el color de fondo en el CSS. También debe quitar el borde del componente. Aquí es una clase que implementa una solución que funciona con Nimbus (no el registro otra & L F):

import java.awt.Color; 
import java.awt.Font; 

import javax.swing.JEditorPane; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.event.HyperlinkEvent; 
import javax.swing.event.HyperlinkListener; 

public class MessageWithLink extends JEditorPane { 
    private static final long serialVersionUID = 1L; 

    public MessageWithLink(String htmlBody) { 
     super("text/html", "<html><body style=\"" + getStyle() + "\">" + htmlBody + "</body></html>"); 
     addHyperlinkListener(new HyperlinkListener() { 
      @Override 
      public void hyperlinkUpdate(HyperlinkEvent e) { 
       if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) { 
        // Process the click event on the link (for example with java.awt.Desktop.getDesktop().browse()) 
        System.out.println(e.getURL()+" was clicked"); 
       } 
      } 
     }); 
     setEditable(false); 
     setBorder(null); 
    } 

    static StringBuffer getStyle() { 
     // for copying style 
     JLabel label = new JLabel(); 
     Font font = label.getFont(); 
     Color color = label.getBackground(); 

     // create some css from the label's font 
     StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";"); 
     style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";"); 
     style.append("font-size:" + font.getSize() + "pt;"); 
     style.append("background-color: rgb("+color.getRed()+","+color.getGreen()+","+color.getBlue()+");"); 
     return style; 
    } 
} 

Uso:

JOptionPane.showMessageDialog(null, new MessageWithLink("Here is a link on <a href=\"http://www.google.com\">http://www.google.com</a>")); 
Cuestiones relacionadas