If the applet uses files that are in a .jar file (jar stands for Java archive), you also need to add the ARCHIVE tag for the .jar file. Below is an example of including a databse driver using the ARCHIVE tag:
< html >
<body>
<applet code = "McKoiApplet.class" archive="mckoidb.jar" width = 800 height = 300>
</applet>
</body>
< /html >
Reminder: to compile and run the applet, type:
javac McKoiApplet.java
appletviewer McKoiApplet.html &
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class McKoiApplet extends JApplet implements Runnable {
JButton button;
JTextArea text;
McKoiApplet me;
public void init() {
//WindowUtilities.setNativeLookAndFeel();
Container content = getContentPane();
content.setBackground(Color.blue);
content.setLayout(new FlowLayout());
button = new JButton("Go");
content.add(button);
button.addActionListener(new ButtonListener());
text = new JTextArea(10, 60);
text.setLineWrap(true);
content.add(text);
me = this;
}
public void run() {
}
public void getResults() {
text.setText("");
try {
//System.out.println("I am here");
Class.forName("com.mckoi.JDBCDriver").newInstance();
}
catch (Exception e) {
System.out.println(
"Unable to register the JDBC Driver.\n" +
"Make sure the JDBC driver is in the\n" +
"classpath.\n");
}
// This URL specifies we are connecting with a database server
// on localhost.
String url = "jdbc:mckoi://birch/";
// The username / password to connect under.
String username = "cs349";
String password = "cs349";
// Make a connection with the database.
Connection con;
try {
con = DriverManager.getConnection(url, username, password);
}
catch (SQLException e) {
System.out.println(
"Unable to make a connection to the database.\n" +
"The reason: " + e.getMessage());
return;
}
try {
Statement stmt = con.createStatement();
// using executeQuery():
ResultSet rs = stmt.executeQuery(
"SELECT * FROM Students ");
// moving forward in the result set:
while (rs.next()) {
int id = rs.getInt("ID");
String first = rs.getString("First_Name");
String last = rs.getString("Last_Name");
String year = rs.getString("Year");
float gpa = rs.getFloat("GPA");
Date date = rs.getDate("Date_of_birth");
text.append(id + " " + first + " " + last + " ");
text.append(year + " " + gpa + " " + date + "\n");
}
// Close the connection when finished
con.close();
}
catch (SQLException e) {
System.out.println(
"An error occured\n" +
"The SQLException message is: " + e.getMessage());
return;
}
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
me.getResults();
}
}
}
Things to notice:
me to be able to invoke the method
on the applet inside the ActionPerformed() method of the
ButtonListener.