关于swing中嵌入html页面以及获取绝对路径

本文介绍如何在Java Swing应用程序中使用JEditorPane展示HTML页面,并详细展示了如何获取文件的绝对路径。通过实例代码,演示了设置页面内容、实现超链接监听以及处理点击事件的方法。
public class HTMLView extends JFrame implements HyperlinkListener{
public HTMLView() throws Exception  
   {  
  setLocation(600, 10);
  setSize(520, 845); 
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
      JEditorPane editorPane = new JEditorPane();  
        
      //放到滚动窗格中才能滚动查看所有内容  
      JScrollPane scrollPane = new JScrollPane(editorPane);  
      //设置是显示网页 html 文件,可选项  
      //editorPane.setContentType("text/html");  
      //设置成只读,如果是可编辑,你会看到显示的样子也是不一样的,true显示界面  
      editorPane.setEditable(false);  
      //要能响应网页中的链接,则必须加上超链监听器  
      editorPane.addHyperlinkListener(this);  
      
      File file = new File("html/detail.html");
      String filePath = file.getAbsolutePath();
      System.out.println(filePath);
      String path = "file:///"+filePath; 
      try  
      {  
         editorPane.setPage(path);  
      }  
      catch (IOException e)  
      {  
         System.out.println("读取页面 " + path + " 出错. " + e.getMessage());  
      }  
      Container container = getContentPane();  
        
      //让editorPane总是填满整个窗体  
      container.add(scrollPane, BorderLayout.CENTER);
      this.setVisible(true);
   }  
   //超链监听器,处理对超级链接的点击事件,但对按钮的点击还捕获不到  
   public void hyperlinkUpdate(HyperlinkEvent e)  
   {  
      if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)  
      {  
         JEditorPane pane = (JEditorPane) e.getSource();  
         if (e instanceof HTMLFrameHyperlinkEvent)  
         {  
            HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e;  
            HTMLDocument doc = (HTMLDocument) pane.getDocument();  
            doc.processHTMLFrameHyperlinkEvent(evt);  
         }  
         else  
         {  
            try  
            {  
               pane.setPage(e.getURL());  
            }  
            catch (Throwable t)  
            {  
               t.printStackTrace();  
            }  
         }  
      }  
   }  
public static void main(String[] args) throws Exception {
new HTMLView();



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值