Selasa, 27 November 2018

PBO-A Database Kuliah

pada kesempatan kali ini saya mendapat tugas membuat database kuliah
Berikut adalah source codenya:
1. Dosen
 public class dosen extends objek  
 {  
   private int gaji;  
   private String jabatan;  
   public dosen (String name, int kode, int Gaji, String Jabatan)  
   {  
     super(name, kode);  
     gaji = Gaji;  
     jabatan = Jabatan;  
   }  
   public int getgaji()  
   {  
     return gaji;  
   }  
   public String getjabatan()  
   {  
     return jabatan;  
   }  
   public void print(){  
     System.out.println("Nama  : "+this.getnama());  
     System.out.println("Kode  : "+this.getid());  
     System.out.println("Gaji  : "+this.getgaji());  
     System.out.println("Jabatan : "+this.getjabatan());  
   }  
 }  

2. Database
 import java.util.ArrayList;  
 public class database  
 {  
   private ArrayList<pegawai> pgw;  
   private ArrayList<dosen> dsn;  
   private ArrayList<mahasiswa> mhs;  
   private ArrayList<kelas> kls;  
   private ArrayList<matkul> mk;  
   private ArrayList<buku> buku;  
   public database(){  
     pgw= new ArrayList<pegawai>();  
     dsn= new ArrayList<dosen>();  
     mhs= new ArrayList<mahasiswa>();  
     kls= new ArrayList<kelas>();  
     mk= new ArrayList<matkul>();  
     buku= new ArrayList<buku>();  
   }  
   public void addpgw (pegawai the_pgw){  
     pgw.add(the_pgw);  
   }  
   public void adddsn (dosen the_dsn){  
     dsn.add(the_dsn);  
   }  
   public void addmhs (mahasiswa the_mhs){  
     mhs.add(the_mhs);  
   }  
   public void addkls (kelas the_kls){  
     kls.add(the_kls);  
   }  
   public void addmk (matkul the_mk){  
     mk.add(the_mk);  
   }  
   public void addbuku (buku the_buku){  
     buku.add(the_buku);  
   }  
   public void list(int id){  
     int no = 1;  
     switch(id){  
     case 1:  
     for(pegawai cd: pgw){  
       System.out.println(no++);  
       for(pegawai iterasi : pgw){  
         iterasi.print();  
       }  
     }  
     break;  
     case 2:  
     for(dosen cd: dsn){  
       System.out.println(no++);  
       for(dosen iterasi : dsn){  
         iterasi.print();  
       }  
     }  
     break;  
     case 3:  
     for(mahasiswa cd: mhs){  
       System.out.println(no++);  
       for(mahasiswa iterasi : mhs){  
         iterasi.print();  
       }  
     }  
     break;  
     case 4:  
     for(matkul cd: mk){  
       System.out.println(no++);  
       for(matkul iterasi : mk){  
         iterasi.print();  
       }  
     }  
     break;  
     case 5:  
     for(kelas cd: kls){  
       System.out.println(no++);  
       for(kelas iterasi : kls){  
         iterasi.print();  
       }  
     }  
     break;  
     case 6:  
     for(buku cd: buku){  
       System.out.println(no++);  
     }  
     break;  
   }  
   }  
 }  

3. Buku
 public class buku extends objek  
 {  
   private String pengarang;  
   private int halaman;  
   public buku (String name, int kode, String Pengarang, int Halaman)  
   {  
     super(name, kode);  
     pengarang = Pengarang;  
   }  
   public String get_pengarang()  
   {  
     return pengarang;  
   }  
   public int get_halaman()  
   {  
     return halaman;  
   }  
   public void print(){  
     System.out.println("Nama    : "+this.getnama());  
     System.out.println("Kode    : "+this.getid());  
     System.out.println("Pengarang  : "+this.get_pengarang());  
     System.out.println("Halaman   : "+this.get_halaman());  
   }  
 }  

4. Objek
 public class objek  
 {  
   private String nama;  
   private int id;  
   public objek(String name,int kode)  
   {  
     nama = name;  
     id = kode;  
   }  
   public String getnama(){  
     return nama;  
   }  
   public int getid(){  
     return id;  
   }  
 }  

5. Kelas
 public class kelas extends objek  
 {  
   private String ruangan;  
   public kelas (String name, int kode, String Ruangan)  
   {  
     super(name, kode);  
     ruangan = Ruangan;  
   }  
   public String get_ruangan()  
   {  
     return ruangan;  
   }  
   public void print(){  
     System.out.println("Nama  : "+this.getnama());  
     System.out.println("Kode  : "+this.getid());  
     System.out.println("Ruangan : "+this.get_ruangan());  
   }  
 }  

6. Mahasiswa
 public class mahasiswa extends objek  
 {  
   private String degree;  
   private String address;  
   public mahasiswa (String name, int kode, String derajat, String alamat)  
   {  
     super (name, kode);  
     degree = derajat;  
     address = alamat;  
   }  
   public String get_degree()  
   {  
     return degree;  
   }  
   public String get_address()  
   {  
     return address;  
   }  
   public void print(){  
     System.out.println("Nama  : "+this.getnama());  
     System.out.println("Kode  : "+this.getid());  
     System.out.println("Derajat : "+this.get_degree());  
     System.out.println("Alamat : "+this.get_address());  
   }  
 }  

7. Matkul
 public class matkul extends objek  
 {  
   private String dosen;  
   public matkul(String name, int kode, String Dosen)  
   {  
     super(name, kode);  
     dosen = Dosen;  
   }  
   public String get_dosen()  
   {  
     return dosen;  
   }  
   public void print(){  
     System.out.println("Nama    : "+this.getnama());  
     System.out.println("Kode    : "+this.getid());  
     System.out.println("Dosen    : "+this.get_dosen());  
   }  
 }  

8. Pegawai
 public class pegawai extends objek  
 {  
   private String bagian;  
   public pegawai (String name, int kode, String Bagian)  
   {  
     super(name, kode);  
     bagian = Bagian;  
   }  
   public String get_bagian()  
   {  
     return bagian;  
   }  
   public void print(){  
     System.out.println("Nama    : "+this.getnama());  
     System.out.println("Kode    : "+this.getid());  
     System.out.println("Bagian   : "+this.get_bagian());  
   }  
 }  

berikut saya lampirkan pula hasilnya:

PBO-A Fox and Rabbit

Pada kesempatan kali ini saya diberikann tuga membuat program simulasi fox and rabbit

Berikut source codenya :
1. Fox
 import java.util.List;   
  import java.util.Iterator;   
  import java.util.Random;   
  public class Fox   
  {    
   private static final int BREEDING_AGE = 10;   
   private static final int MAX_AGE = 150;   
   private static final double BREEDING_PROBABILITY = 0.35;   
   private static final int MAX_LITTER_SIZE = 5;    
   private static final int RABBIT_FOOD_VALUE = 7;   
   private static final Random rand = Randomizer.getRandom();  
   private int age;   
   private boolean alive;   
   private Location location;   
   private Field field;   
   private int foodLevel;   
   public Fox(boolean randomAge, Field field, Location location)   
   {   
    age = 0;   
    alive = true;   
    this.field = field;   
    setLocation(location);   
    if(randomAge) {   
     age = rand.nextInt(MAX_AGE);   
     foodLevel = rand.nextInt(RABBIT_FOOD_VALUE);   
    }   
    else {   
     foodLevel = RABBIT_FOOD_VALUE;   
    }   
   }   
   public void hunt(List<Fox> newFoxes)   
   {   
    incrementAge();   
    incrementHunger();   
    if(alive) {   
     giveBirth(newFoxes);       
     Location newLocation = findFood(location);   
     if(newLocation == null) {     
      newLocation = field.freeAdjacentLocation(location);   
     }   
     if(newLocation != null) {   
      setLocation(newLocation);   
     }   
     else {   
      setDead();   
     }   
    }   
   }   
   public boolean isAlive()   
   {   
    return alive;   
   }   
   public Location getLocation()   
   {   
    return location;   
   }   
   private void setLocation(Location newLocation)   
   {   
    if(location != null) {   
     field.clear(location);   
    }   
    location = newLocation;   
    field.place(this, newLocation);   
   }   
   private void incrementAge()   
   {   
    age++;   
    if(age > MAX_AGE) {   
     setDead();   
    }   
   }   
   private void incrementHunger()   
   {   
    foodLevel--;   
    if(foodLevel <= 0) {   
     setDead();   
    }   
   }   
   private Location findFood(Location location)   
   {   
    List<Location> adjacent = field.adjacentLocations(location);   
    Iterator<Location> it = adjacent.iterator();   
    while(it.hasNext()) {   
     Location where = it.next();   
     Object animal = field.getObjectAt(where);   
     if(animal instanceof Rabbit) {   
      Rabbit rabbit = (Rabbit) animal;   
      if(rabbit.isAlive()) {    
       rabbit.setDead();   
       foodLevel = RABBIT_FOOD_VALUE;    
       return where;   
      }   
     }   
    }   
    return null;   
   }   
   private void giveBirth(List<Fox> newFoxes)   
   {   
    List<Location> free = field.getFreeAdjacentLocations(location);   
    int births = breed();   
    for(int b = 0; b < births && free.size() > 0; b++) {   
     Location loc = free.remove(0);   
     Fox young = new Fox(false, field, loc);   
     newFoxes.add(young);   
    }   
   }   
   private int breed()   
   {   
    int births = 0;   
    if(canBreed() && rand.nextDouble() <= BREEDING_PROBABILITY) {   
     births = rand.nextInt(MAX_LITTER_SIZE) + 1;   
    }   
    return births;   
   }   
   private boolean canBreed()   
   {   
    return age >= BREEDING_AGE;   
   }   
   private void setDead()   
   {   
    alive = false;   
    if(location != null) {   
     field.clear(location);   
     location = null;   
     field = null;   
    }   
   }   
  }   

2.Rabbit
 import java.util.List;   
  import java.util.Random;   
  public class Rabbit   
  {    
   private static final int BREEDING_AGE = 5;   
   private static final int MAX_AGE = 40;   
   private static final double BREEDING_PROBABILITY = 0.15;   
   private static final int MAX_LITTER_SIZE = 4;    
   private static final Random rand = Randomizer.getRandom();   
   private int age;   
   private boolean alive;   
   private Location location;   
   private Field field;   
   public Rabbit(boolean randomAge, Field field, Location location)   
   {   
    age = 0;   
    alive = true;   
    this.field = field;   
    setLocation(location);   
    if(randomAge) {   
     age = rand.nextInt(MAX_AGE);   
    }   
   }   
   public void run(List<Rabbit> newRabbits)   
   {   
    incrementAge();   
    if(alive) {   
     giveBirth(newRabbits);       
     Location newLocation = field.freeAdjacentLocation(location);   
     if(newLocation != null) {   
      setLocation(newLocation);   
     }   
     else {   
      setDead();   
     }   
    }   
   }   
   public boolean isAlive()   
   {   
    return alive;   
   }   
   public void setDead()   
   {   
    alive = false;   
    if(location != null) {   
     field.clear(location);   
     location = null;   
     field = null;   
    }   
   }   
   public Location getLocation()   
   {   
    return location;   
   }   
   private void setLocation(Location newLocation)   
   {   
    if(location != null) {   
     field.clear(location);   
    }   
    location = newLocation;   
    field.place(this, newLocation);   
   }   
   private void incrementAge()   
   {   
    age++;   
    if(age > MAX_AGE) {   
     setDead();   
    }   
   }   
   private void giveBirth(List<Rabbit> newRabbits)   
   {   
    List<Location> free = field.getFreeAdjacentLocations(location);   
    int births = breed();   
    for(int b = 0; b < births && free.size() > 0; b++) {   
     Location loc = free.remove(0);   
     Rabbit young = new Rabbit(false, field, loc);   
     newRabbits.add(young);   
    }   
   }   
   private int breed()   
   {   
    int births = 0;   
    if(canBreed() && rand.nextDouble() <= BREEDING_PROBABILITY) {   
     births = rand.nextInt(MAX_LITTER_SIZE) + 1;   
    }   
    return births;   
   }   
   private boolean canBreed()   
   {   
    return age >= BREEDING_AGE;   
   }   
  }   

3. Fieldstat
 import java.awt.Color;   
  import java.util.HashMap;   
  public class FieldStats   
  {    
   private HashMap<Class, Counter> counters;   
   private boolean countsValid;   
   public FieldStats()   
   {   
    counters = new HashMap<Class, Counter>();   
    countsValid = true;   
   }   
   public String getPopulationDetails(Field field)   
   {   
    StringBuffer buffer = new StringBuffer();   
    if(!countsValid) {   
     generateCounts(field);   
    }   
    for(Class key : counters.keySet()) {   
     Counter info = counters.get(key);   
     buffer.append(info.getName());   
     buffer.append(": ");   
     buffer.append(info.getCount());   
     buffer.append(' ');   
    }   
    return buffer.toString();   
   }   
   public void reset()   
   {   
    countsValid = false;   
    for(Class key : counters.keySet()) {   
     Counter count = counters.get(key);   
     count.reset();   
    }   
   }   
   public void incrementCount(Class animalClass)   
   {   
    Counter count = counters.get(animalClass);   
    if(count == null) {    
     count = new Counter(animalClass.getName());   
     counters.put(animalClass, count);   
    }   
    count.increment();   
   }   
   public void countFinished()   
   {   
    countsValid = true;   
   }   
   public boolean isViable(Field field)   
   {   
    int nonZero = 0;   
    if(!countsValid) {   
     generateCounts(field);   
    }   
    for(Class key : counters.keySet()) {   
     Counter info = counters.get(key);   
     if(info.getCount() > 0) {   
      nonZero++;   
     }   
    }   
    return nonZero > 1;   
   }   
   private void generateCounts(Field field)   
   {   
    reset();   
    for(int row = 0; row < field.getDepth(); row++) {   
     for(int col = 0; col < field.getWidth(); col++) {   
      Object animal = field.getObjectAt(row, col);   
      if(animal != null) {   
       incrementCount(animal.getClass());   
      }   
     }   
    }   
    countsValid = true;   
   }   
  }   

4. field
 import java.util.Collections;   
  import java.util.Iterator;   
  import java.util.LinkedList;   
  import java.util.List;   
  import java.util.Random;   
  public class Field   
  {   
   private static final Random rand = Randomizer.getRandom();   
   private int depth, width;   
   private Object[][] field;    
   public Field(int depth, int width)   
   {   
    this.depth = depth;   
    this.width = width;   
    field = new Object[depth][width];   
   }   
   public void clear()   
   {   
    for(int row = 0; row < depth; row++) {   
     for(int col = 0; col < width; col++) {   
      field[row][col] = null;   
     }   
    }   
   }   
   public void clear(Location location)   
   {   
    field[location.getRow()][location.getCol()] = null;   
   }   
   public void place(Object animal, int row, int col)   
   {   
    place(animal, new Location(row, col));   
   }   
   public void place(Object animal, Location location)   
   {   
    field[location.getRow()][location.getCol()] = animal;   
   }   
   public Object getObjectAt(Location location)   
   {   
    return getObjectAt(location.getRow(), location.getCol());   
   }   
   public Object getObjectAt(int row, int col)   
   {   
    return field[row][col];   
   }   
   public Location randomAdjacentLocation(Location location)   
   {   
    List<Location> adjacent = adjacentLocations(location);   
    return adjacent.get(0);   
   }    
   public List<Location> getFreeAdjacentLocations(Location location)   
   {   
    List<Location> free = new LinkedList<Location>();   
    List<Location> adjacent = adjacentLocations(location);   
    for(Location next : adjacent) {   
     if(getObjectAt(next) == null) {   
      free.add(next);   
     }   
    }   
    return free;   
   }   
   public Location freeAdjacentLocation(Location location)   
   {   
    List<Location> free = getFreeAdjacentLocations(location);   
    if(free.size() > 0) {   
     return free.get(0);   
    }   
    else {   
     return null;   
    }   
   }    
   public List<Location> adjacentLocations(Location location)   
   {   
    assert location != null : "Null location passed to adjacentLocations";    
    List<Location> locations = new LinkedList<Location>();   
    if(location != null) {   
     int row = location.getRow();   
     int col = location.getCol();   
     for(int roffset = -1; roffset <= 1; roffset++) {   
      int nextRow = row + roffset;   
      if(nextRow >= 0 && nextRow < depth) {   
       for(int coffset = -1; coffset <= 1; coffset++) {   
        int nextCol = col + coffset;   
        if(nextCol >= 0 && nextCol < width && (roffset != 0 || coffset != 0)) {   
         locations.add(new Location(nextRow, nextCol));   
        }   
       }   
      }   
     }   
     Collections.shuffle(locations, rand);   
    }   
    return locations;   
   }   
   public int getDepth()   
   {   
    return depth;   
   }   
   public int getWidth()   
   {   
    return width;   
   }   
  }   

5. Locationa
 public class Location   
  {   
   private int row;   
   private int col;   
   public Location(int row, int col)   
   {   
    this.row = row;   
    this.col = col;   
   }   
   public boolean equals(Object obj)   
   {   
    if(obj instanceof Location) {   
     Location other = (Location) obj;   
     return row == other.getRow() && col == other.getCol();   
    }   
    else {   
     return false;   
    }   
   }   
   public String toString()   
   {   
    return row + "," + col;   
   }   
   public int hashCode()   
   {   
    return (row << 16) + col;   
   }   
   public int getRow()   
   {   
    return row;   
   }   
   public int getCol()   
   {   
    return col;   
   }   
  }   

6. Randomizer
 import java.util.Random;   
  public class Randomizer   
  {   
   private static final int SEED = 1111;   
   private static final Random rand = new Random(SEED);    
   private static final boolean useShared = true;   
   public Randomizer()   
   {   
   }   
   public static Random getRandom()   
   {   
    if(useShared) {   
     return rand;   
    }   
    else {   
     return new Random();   
    }   
   }   
   public static void reset()   
   {   
    if(useShared) {   
     rand.setSeed(SEED);   
    }   
   }   
  }   

7. Counter
 import java.awt.Color;   
  public class Counter   
  {   
   private String name;   
   private int count;   
   public Counter(String name)   
   {   
    this.name = name;   
    count = 0;   
   }   
  public String getName()   
   {   
    return name;   
   }   
   public int getCount()   
   {   
    return count;   
   }   
   public void increment()   
   {   
    count++;   
   }   
   public void reset()   
   {   
    count = 0;   
   }   
  }   

8. Simulator
 import java.util.Random;   
  import java.util.List;   
  import java.util.ArrayList;   
  import java.util.Iterator;   
  import java.awt.Color;   
  public class Simulator   
  {    
   private static final int DEFAULT_WIDTH = 50;   
   private static final int DEFAULT_DEPTH = 50;    
   private static final double FOX_CREATION_PROBABILITY = 0.02;   
   private static final double RABBIT_CREATION_PROBABILITY = 0.08;    
   private List<Rabbit> rabbits;   
   private List<Fox> foxes;   
   private Field field;   
   private int step;   
   private SimulatorView view;   
  public Simulator()   
   {   
    this(DEFAULT_DEPTH, DEFAULT_WIDTH);   
   }   
   public Simulator(int depth, int width)   
   {   
    if(width <= 0 || depth <= 0) {   
     System.out.println("The dimensions must be greater than zero.");   
     System.out.println("Using default values.");   
     depth = DEFAULT_DEPTH;   
     width = DEFAULT_WIDTH;   
    }   
    rabbits = new ArrayList<Rabbit>();   
    foxes = new ArrayList<Fox>();   
    field = new Field(depth, width);   
    view = new SimulatorView(depth, width);   
    view.setColor(Rabbit.class, Color.orange);   
    view.setColor(Fox.class, Color.blue);   
    reset();   
   }   
   public void runLongSimulation()   
   {   
    simulate(500);   
   }   
   public void simulate(int numSteps)   
   {   
    for(int step = 1; step <= numSteps && view.isViable(field); step++) {   
     simulateOneStep();   
    }   
   }   
   public void simulateOneStep()   
   {   
    step++;   
    List<Rabbit> newRabbits = new ArrayList<Rabbit>();   
    for(Iterator<Rabbit> it = rabbits.iterator(); it.hasNext(); ) {   
     Rabbit rabbit = it.next();   
     rabbit.run(newRabbits);   
     if(! rabbit.isAlive()) {   
      it.remove();   
     }   
    }   
    List<Fox> newFoxes = new ArrayList<Fox>();  
    for(Iterator<Fox> it = foxes.iterator(); it.hasNext(); ) {   
     Fox fox = it.next();   
     fox.hunt(newFoxes);   
     if(! fox.isAlive()) {   
      it.remove();   
     }   
    }   
    rabbits.addAll(newRabbits);   
    foxes.addAll(newFoxes);   
    view.showStatus(step, field);   
   }   
   public void reset()   
   {   
    step = 0;   
    rabbits.clear();   
    foxes.clear();   
    populate();   
    view.showStatus(step, field);   
   }   
   private void populate()   
   {   
    Random rand = Randomizer.getRandom();   
    field.clear();   
    for(int row = 0; row < field.getDepth(); row++) {   
     for(int col = 0; col < field.getWidth(); col++) {   
      if(rand.nextDouble() <= FOX_CREATION_PROBABILITY) {   
       Location location = new Location(row, col);   
       Fox fox = new Fox(true, field, location);   
       foxes.add(fox);   
      }   
      else if(rand.nextDouble() <= RABBIT_CREATION_PROBABILITY) {   
       Location location = new Location(row, col);   
       Rabbit rabbit = new Rabbit(true, field, location);   
       rabbits.add(rabbit);   
      }   
     }   
    }   
   }   
  }   

9. Simulator view
  import java.awt.*;   
  import java.awt.event.*;   
  import javax.swing.*;   
  import java.util.LinkedHashMap;   
  import java.util.Map;   
  public class SimulatorView extends JFrame   
  {   
   private static final Color EMPTY_COLOR = Color.white;   
   private static final Color UNKNOWN_COLOR = Color.gray;   
   private final String STEP_PREFIX = "Step: ";   
   private final String POPULATION_PREFIX = "Population: ";   
   private JLabel stepLabel, population;   
   private FieldView fieldView;   
   private Map<Class, Color> colors;   
   private FieldStats stats;   
   public SimulatorView(int height, int width)   
   {   
    stats = new FieldStats();   
    colors = new LinkedHashMap<Class, Color>();   
    setTitle("Fox and Rabbit Simulation");   
    stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);   
    population = new JLabel(POPULATION_PREFIX, JLabel.CENTER);   
    setLocation(100, 50);   
    fieldView = new FieldView(height, width);   
    Container contents = getContentPane();   
    contents.add(stepLabel, BorderLayout.NORTH);   
    contents.add(fieldView, BorderLayout.CENTER);   
    contents.add(population, BorderLayout.SOUTH);   
    pack();   
    setVisible(true);   
   }   
   public void setColor(Class animalClass, Color color)   
   {   
    colors.put(animalClass, color);   
   }   
   private Color getColor(Class animalClass)   
   {   
    Color col = colors.get(animalClass);   
    if(col == null) {    
     return UNKNOWN_COLOR;   
    }   
    else {   
     return col;   
    }   
   }   
   public void showStatus(int step, Field field)   
   {   
    if(!isVisible()) {   
     setVisible(true);   
    }   
    stepLabel.setText(STEP_PREFIX + step);   
    stats.reset();   
    fieldView.preparePaint();   
    for(int row = 0; row < field.getDepth(); row++) {   
     for(int col = 0; col < field.getWidth(); col++) {   
      Object animal = field.getObjectAt(row, col);   
      if(animal != null) {   
       stats.incrementCount(animal.getClass());   
       fieldView.drawMark(col, row, getColor(animal.getClass()));   
      }   
      else {   
       fieldView.drawMark(col, row, EMPTY_COLOR);   
      }   
     }   
    }   
    stats.countFinished();   
    population.setText(POPULATION_PREFIX + stats.getPopulationDetails(field));   
    fieldView.repaint();   
   }   
   public boolean isViable(Field field)   
   {   
    return stats.isViable(field);   
   }   
   private class FieldView extends JPanel   
   {   
    private final int GRID_VIEW_SCALING_FACTOR = 6;   
    private int gridWidth, gridHeight;   
    private int xScale, yScale;   
    Dimension size;   
    private Graphics g;   
    private Image fieldImage;   
    public FieldView(int height, int width)   
    {   
     gridHeight = height;   
     gridWidth = width;   
     size = new Dimension(0, 0);   
    }   
    public Dimension getPreferredSize()   
    {   
     return new Dimension(gridWidth * GRID_VIEW_SCALING_FACTOR,   
          gridHeight * GRID_VIEW_SCALING_FACTOR);   
    }   
    public void preparePaint()   
    {   
     if(! size.equals(getSize())) {  
      size = getSize();   
      fieldImage = fieldView.createImage(size.width, size.height);   
      g = fieldImage.getGraphics();   
      xScale = size.width / gridWidth;   
      if(xScale < 1) {   
       xScale = GRID_VIEW_SCALING_FACTOR;   
      }   
      yScale = size.height / gridHeight;   
      if(yScale < 1) {   
       yScale = GRID_VIEW_SCALING_FACTOR;   
      }   
     }   
    }   
    public void drawMark(int x, int y, Color color)   
    {   
     g.setColor(color);   
     g.fillRect(x * xScale, y * yScale, xScale-1, yScale-1);   
    }   
    public void paintComponent(Graphics g)   
    {   
     if(fieldImage != null) {   
      Dimension currentSize = getSize();   
      if(size.equals(currentSize)) {   
       g.drawImage(fieldImage, 0, 0, null);   
      }   
      else {    
       g.drawImage(fieldImage, 0, 0, currentSize.width, currentSize.height, null);   
      }   
     }   
    }   
   }   
  }   

Berikut adalah hasil simulasinya

1. start

2. 1 step

3. 100 step

PBO-A Image viewer

