读书人

依照书上敲了个简单实现WebBrowser的代

发布时间: 2012-06-29 15:48:47 作者: rapoo

按照书上敲了个简单实现WebBrowser的代码,运行结果,网站总是在变化
代码如下

Java code
package ex30;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.net.URL;import javax.swing.event.*;import java.io.*;public class WebBrowser extends JApplet{    // JEditor pane to view HTML files    private JEditorPane jep = new JEditorPane();        // Label for URL    private JLabel jlblURL = new JLabel("URL");        // Text field for entering URL    private JTextField jtfURL = new JTextField();        /** Initialize the applet */    public void init(){        // Create a panel jpURL to hold the label and text field        JPanel jpURL = new JPanel();        jpURL.setLayout(new BorderLayout());        jpURL.add(jlblURL, BorderLayout.WEST);        jpURL.add(jtfURL, BorderLayout.CENTER);                // Place jpURL and jspViewer in the applet        add(new JScrollPane(jep), BorderLayout.CENTER);        add(jpURL, BorderLayout.NORTH);                // Set jep noneditable        jep.setEditable(false);                // Register listener        jep.addHyperlinkListener(new HyperlinkListener(){            public void hyperlinkUpdate(HyperlinkEvent e){                try{                    jep.setPage(e.getURL());                }                catch(IOException ex){                    System.out.println(ex);                }            }        });        jtfURL.addActionListener(new ActionListener(){            public void actionPerformed(ActionEvent e){                try{                    // Get the URL from text field                    URL url = new URL(jtfURL.getText().trim());                                        // Display the HTML file                    jep.setPage(url);                }                catch(IOException ex){                    System.out.println(ex);                }            }        });    }}

进入程序后,我输入http://www.hao123.com
开始的时候能显示hao123的界面出来,后面不一会儿就变化,好像一直在刷新,而且也不再是原来的网站
求高手解释一下这是为什么

[解决办法]
其实不是一直在刷新,是你的鼠标移动到了一个链接,这个事件被抓到后,执行了ActionPerformed方法。
HyperlinkEvent e
HyperlinkEvent有3中类型

static HyperlinkEvent.EventType ACTIVATED
激活类型。
static HyperlinkEvent.EventType ENTERED
进入类型。 (就是你鼠标移动到一个链接后的类型)
static HyperlinkEvent.EventType EXITED
退出类型。
在 jep.setPage(e.getURL());上加一条判断语句
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)

读书人网 >J2SE开发

热点推荐