在JEditorPane文件中最常用到事件处理的部份就是HTML文件,那是因为HTML文件本身具有超级链接的功能来做文章链接的用途 。大家还记得我们这一节的第一个范例吗?我们不是加载了一份HTML文件到JEditorPane中吗?虽然画面上都有确实的将超级链接和 图片信息展现出来,可是你有没有发现当你想要点选超级链接的地方时却没有反应呢?那是因为我们并没有在JEditorPane中加入事 件处理机制的缘故。我们改写JEditorPane1.java加入事件处理机制,使JEditorPane具有正常的超链接功能。如下范例:
import javax.swing.*; import javax.swing.event.*; import java.io.*; import java.awt.event.*; public class JEditorPane4{ public static void main(String[] args){ JEditorPane editPane = null; try{ File thef = new File ("docs/JEditorPane_1.html"); String str = thef.getAbsolutePath(); str = "file:"+str; editPane = new JEditorPane(); editPane.setPage(str); } catch(IOException ioe){ ioe.printStackTrace(System.err); System.exit(0); } editPane.setEditable(false); final JEditorPane thePane = editPane; //采用inner class的方式编写触发超级链接事件时的对应操作类 editPane.addHyperlinkListener(new HyperlinkListener(){ public void hyperlinkUpdate(HyperlinkEvent hle){//覆写hyperlinkUpdate()方法,当超级链接事件触发时会进入这 //个区段运行. try{ //判断是否为超级链接运行操作。若操作为真,则将新的HTML文件放到JEditorPane中, //操作为(thePane.setPage(hle.getURL());) if (hle.getEventType() == HyperlinkEvent.EventType.ACTIVATED) } catch(IOException ioe){ ioe.printStackTrace(System.err); } } }); JFrame f = new JFrame("JEditorPane4"); f.setContentPane(new JScrollPane(editPane)); f.setSize(200,250); f.show(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); }//end of main() }//end of class JEditPane1
另外,若是我们是在纯文字模式(Plain Text)或RTF模式(RTF Text)下需要事件处理模式又该怎么办呢?你还记得我们在 JTextArea中是如何加入事件处理模式的吗?没错!在JEditorPane中也是相同的做法,也就是利用DocumentListener interface的 机制来处理,由于做法相当类似,因此我们就不在这里重复的说明.