Pada kesempatan kali ini saya mendapat kan tuguas membuat program Image Viewer dengan bbrp filter berikut adalah source codenya:
1. Image viewer
  import java.awt.*;    
  import java.awt.event.*;    
  import java.awt.image.*;    
  import javax.swing.*;    
  import javax.swing.border.*;    
  import java.io.File;    
  import java.util.List;    
  import java.util.ArrayList;    
  import java.util.Iterator;    
  public class ImageViewer    
  {     
   private static final String VERSION = "Version 3.0";    
   private static JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));    
   private JFrame frame;    
   private ImagePanel imagePanel;    
   private JLabel filenameLabel;    
   private JLabel statusLabel;    
   private JButton smallerButton;    
   private JButton largerButton;    
   private OFImage currentImage;    
   private List<Filter> filters;    
   public ImageViewer()    
   {    
   currentImage = null;    
   filters = createFilters();    
   makeFrame();    
   }     
   private void openFile()    
   {    
   int returnVal = fileChooser.showOpenDialog(frame);    
   if(returnVal != JFileChooser.APPROVE_OPTION) {    
    return;    
   }    
   File selectedFile = fileChooser.getSelectedFile();    
   currentImage = ImageFileManager.loadImage(selectedFile);    
   if(currentImage == null) {   
    JOptionPane.showMessageDialog(frame,    
     "The file was not in a recognized image file format.",    
     "Image Load Error",    
     JOptionPane.ERROR_MESSAGE);    
    return;    
   }    
   imagePanel.setImage(currentImage);    
   setButtonsEnabled(true);    
   showFilename(selectedFile.getPath());    
   showStatus("File loaded.");    
   frame.pack();    
   }    
   private void close()    
   {    
   currentImage = null;    
   imagePanel.clearImage();    
   showFilename(null);    
   setButtonsEnabled(false);    
   }    
   private void saveAs()    
   {    
   if(currentImage != null) {    
    int returnVal = fileChooser.showSaveDialog(frame);    
    if(returnVal != JFileChooser.APPROVE_OPTION) {    
    return;    
    }    
    File selectedFile = fileChooser.getSelectedFile();    
    ImageFileManager.saveImage(currentImage, selectedFile);    
    showFilename(selectedFile.getPath());    
   }    
   }    
   private void quit()    
   {    
   System.exit(0);    
   }    
   private void applyFilter(Filter filter)    
   {    
   if(currentImage != null) {    
    filter.apply(currentImage);    
    frame.repaint();    
    showStatus("Applied: " + filter.getName());    
   }    
   else {    
    showStatus("No image loaded.");    
   }    
   }    
   private void showAbout()    
   {    
   JOptionPane.showMessageDialog(frame,    
     "ImageViewer\n" + VERSION,    
     "About ImageViewer",    
     JOptionPane.INFORMATION_MESSAGE);    
   }    
   private void makeLarger()    
   {    
   if(currentImage != null) {    
    int width = currentImage.getWidth();    
    int height = currentImage.getHeight();    
    OFImage newImage = new OFImage(width * 2, height * 2);    
    for(int y = 0; y < height; y++) {    
    for(int x = 0; x < width; x++) {    
     Color col = currentImage.getPixel(x, y);    
     newImage.setPixel(x * 2, y * 2, col);    
     newImage.setPixel(x * 2 + 1, y * 2, col);    
     newImage.setPixel(x * 2, y * 2 + 1, col);    
     newImage.setPixel(x * 2+1, y * 2 + 1, col);    
    }    
    }    
    currentImage = newImage;    
    imagePanel.setImage(currentImage);    
    frame.pack();    
   }    
   }    
   private void makeSmaller()    
   {    
   if(currentImage != null) {    
    int width = currentImage.getWidth() / 2;    
    int height = currentImage.getHeight() / 2;    
    OFImage newImage = new OFImage(width, height);   
    for(int y = 0; y < height; y++) {    
    for(int x = 0; x < width; x++) {    
     newImage.setPixel(x, y, currentImage.getPixel(x * 2, y * 2));    
    }    
    }    
    currentImage = newImage;    
    imagePanel.setImage(currentImage);    
    frame.pack();    
   }    
   private void showFilename(String filename)    
   {    
   if(filename == null) {    
    filenameLabel.setText("No file displayed.");    
   }    
   else {    
    filenameLabel.setText("File: " + filename);    
   }    
   }    
   private void showStatus(String text)    
   {    
   statusLabel.setText(text);    
   }    
   private void setButtonsEnabled(boolean status)    
   {    
   smallerButton.setEnabled(status);    
   largerButton.setEnabled(status);    
   }    
   private List<Filter> createFilters()    
   {    
   List<Filter> filterList = new ArrayList<Filter>();    
   filterList.add(new DarkerFilter("Darker"));    
   filterList.add(new LighterFilter("Lighter"));    
   filterList.add(new ThresholdFilter("Threshold"));    
   filterList.add(new FishEyeFilter("Fish Eye"));    
   return filterList;    
   }    
   private void makeFrame()    
   {    
   frame = new JFrame("ImageViewer");    
   JPanel contentPane = (JPanel)frame.getContentPane();    
   contentPane.setBorder(new EmptyBorder(6, 6, 6, 6));    
   makeMenuBar(frame);    
   contentPane.setLayout(new BorderLayout(6, 6));    
   imagePanel = new ImagePanel();    
   imagePanel.setBorder(new EtchedBorder());    
   contentPane.add(imagePanel, BorderLayout.CENTER);    
   filenameLabel = new JLabel();    
   contentPane.add(filenameLabel, BorderLayout.NORTH);    
   statusLabel = new JLabel(VERSION);    
   contentPane.add(statusLabel, BorderLayout.SOUTH);    
   JPanel toolbar = new JPanel();    
   toolbar.setLayout(new GridLayout(0, 1));    
   smallerButton = new JButton("Smaller");    
   smallerButton.addActionListener(new ActionListener() {    
      public void actionPerformed(ActionEvent e) { makeSmaller(); }    
      });    
   toolbar.add(smallerButton);    
   largerButton = new JButton("Larger");    
   largerButton.addActionListener(new ActionListener() {    
      public void actionPerformed(ActionEvent e) { makeLarger(); }    
      });    
   toolbar.add(largerButton);    
   JPanel flow = new JPanel();    
   flow.add(toolbar);    
   contentPane.add(flow, BorderLayout.WEST);    
   showFilename(null);    
   setButtonsEnabled(false);    
   frame.pack();    
   Dimension d = Toolkit.getDefaultToolkit().getScreenSize();    
   frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);    
   frame.setVisible(true);    
   }    
   private void makeMenuBar(JFrame frame)    
   {    
   final int SHORTCUT_MASK =    
    Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();    
   JMenuBar menubar = new JMenuBar();    
   frame.setJMenuBar(menubar);    
   JMenu menu;    
   JMenuItem item;    
   menu = new JMenu("File");    
   menubar.add(menu);    
   item = new JMenuItem("Open...");    
    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, SHORTCUT_MASK));    
    item.addActionListener(new ActionListener() {    
      public void actionPerformed(ActionEvent e) { openFile(); }    
      });    
   menu.add(item);    
   item = new JMenuItem("Close");    
    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, SHORTCUT_MASK));    
    item.addActionListener(new ActionListener() {    
      public void actionPerformed(ActionEvent e) { close(); }    
      });    
   menu.add(item);    
   menu.addSeparator();    
   item = new JMenuItem("Save As...");    
    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, SHORTCUT_MASK));    
    item.addActionListener(new ActionListener() {    
      public void actionPerformed(ActionEvent e) { saveAs(); }    
      });    
   menu.add(item);    
   menu.addSeparator();    
   item = new JMenuItem("Quit");    
    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));    
    item.addActionListener(new ActionListener() {    
      public void actionPerformed(ActionEvent e) { quit(); }    
      });    
   menu.add(item);    
   menu = new JMenu("Filter");    
   menubar.add(menu);    
   for(final Filter filter : filters) {    
    item = new JMenuItem(filter.getName());    
    item.addActionListener(new ActionListener() {    
      public void actionPerformed(ActionEvent e) {    
       applyFilter(filter);    
      }    
      });    
    menu.add(item);    
   }    
   menu = new JMenu("Help");    
   menubar.add(menu);    
   item = new JMenuItem("About ImageViewer...");    
    item.addActionListener(new ActionListener() {    
      public void actionPerformed(ActionEvent e) { showAbout(); }    
      });    
   menu.add(item);    
   }    
  }  

