swing gui 打开url 连接的一个方法

来源:互联网 发布:微博域名怎么才正确 编辑:程序博客网 时间:2024/05/29 07:00

// coding

 StringBuffer html = new StringBuffer();
 private static final String LEGAL_INFORMATION = "Legal_Information";
  html.append("<html><head></head>");
  html.append("<body style='font-family: Pain; color:#383838; font-size: 8px; font-weight: normal;'>"); 
  html.append(" <a href="+LEGAL_INFORMATION+"> Legal<BR>");
  html.append("Information</a>. By use of this system, the user consents to the terms of this Notice.");
  html.append("</body></html>");

  JEditorPane last = new JEditorPane("text/html", html.toString());
  last.setBackground(this.getBackground());
  last.setEditable(false);
  last.setSelectionColor(this.getBackground());
  last.addHyperlinkListener(new HyperlinkListener() {
   public void hyperlinkUpdate(HyperlinkEvent e) {
    if(e.getEventType().equals(EventType.ENTERED)){
     setCursor(new Cursor(Cursor.HAND_CURSOR));
    }else{
     if(e.getEventType().equals(EventType.EXITED)){
      setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); 
     } 
    }

    if(e.getEventType().equals(EventType.ACTIVATED)){
     if (e.getDescription() != null) {
      if (LEGAL_INFORMATION.equals(e.getDescription())) {
       openURL("http://www.yourCompany.com/legal.html");
      }
     }
    }
   }
  });

 

 

//open url

 public static void openURL(String url) {
  String errMsg = "Error attempting to launch web browser";
     String osName = System.getProperty("os.name");
     try {
      if(osName.startsWith("Mac OS")) {
       Class fileMgr = Class.forName("com.apple.eio.FileManager");
             Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] {String.class});
             openURL.invoke(null, new Object[] { url });
          } else if(osName.startsWith("Windows")){
                 Runtime.getRuntime().exec((new StringBuilder()).append("rundll32 url.dll,FileProtocolHandler ").append(url).toString());
          } else {
                String browsers[] = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
                String browser = null;
                for(int count = 0; count < browsers.length && browser == null; count++)
                 if( Runtime.getRuntime().exec( new String[] { "which", browsers[count] }).waitFor() == 0)
                     browser = browsers[count];
             if(browser == null)
              throw new Exception("Could not find web browser");
             Runtime.getRuntime().exec(new String[] { browser, url});
          }
      }catch(Exception e){
       JOptionPane.showMessageDialog(null, (new StringBuilder()).append(errMsg).append(":/n").append(e.getLocalizedMessage()).toString());
      }
   }

原创粉丝点击