超链接事件类型已激活错误

时间:2014-08-22 08:21:12

标签: java swing hyperlink jeditorpane

我正在尝试创建一个简单的网络浏览器但是当我运行它并将鼠标悬停在某个网址上时,即使我提供event.getEventType()==HyperlinkEvent.EventType.ACTIVATED,网址也会运行 为什么它的行为类似于event.getEventType()==HyperlinkEvent.EventType.ENTERED

这是完整的代码

package gui;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.*;
import java.awt.event.*;
public class WebBrowser extends JFrame{
private JTextField addressbar;
private JEditorPane display;
public WebBrowser(){
    super("Sagar Browser");
    addressbar = new JTextField("Enter a URL");
    addressbar.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event){
                    load(event.getActionCommand());                     
                }
            }           
            );
    add(addressbar,BorderLayout.NORTH); 
    display = new JEditorPane();
    display.setEditable(false);
    display.addHyperlinkListener(
            new HyperlinkListener(){
                public void hyperlinkUpdate(HyperlinkEvent event){
                    if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED);
                    load(event.getURL().toString());
                }
            }
            );
    add(new JScrollPane(display),BorderLayout.CENTER);      
  }
private void load(String usertext){
    try{
        display.setPage(usertext);
        addressbar.setText(usertext);
    }catch(Exception e){
        System.out.println("Enter Full URL");
    }
}
public static void main(String[] args){
    WebBrowser w = new WebBrowser();
    w.setSize(500,500);
    w.setVisible(true);
}
} 

1 个答案:

答案 0 :(得分:3)

您的侦听器会忽略相关谓词。你可能意味着这个:

new HyperlinkListener(){
    public void hyperlinkUpdate(HyperlinkEvent event){
        if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED) {
            load(event.getURL().toString());
        }
    }
}

检查相关示例herehere