2.OF Image
  import java.awt.*;    
  import java.awt.image.*;    
  import javax.swing.*;    
  public class OFImage extends BufferedImage    
  {    
   public OFImage(BufferedImage image)    
   {    
   super(image.getColorModel(), image.copyData(null),    
    image.isAlphaPremultiplied(), null);    
   }    
   public OFImage(int width, int height)    
   {    
   super(width, height, TYPE_INT_RGB);    
   }    
   public void setPixel(int x, int y, Color col)    
   {    
   int pixel = col.getRGB();    
   setRGB(x, y, pixel);    
   }    
   public Color getPixel(int x, int y)    
   {    
   int pixel = getRGB(x, y);    
   return new Color(pixel);    
   }    
  }    

3.Image panel
 import java.awt.*;    
  import javax.swing.*;    
  import java.awt.image.*;    
  public class ImagePanel extends JComponent    
  {    
   private int width, height;    
   private OFImage panelImage;    
   public ImagePanel()    
   {    
   width = 360;   
   height = 240;    
   panelImage = null;    
   }    
   public void setImage(OFImage image)    
   {    
   if(image != null) {    
    width = image.getWidth();    
    height = image.getHeight();    
    panelImage = image;    
    repaint();    
   }    
   }    
   public void clearImage()    
   {    
   Graphics imageGraphics = panelImage.getGraphics();    
   imageGraphics.setColor(Color.LIGHT_GRAY);    
   imageGraphics.fillRect(0, 0, width, height);    
   repaint();    
   }    
   public Dimension getPreferredSize()    
   {    
   return new Dimension(width, height);    
   }    
   public void paintComponent(Graphics g)    
   {    
   Dimension size = getSize();    
   g.clearRect(0, 0, size.width, size.height);    
   if(panelImage != null) {    
    g.drawImage(panelImage, 0, 0, null);    
   }    
   }    
  }    

4. Image File Manager
  import java.awt.image.*;    
  import javax.imageio.*;    
  import java.io.*;    
  public class ImageFileManager    
  {    
   private static final String IMAGE_FORMAT = "jpg";    
   public static OFImage loadImage(File imageFile)    
   {    
   try {    
    BufferedImage image = ImageIO.read(imageFile);    
    if(image == null || (image.getWidth(null) < 0)) {    
    return null;    
    }    
    return new OFImage(image);    
   }    
   catch(IOException exc) {    
    return null;    
   }    
   }    
   public static void saveImage(OFImage image, File file)    
   {    
   try {    
    ImageIO.write(image, IMAGE_FORMAT, file);    
   }    
   catch(IOException exc) {    
    return;    
   }    
   }    
  }    

5. Filter
  public abstract class Filter    
  {    
   private String name;    
   public Filter(String name)    
   {    
   this.name = name;    
   }    
   public String getName()    
   {    
   return name;    
   }    
   public abstract void apply(OFImage image);    
  }    

6. Treshold Filter
 import java.awt.Color;    
  public class ThresholdFilter extends Filter    
  {    
   public ThresholdFilter(String name)    
   {    
   super(name);    
   }    
   public void apply(OFImage image)    
   {    
   int height = image.getHeight();    
   int width = image.getWidth();    
   for(int y = 0; y < height; y++) {    
    for(int x = 0; x < width; x++) {    
    Color pixel = image.getPixel(x, y);    
    int brightness = (pixel.getRed() + pixel.getBlue() + pixel.getGreen()) / 3;    
    if(brightness <= 85) {    
     image.setPixel(x, y, Color.BLACK);    
    }    
    else if(brightness <= 170) {    
     image.setPixel(x, y, Color.GRAY);    
    }    
    else {    
     image.setPixel(x, y, Color.WHITE);    
    }    
    }    
   }    
   }    
  }    

7. Darker Filter
  public class DarkerFilter extends Filter    
  {    
   public DarkerFilter(String name)    
   {    
   super(name);    
   }    
   public void apply(OFImage image)    
   {    
   int height = image.getHeight();    
   int width = image.getWidth();    
   for(int y = 0; y < height; y++) {    
    for(int x = 0; x < width; x++) {    
    image.setPixel(x, y, image.getPixel(x, y).darker());    
    }    
   }    
   }    
  }    

8. Lighter Filter
  public class LighterFilter extends Filter    
  {    
   public LighterFilter(String name)    
   {    
   super(name);    
   }  
   public void apply(OFImage image)    
   {    
   int height = image.getHeight();    
   int width = image.getWidth();    
   for(int y = 0; y < height; y++) {    
    for(int x = 0; x < width; x++) {    
    image.setPixel(x, y, image.getPixel(x, y).brighter());    
    }    
   }    
   }    
  }    

9. Fish eye Filte
 import java.awt.Color;   
  public class FishEyeFilter extends Filter    
  {    
   private final static int SCALE = 20;  
   private final static double TWO_PI = 2 * Math.PI;    
   public FishEyeFilter(String name)    
   {    
   super(name);    
   }    
   public void apply(OFImage image)    
   {    
   int height = image.getHeight();    
   int width = image.getWidth();    
   OFImage original = new OFImage(image);    
   int[] xa = computeXArray(width);    
   int[] ya = computeYArray(height);    
   for(int y = 0; y < height; y++) {    
    for(int x = 0; x < width; x++) {    
    image.setPixel(x, y, original.getPixel(x + xa[x], y + ya[y]));    
    }    
   }    
   }    
   private int[] computeXArray(int width)    
   {    
   int[] xArray = new int[width];    
   for(int i=0; i < width; i++) {    
    xArray[i] = (int)(Math.sin( ((double)i / width) * TWO_PI) * SCALE);    
   }    
   return xArray;    
   }    
   private int[] computeYArray(int height)    
   {    
   int[] yArray = new int[height];    
   for(int i=0; i < height; i++) {    
    yArray[i] = (int)(Math.sin( ((double)i / height) * TWO_PI) * SCALE);    
   }    
   return yArray;    
   }    
  }    

Dan berikut adalah hasilnya:

1. no filter

2. treshold

3. lighter or darker

Selasa, 13 November 2018

PWEB C AJAX

pada kesempatan kali ini saya mendapatkan tugas membuat formulir pendafataran siswa dengan menggunakan bahasa AJAX, berikut saya lampirkan hasilnya:







Berikut saya lampirkan pula source codenya:
1. index
 <!DOCTYPE html>   
  <html>   
  <head>  
   <script>    
    function listsiswa() {    
     var xhttp;    
     if (window.XMLHttpRequest) {    
      xhttp = new XMLHttpRequest();    
     }    
     else {    
      xhttp = new ActiveXObject("Microsoft.XMLHTTP");    
     }    
     xhttp.onreadystatechange = function() {    
      if (this.readyState == 4 && this.status == 200) {    
       document.getElementById("status").innerHTML = this.responseText;    
      }    
     };    
     xhttp.open("GET", "list-siswa.php", true);    
     xhttp.send();    
    }    
    function daftar() {    
     var xhttp;    
     if (window.XMLHttpRequest) {    
      xhttp = new XMLHttpRequest();    
     }    
     else {    
      xhttp = new ActiveXObject("Microsoft.XMLHTTP");    
     }    
     xhttp.onreadystatechange = function() {    
      if (this.readyState == 4 && this.status == 200) {    
       document.getElementById("status").innerHTML = this.responseText;    
      }    
     };    
     xhttp.open("GET", "form-daftar.php", true);    
     xhttp.send();    
    }   
    function hapus(id) {    
     var xhttp;    
     if (window.XMLHttpRequest) {    
      xhttp = new XMLHttpRequest();    
     }    
     else {    
      xhttp = new ActiveXObject("Microsoft.XMLHTTP");    
     }    
     xhttp.onreadystatechange = function() {    
      if (this.readyState == 4 && this.status == 200) {    
       alert(this.responseText);    
       listsiswa();    
      }    
     };    
     xhttp.open("GET", "hapus.php?id=" + id, true);    
     xhttp.send();    
    }    
   </script>   
   <title>Pendaftaran Siswa Baru | SMK Coding</title>   
  </head>   
  <body>   
   <header>   
    <h3>Pendaftaran Siswa Baru</h3>   
    <h1>SMK Coding</h1>   
   </header>   
   <button type="button" onclick="listsiswa()">List Siswa</button>   
   <button type="button" onclick="daftar()">Pendaftaran Siswa</button>  
   <div id="status"></div>   
   </body>   
  </html>   

2.config
 <?php  
 $server = "localhost";  
 $user = "root";  
 $password = "";  
 $nama_database = "ajax";  
 $db = mysqli_connect($server, $user, $password , $nama_database);  
 if( !$db ){  
   die("Gagal terhubung dengan database: " . mysqli_connect_error());  
 }  
 ?>  

3. list siswa
 <?php include("config.php"); ?>   
  <!DOCTYPE html>   
  <html>   
  <head>  
   <title>Pendaftaran Siswa Baru | SMK Coding</title>   
   </head>   
  <body>   
   <header>   
    <h3>Siswa yang sudah mendaftar</h3>   
   </header>   
   <br>    
   <table border="1">    
   <thead>    
    <tr>    
     <th>No</th>    
     <th>Nama</th>    
     <th>Alamat</th>    
     <th>Jenis Kelamin</th>    
     <th>Agama</th>    
     <th>Sekolah Asal</th>    
     <th>Tindakan</th>    
    </tr>    
   </thead>    
   <tbody>   
    <?php    
    $sql = "SELECT * FROM calon_siswa";    
    $query = mysqli_query($db, $sql);    
    $no = 0;    
    while($siswa = mysqli_fetch_array($query)){    
     echo "<tr>";    
     $no++;    
     echo "<td>".$no."</td>";    
     echo "<td>".$siswa['nama']."</td>";    
     echo "<td>".$siswa['alamat']."</td>";    
     echo "<td>".$siswa['jenis_kelamin']."</td>";    
     echo "<td>".$siswa['agama']."</td>";    
     echo "<td>".$siswa['sekolah_asal']."</td>";    
     echo "<td>";    
     echo "<button><a href='form-edit.php?id=".$siswa['id']."'>Edit</a></button> | ";    
     echo "<input type='button' onclick=hapus('".$siswa['id']."') value='Hapus'>";    
     echo "</td>";    
     echo "</tr>";    
    }    
   ?>    
   </tbody>   
   </table>   
   <p> Total: <?php echo mysqli_num_rows($query) ?></p>   
   <div id="status"></div>   
   </body>   
  </html>  

4. form edit
 <?php   
  include("config.php");   
  if( !isset($_GET['id']) ){   
   header('Location: list-siswa.php');   
  }   
  $id = $_GET['id'];   
  $sql = "SELECT * FROM calon_siswa WHERE id=$id";   
  $query = mysqli_query($db, $sql);   
  $siswa = mysqli_fetch_assoc($query);   
  if( mysqli_num_rows($query) < 1 ){   
   die("Data tidak ditemukan.");   
  }   
  ?>   
  <!DOCTYPE html>   
  <html>   
  <head>  
   <title>Formulir Edit Siswa | SMK Coding</title>   
   <script type="text/javascript">    
    function edit(){    
    var nama = document.getElementById("nama").value;    
    var alamat = document.getElementById("alamat").value;    
    var jenis_kelamin;    
    if(document.getElementById("jk_laki").checked)    
    {    
     jenis_kelamin = "laki-laki";    
    }    
    else { jenis_kelamin = "perempuan";}    
    var agama = document.getElementById("agama").value;    
    var sekolah_asal = document.getElementById("sekolah_asal").value;    
    var xhttp;    
    if (window.XMLHttpRequest) {    
     xhttp = new XMLHttpRequest();    
    }    
    else {    
     xhttp = new ActiveXObject("Microsoft.XMLHTTP");    
    }    
    xhttp.onreadystatechange = function() {    
    if (this.readyState == 4 && this.status == 200)    
    {    
     alert('Perubahan Data Berhasil.');    
     listsiswa();    
    }    
    };    
    xhttp.open("GET", "proses-edit.php?id=" + <?php echo $id; ?> + "&nama=" + nama + "&alamat=" + alamat + "&jenis_kelamin=" + jenis_kelamin + "&agama=" + agama + "&sekolah_asal=" + "sekolah_asal", true);    
    xhttp.send();    
   }    
   </script>    
  </head>   
  <body>   
   <header>   
    <h3>Formulir Edit Siswa</h3>   
   </header>   
   <form action="proses-edit.php" method="POST" >   
    <fieldset>   
     <input type="hidden" name="id" value="<?php echo $siswa['id'] ?>" />   
    <p>   
     <label for="nama">Nama: </label>   
     <input type="text" name="nama" id="nama" placeholder="nama lengkap" value="<?php echo $siswa['nama'] ?>" />   
    </p>   
    <p>   
     <label for="alamat">Alamat: </label>   
     <textarea name="alamat" id="alamat"><?php echo $siswa['alamat'] ?></textarea>   
    </p>   
    <p>   
     <label for="jenis_kelamin">Jenis Kelamin: </label>   
     <?php $jk = $siswa['jenis_kelamin']; ?>   
     <label><input type="radio" name="jenis_kelamin" id="jk_laki" value="laki-laki" <?php echo ($jk == 'laki-laki') ? "checked": "" ?>> Laki-laki</label>   
     <label><input type="radio" name="jenis_kelamin" id="jk_per" value="perempuan" <?php echo ($jk == 'perempuan') ? "checked": "" ?>> Perempuan</label>   
    </p>   
    <p>   
     <label for="agama">Agama: </label>   
     <?php $agama = $siswa['agama']; ?>   
     <select name="agama" id="agama">   
      <option <?php echo ($agama == 'Islam') ? "selected": "" ?>>Islam</option>   
      <option <?php echo ($agama == 'Kristen') ? "selected": "" ?>>Kristen</option>   
      <option <?php echo ($agama == 'Hindu') ? "selected": "" ?>>Hindu</option>   
      <option <?php echo ($agama == 'Budha') ? "selected": "" ?>>Budha</option>   
      <option <?php echo ($agama == 'Katolik') ? "selected": "" ?>>Katolik</option>  
           <option <?php echo ($agama == 'Kong Hu Cu') ? "selected": "" ?>>Kong Hu Cu</option>  
     </select>   
    </p>   
    <p>   
     <label for="sekolah_asal">Sekolah Asal: </label>   
     <input type="text" name="sekolah_asal" id="sekolah_asal" placeholder="nama sekolah" value="<?php echo $siswa['sekolah_asal'] ?>" />   
    </p>   
    <p>   
     <input type="submit" value="Simpan" name="simpan" onclick="edit()" />   
    </p>   
    </fieldset>   
   </form>   
   </body>   
  </html>   

