使用Java中JEditorPane的setPage方法,可以非常方便的将指定的URL对应的Web也显示出来,其支持的格式包括文本和图像。
将会用到的核心代码(API):
editorPane = new JEditorPane();
editorPane.setContentType("text/html; charset=iso-8859-1");
try {
editorPane.setPage(url);
} catch (IOException e) {
System.err.println("Attempted to read a bad URL: " + url);
}
可是我这么做以后,显示的网页和我们在浏览器中看到的有很大的不同,很多标签都显示出来了,根本就不是一个我们平时见到的网页。这是为什么呢 ?
怎么才能完美的显示网页呢? 麻烦指点!!!
将会用到的核心代码(API):
editorPane = new JEditorPane();
editorPane.setContentType("text/html; charset=iso-8859-1");
try {
editorPane.setPage(url);
} catch (IOException e) {
System.err.println("Attempted to read a bad URL: " + url);
}
可是我这么做以后,显示的网页和我们在浏览器中看到的有很大的不同,很多标签都显示出来了,根本就不是一个我们平时见到的网页。这是为什么呢 ?
怎么才能完美的显示网页呢? 麻烦指点!!!
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
public class JEditorPaneExample extends JFrame implements
HyperlinkListener
{
public static void main(String[] argv)
{
JEditorPaneExample mainApp = new JEditorPaneExample();
}
public JEditorPaneExample()
{
super("JEditorPaneExample Example");
setBounds(0, 0, 600, 400);
getContentPane().setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Attempt to load an 'index' html page...
try
{
URL url = null;
try
{
url = getClass().getResource("index.html");
}
catch(Exception e)
{
System.out.println("Could not open file!");
url = null;
}
if(url != null)
{
htmlViewer = new JEditorPane(url);
htmlViewer.setEditable(false);
htmlViewer.addHyperlinkListener(this);
scrollpane = new JScrollPane();
scrollpane.setBounds(10, 10, 570, 350);
scrollpane.getViewport().add(htmlViewer);
}
}
catch(MalformedURLException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
getContentPane().add(scrollpane);
setVisible(true);
}
public void hyperlinkUpdate(HyperlinkEvent e)
{
if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
{
if(e instanceof HTMLFrameHyperlinkEvent)
{
((HTMLDocument) htmlViewer.getDocument()).processHTML
FrameHyperlinkEvent((HTMLFrameHyperlinkEvent) e);
}
else
{
try
{
htmlViewer.setPage(e.getURL());
}
catch(IOException e2)
{
System.out.println(e2);
}
}
}
}
JEditorPane htmlViewer;
JScrollPane scrollpane;
}
JEditorPaneExample.java:71: not a statement
((HTMLDocument) htmlViewer.getDocument()).processHTML
^
D:\JEditorPaneExample.java:71: ';' expected
((HTMLDocument) htmlViewer.getDocument()).processHTML
^
2 errors