import java.awt.Font;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.*;

import java.sql.*;
import java.net.*;
import java.io.*;

public class DbaOdbAppl extends Applet
		 implements ActionListener {

   JLabel text, clicked;
   JButton button, clickButton;
   JTextField textField;
   private boolean _clickMeMode = true;
   private Connection c;
   final static private String _driver = "sun.jdbc.odbc.JdbcOdbcDriver";
   final static private String _user = "username";
   final static private String _pass = "password";
   final static private String _url = "jdbc:odbc:jdc";
   public void init(){
     text = new JLabel("Text to save to file:");
     clicked = new JLabel("Text retrieved from file:");
     button = new JButton("Click Me");
     button.addActionListener(this);
     clickButton = new JButton("Click Again");
     clickButton.addActionListener(this);
     textField = new JTextField(20);
     setLayout(new BorderLayout());
     setBackground(Color.white);
     add(BorderLayout.NORTH, text);
     add(BorderLayout.CENTER, textField);
     add(BorderLayout.SOUTH, button);
   }

   public void start(){ 
   } 

  public void stop(){
     System.out.println("Applet stopping.");
  }

  public void destroy(){
     System.out.println("Destroy method called.");
  }

  public void actionPerformed(ActionEvent event){
    try{
      Class.forName (_driver);
      c = DriverManager.getConnection(_url, _user, _pass);
     }catch (Exception e){
      e.printStackTrace();
      System.exit(1);
     }

     Object source = event.getSource();
     if(source == button){
       if(_clickMeMode){
         JTextArea displayText = new JTextArea();
         try{
     //Write to database
          String theText = textField.getText();
          Statement stmt = c.createStatement();
          String updateString = "INSERT INTO dba VALUES ('" + theText + "')";
          int count = stmt.executeUpdate(updateString);
    //Read from database
          ResultSet results = stmt.executeQuery("SELECT TEXT FROM dba "); 
          while(results.next()){
            String s = results.getString("TEXT");
            displayText.append(s + "\n");
          }
          stmt.close();
         }catch(java.sql.SQLException e){
         System.out.println("Cannot create SQL statement");
         System.exit(1);
         }

//Display text read from database
        text.setText("Text retrieved from file:");
        button.setText("Click Again");
        _clickMeMode = false;
//Display text read from database
      } else {
        text.setText("Text to save to file:");
        textField.setText("");
        button.setText("Click Me");
        _clickMeMode = true;
      }
    }
  }
}
