This tip shows you how to have a search box on your site. You can select from three different search engines. Since this is a Java applet you need a HTML file in order to use this code. That file is included at the end of this tip.
==========================================
import java.applet.Applet;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class Search extends Applet implements ActionListener {
TextField searchParameter;
Choice searchEngine;
Button searchButton;
// initialize the display
public void init() {
setBackground(Color.white);
searchParameter = new TextField(20);
add(searchParameter);
searchEngine = new Choice();
searchEngine.addItem("Google");
searchEngine.addItem("Yahoo");
searchEngine.addItem("AltaVista");
searchEngine.select(0);
add(searchEngine);
searchButton = new Button("Search");
searchButton.addActionListener(this);
add(searchButton);
}
public void actionPerformed(ActionEvent event){
if (event.getSource().equals(searchButton)) {
try {
sendSearch();
}
catch (Exception e1) {
showStatus("Exception caught:" + e1.toString());
}
}
}
public void sendSearch() throws Exception {
String searchString = searchParameter.getText();
if (searchString.equals("")) {
showStatus("Must enter a search string");
return;
}
String url;
switch (searchEngine.getSelectedIndex()) {
case 0: url = "http://www.google.com/search?q=";
break;
case 1: url = "http://search.yahoo.com/bin/search?p=";
break;
case 2: url = "http://www.altavista.com/sites/search/web?q=";
break;
default: showStatus("Invalid search engine selected.");
return;
}
// encode the search data
url += URLEncoder.encode(searchString);
// launch the search engine
showStatus("Connecting to search location " + url);
getAppletContext().showDocument(new URL(url), "_top");
}
}
=============== HTML File ===============
< HTML>
< TITLE>< /TITLE>
< BODY>
< APPLET CODE="Search.class">
< /APPLET>
<
/BODY>< /HTML>