Java Swing JEditorPane
2018-01-09 19:23 更新
Java Swing教程 - Java Swing JEditorPane
JEditorPane是一个文本组件,可以处理具有样式的不同文本。
默认情况下,它可以处理纯文本,HTML和RTF格式(RTF)。
JEditorPane主要用于显示仅包含基本HTML元素的HTML文档。
以下代码使用JEditorPane显示HTML页面。
JEditorPane htmlPane = new JEditorPane("http://www.www.w3cschool.cn");
JEditorPane预配置为了解三种类型的内容:
- text/plain
- text/html
- text/rtf
我们可以使用下面的代码显示文本Hello,使用< h1> 标签:
htmlPane.setContentType("text/html");
htmlPane.setText("<html><body><h1>Hello</h1></body></html>");
要处理RTF文件,请使用文件协议
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.w3cschool.cn");
}
}
以上内容是否对您有帮助:

免费 AI IDE


更多建议: