Check type for HyperlinkEvent in Java
Description
The following code shows how to check type for HyperlinkEvent.
Example
/* w w w. j a va 2s . com*/
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.net.IDN;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLFrameHyperlinkEvent;
public class Main extends JFrame implements HyperlinkListener {
private JTextField txtURL= new JTextField("");
JEditorPane ep = new JEditorPane();
private JLabel lblStatus= new JLabel(" ");
public Main() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel pnlURL = new JPanel();
pnlURL.setLayout(new BorderLayout());
pnlURL.add(new JLabel("URL: "), BorderLayout.WEST);
pnlURL.add(txtURL, BorderLayout.CENTER);
getContentPane().add(pnlURL, BorderLayout.NORTH);
getContentPane().add( ep, BorderLayout.CENTER);
getContentPane().add(lblStatus, BorderLayout.SOUTH);
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
String url = ae.getActionCommand().toLowerCase();
if (url.startsWith("http://"))
url = url.substring(7);
ep.setPage("http://" + IDN.toASCII(url));
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(Main.this, "Browser problem: " + e.getMessage());
}
}
};
txtURL.addActionListener(al);
setSize(300, 300);
setVisible(true);
}
public void hyperlinkUpdate(HyperlinkEvent he) {
HyperlinkEvent.EventType type = he.getEventType();
if (type == HyperlinkEvent.EventType.ENTERED) {
System.out.println(he.getURL().toString());
} else if (type == HyperlinkEvent.EventType.EXITED) {
System.out.println("Exited");
} else if (type == HyperlinkEvent.EventType.ACTIVATED) {
if (he instanceof HTMLFrameHyperlinkEvent) {
HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) he;
HTMLDocument doc = (HTMLDocument) ep.getDocument();
doc.processHTMLFrameHyperlinkEvent(evt);
} else {
try {
ep.setPage(he.getURL());
System.out.println(he.getURL().toString());
} catch (FileNotFoundException fnfe) {
ep.setText("Could not open file: <tt>" + he.getURL() + "</tt>.<hr>");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new Main();
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »