package explorer;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
/**
* java浏览器雏形
* @author tiger
*/
@SuppressWarnings("serial")
public class TigerExplorer extends JFrame{
private JTextField field ;
private JEditorPane pane;
public TigerExplorer(String defaultUrl) {
field = new JTextField(defaultUrl, 40);
JToolBar bar = new JToolBar();
bar.add(new JLabel("Location:"));
bar.add(field);
pane = new JEditorPane();
pane.setEditable(false);
this.setTitle("tiger explorer");
Container contentpane = this.getContentPane();
contentpane.add(bar, BorderLayout.NORTH);
contentpane.add(new JScrollPane(pane), BorderLayout.CENTER);
this.setSize(600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
field.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e) {
openUrl(e.getActionCommand());
}
}
);
pane.addHyperlinkListener(new LinkActivator());
openUrl(defaultUrl);
}
private void openUrl(String urlString) {
if(urlString == null || urlString.trim().length() == 0)
{
return;
}
if(!urlString.startsWith("http://"))
{
urlString = "http://" + urlString;
}
try {
URL url = new URL(urlString);
pane.setPage(url);
field.setText(url.toExternalForm());
} catch (Exception e) {
System.out.println("Couldn't open " + urlString + " : " + e);
pane.setText("Couldn't open " + urlString + " : " + e);
}
}
class LinkActivator implements HyperlinkListener
{
public void hyperlinkUpdate(HyperlinkEvent e) {
if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
{
openUrl(e.getURL().toExternalForm());
}
}
}
public static void main(String[] args) {
String defaultUrl = "";
new TigerExplorer(defaultUrl).setVisible(true);
}
}