import java.awt.Cursor; import java.awt.Desktop; import java.awt.FlowLayout; import java.awt.Desktop.Action; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.SwingUtilities; /** * @author Leyer */ public class _Main extends JDialog{ private static final long serialVersionUID = 1L; private JLabel label; public _Main(){ this.setTitle("Link on Jlabel"); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); this.setSize(200,100); this.setLayout(new FlowLayout(FlowLayout.CENTER)); label=new JLabel(""); addLinkToJLabel(label, "www.google.com"); add(label); } public void addLinkToJLabel(final JLabel label,final String url){ label.setText("<html><a href=>http//"+url+"</html>"); label.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) { label.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } @Override public void mouseEntered(MouseEvent arg0) { label.setCursor(new Cursor(Cursor.HAND_CURSOR)); } @Override public void mouseClicked(MouseEvent arg0) { try { if(Desktop.getDesktop().isSupported(Action.BROWSE)){ label.setCursor(new Cursor(Cursor.WAIT_CURSOR)); Desktop.getDesktop().browse(new URI(url)); label.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else System.err.println("Not supported!"); } catch (IOException e1) {e1.printStackTrace(); } catch (URISyntaxException e1) {System.err.println("URI Syntax error!"); } } }); } public static void main(String[] argv) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new _Main().setVisible(true); } }); } }
julio 19, 2011