5. form daftar
 <!DOCTYPE html>   
  <html>   
  <head>   
   <script type="text/javascript">    
   function addsiswa() {    
    var nama = document.getElementById("nama").value;    
    var alamat = document.getElementById("alamat").value;    
    var jenis_kelamin;    
    if(document.getElementById("jk_laki").checked) {    
     jenis_kelamin = "laki-laki";    
    }    
    else { jenis_kelamin = "perempuan";}    
    var agama = document.getElementById("agama").value;    
    var sekolah_asal = document.getElementById("sekolah_asal").value;    
    var xhttp;    
    if (window.XMLHttpRequest) {    
     xhttp = new XMLHttpRequest();    
    }    
    else {    
     xhttp = new ActiveXObject("Microsoft.XMLHTTP");    
    }    
    xhttp.onreadystatechange = function() {    
    if (this.readyState == 4 && this.status == 200)    
    {    
     alert('Pendaftaran berhasil');    
     listsiswa();    
    }    
    };    
    xhttp.open("GET", "proses-pendaftaran.php?nama=" + nama + "&alamat=" + alamat + "&jenis_kelamin=" + jenis_kelamin + "&agama=" + agama + "&sekolah_asal=" + "sekolah_asal", true);    
    xhttp.send();    
   }    
   </script>    
  </head>   
  <body>   
   <header>   
    <h3>Formulir Pendaftaran Siswa Baru</h3>   
   </header>   
   <form action="proses-pendaftaran.php" method="POST">   
    <fieldset>   
    <p>   
     <label for="nama">Nama: </label>   
     <input type="text" name="nama" id="nama" placeholder="Nama Lengkap" />   
    </p>   
    <p>   
     <label for="alamat">Alamat: </label>   
     <textarea name="alamat" id="alamat"></textarea>   
    </p>   
    <p>   
     <label for="jenis_kelamin">Jenis Kelamin: </label>   
     <label><input type="radio" name="jenis_kelamin" id="jk_laki" value="laki-laki"> Laki-laki</label>   
     <label><input type="radio" name="jenis_kelamin" id="jk_per" value="perempuan"> Perempuan</label>   
    </p>   
    <p>   
     <label for="agama">Agama: </label>   
     <select name="agama" id="agama">   
      <option>Islam</option>   
      <option>Kristen</option>   
      <option>Hindu</option>   
      <option>Budha</option>   
      <option>Katolik</option>  
           <option>Kong Hu Cu</option>  
     </select>   
    </p>   
    <p>   
     <label for="sekolah_asal">Sekolah Asal: </label>   
     <input type="text" name="sekolah_asal" id="sekolah_asal" placeholder="nama sekolah" />   
    </p>   
    <p>   
     <input type="submit" value="Daftar" name="daftar" onclick="addsiswa()" />   
    </p>   
    </fieldset>   
   </form>   
   </body>   
  </html>   

6. hapus
 <?php      
  include("config.php");   
    if(isset($_GET['id']) ){   
     $id = $_GET['id'];    
     $sql = "DELETE FROM calon_siswa WHERE id=$id";   
     $query = mysqli_query($db, $sql);    
     if( $query ){   
      echo "Hapus Data Berhasil";   
     } else {   
      echo "GAGAL";   
     }      
    }    
  ?>   

7. proses edit
  <?php   
  include("config.php");   
  if(isset($_POST['simpan'])){   
   $id = $_POST['id'];   
   $nama = $_POST['nama'];   
   $alamat = $_POST['alamat'];   
   $jk = $_POST['jenis_kelamin'];   
   $agama = $_POST['agama'];   
   $sekolah = $_POST['sekolah_asal'];   
   $sql = "UPDATE calon_siswa SET nama='$nama', alamat='$alamat', jenis_kelamin='$jk', agama='$agama', sekolah_asal='$sekolah' WHERE id=$id";   
   $query = mysqli_query($db, $sql);   
   if( $query ) {   
    header('Location: index.php');   
   } else {   
    die("Gagal menyimpan perubahan.");   
   }   
  } else {   
   die("Akses dilarang!");   
  }   
  ?>   

8. proses daftar
 <?php   
  include("config.php");   
  if(isset($_POST['daftar'])){   
   $nama = $_POST['nama'];   
   $alamat = $_POST['alamat'];   
   $jk = $_POST['jenis_kelamin'];   
   $agama = $_POST['agama'];   
   $sekolah = $_POST['sekolah_asal'];   
   $sql = "INSERT INTO calon_siswa (nama, alamat, jenis_kelamin, agama, sekolah_asal) VALUE ('$nama', '$alamat', '$jk', '$agama', '$sekolah')";   
   $query = mysqli_query($db, $sql);   
   if( $query ) {   
    header('Location: index.php');   
   } else {   
    echo "Pendaftaran siswa gagal.";   
   }   
  } else {   
   die("Akses dilarang!");   
  }   
  ?>