W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
JEditorPane是一個文本組件,可以處理具有樣式的不同文本。
默認情況下,它可以處理純文本,HTML和RTF格式(RTF)。
JEditorPane主要用于顯示僅包含基本HTML元素的HTML文檔。
以下代碼使用JEditorPane顯示HTML頁面。
JEditorPane htmlPane = new JEditorPane("http://www.www.o2fo.com");
JEditorPane預配置為了解三種類型的內(nèi)容:
我們可以使用下面的代碼顯示文本Hello,使用< h1> 標簽:
htmlPane.setContentType("text/html"); htmlPane.setText("<html><body><h1>Hello</h1></body></html>");
要處理RTF文件,請使用文件協(xié)議
editorPane.setPage("file:///C:/test.rtf");
以下代碼顯示了如何處理JEditorPane中的超鏈接點擊事件。
import java.awt.BorderLayout; import java.awt.Container; import java.beans.PropertyChangeEvent; import java.io.IOException; import java.net.URL; /*w w w .j a v a 2s .com*/ import javax.swing.Box; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.event.HyperlinkEvent; public class Main extends JFrame { JEditorPane editorPane = new JEditorPane(); public Main(String title) { super(title); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = this.getContentPane(); Box editorPaneBox = this.getEditPaneBox(); contentPane.add(editorPaneBox, BorderLayout.CENTER); } private Box getEditPaneBox() { editorPane.setEditable(false); Box editorBox = Box.createHorizontalBox(); editorBox.add(new JScrollPane(editorPane)); editorPane.addHyperlinkListener((HyperlinkEvent event) -> { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { go(event.getURL()); } else if (event.getEventType() == HyperlinkEvent.EventType.ENTERED) { System.out.println("click this link"); } else if (event.getEventType() == HyperlinkEvent.EventType.EXITED) { System.out.println("Ready"); } }); editorPane.addPropertyChangeListener((PropertyChangeEvent e) -> { String propertyName = e.getPropertyName(); if (propertyName.equalsIgnoreCase("page")) { URL url = editorPane.getPage(); System.out.println(url.toExternalForm()); } }); return editorBox; } public void go(URL url) { try { editorPane.setPage(url); } catch (IOException e) { System.out.println(e.getMessage()); } } public void go(String urlString) { try { URL url = new URL(urlString); go(url); } catch (IOException e) { System.out.println(e.getMessage()); } } public static void main(String[] args) { Main browser = new Main(""); browser.setSize(700, 500); browser.setVisible(true); browser.go("http://www.www.o2fo.com"); } }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: