Query program java

Posted: Mei 18, 2013 in Maniesst Imutzz

Pertemuan 11 Dasar Java Berbasis GUI dengan NetBeans 6.5.1

Permulaan :
1. Install Netbeans 6.5.1
2. Buat Folder Baru di C:\nama_mynbproject
3. Jalankan program NetBeans tsb.
4. Buat Project Baru :
– File
– New Project
– Name Project : MyKalkulator
– Pilih Project Location (C:\nama_mynbproject).
5. Klik kanan diprojek MyKalkulator
6. Pilih JFrame Form
7. Class Name : fhitung
8. Package : MyKalkulator
9. Klik Kanan pada tampilan form fhitung, pilih :
– Set Layout
– Null Layout
10. Untuk membuat tampilan form di tengah saat running, pilih :
– Properties => – code
– form size policy
– generate resize code
————————————————————————————————-
Source Code :

1. Tombol Tambah :
private void jbtntambahActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int a = Integer.parseInt(jtxtnil1.getText());
int b = Integer.parseInt(jtxtnil2.getText());
int c = a+b;
jtxthasil.setText(Integer.toString(c));
}

2. Tombol Kurang :
private void jbtnkurangActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int a = Integer.parseInt(jtxtnil1.getText());
int b = Integer.parseInt(jtxtnil2.getText());
int c = a-b;
jtxthasil.setText(Integer.toString(c));
}

3. Tombol Kali :
private void jbtnkaliActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int a = Integer.parseInt(jtxtnil1.getText());
int b = Integer.parseInt(jtxtnil2.getText());
int c = a*b;
jtxthasil.setText(Integer.toString(c));
}

4. Tombol Bagi :
private void jbtnbagiActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int a = Integer.parseInt(jtxtnil1.getText());
int b = Integer.parseInt(jtxtnil2.getText());
int c = a/b;
jtxthasil.setText(Integer.toString(c));
}

5. Tombol Bersih :
private void jbtnbersihActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jtxtnil1.setText(“”);
jtxtnil2.setText(“”);
jtxthasil.setText(“”);
}

6. Tombol Keluar :
private void jbtnkeluarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
dispose();
}

Step by step

1. Install webserver

WAMP stands for Windows, Apache, MySQL and PHP. get ist from  http://www.wampserver.com/en/
For Linux see LAMP or XAMPP
Install it. Now you can write a http client, and place it into the WWW-directory on this webserver.
Typically: call it index.php, open in a editor and copy following into. See this simple example:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="de">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Tutorial index page</title>
</head><body bgcolor=#cccccc>
<div align="center">
<!--index page of tutorial-->
<?php 
$my_query = "SELECT title FROM tutorial";
echo $my_query;
?>
</div><br></body></html>

go to

http://localhost/index.php

or

http://localhost/

this should display the content of variable $my_query in your browser, but you will not see it.
So install PHP!

2. Install PHP

Get it from  http://www.php.net/downloads.php, install it.
Due the installation it should automatically configurate the webserver.

3. Database

It is possible to use any database, it only depends on connector. So i use for my nutrient content calculator local MySql? database. For this tutorial i create a table “tutorial”:

Id Title
1 Webservices
2 Step by Step

4. Install Netbeans

Get ist from  http://www.netbeans.org/

5. Install Glassfish v2.1

If not installed with Netbeans:
get it from  https://glassfish.dev.java.net/public/downloadsindex.html#top

6. Create JavaBean?

Netbeans includes a good tool to create JavaBeans?. Let’s do a simple webservice bean:

  • New Project -> Java EE -> EJB Module
  • Project Name: “tutotial”, Server: “GlassGish? v2.1”
  • click on project -> new -> new Webservice
  • provide a package name, an webservice name. done. now we see:
package ws;

import javax.jws.WebService;
import javax.ejb.Stateless;

/**
 *
 * @author Konstantin
 */
@WebService()
@Stateless()
public class PingPong {

}

7. Some simple code

now we add a simple webservice operation:

package ws;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.ejb.Stateless;

@WebService()
@Stateless()
public class Ping {

    /**
     * Web service operation
     */
    @WebMethod(operationName = "ping")
    public String ping() {
        return "pong";
    }
}

therefor netbeans offers nice tools:

  • add webservice operation
  • then deploy it on glassfish ( should be allready started)

now you can see the WSDL file under :

http://localhost:8080/PingService/Ping?wsdl

(WSDL = Web Services Description Language, describes webservice and operations)
glassfish offers also a testing interface for webservice operations. see it at:

http://localhost:8080/PingService/Ping?tester

8. Connect to webservice

Back to php code. Now it is possible to call webservice over the SOAP-protocol. (therefor php-extention “php-soap” should be initialized)

<?php 
               echo "create a connection to webservice";

               $client  = new SoapClient("http://localhost:8080/PingService/Ping?wsdl");
               echo "<hr>";
               try {
                       $result = $client->ping();
               } catch (SoapFault $exception) {
               }
               print($result->return);
?>

as a result you see in your bowser:

9. Get response

In order to use webservice as a preference SQL application you need to export PreferenceSQL and PreferenceBase as .jar file
let’s call it “prefSQL.jar”

now add it as JAR/Folder to netbeans project under Libraries
xxl.jar has also to be added to webservice project.


Next web operation, named “getQuery”, gets a query and returns a simple String as a result of evaluating.
webservice code:

package ws;

import java.sql.Connection;
import java.sql.DriverManager;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.ejb.Stateless;
import preference.sql.PSQLEngine;
import xxl.core.cursors.MetaDataCursor;
import xxl.core.relational.ArrayTuple;
/**
 */
@WebService()
@Stateless()
public class Ping {
    /**
     * Web service operation
     */
    @WebMethod(operationName = "ping")
    public String ping() {
        return "pong";
    }

    public static String DBDRIVER = "com.mysql.jdbc.Driver";
    public static String DBURL = "jdbc:mysql://localhost/tutorial";
    public static String DBUSER = "root";
    public static String DBPASS = "kostja";
    /**
     * gets a preference SQL query and returns a string result
     */
    @WebMethod(operationName = "getQuery") 
    public String getQuery(@WebParam(name = "query")
    String query) {
        System.out.println("incoming query : " + query);
        return executeQuery(query);
    }
    String executeQuery(String query) {
        Connection sqlCon = null;
        String resString = "";
        try {
            Class.forName(DBDRIVER);
            sqlCon =  DriverManager.getConnection(DBURL, DBUSER, DBPASS);
            PSQLEngine engine = new PSQLEngine(sqlCon);
            MetaDataCursor rs = engine.executeQuery(query);
            ArrayTuple current = null;
            while (rs.hasNext()) {
                current = (ArrayTuple) rs.next();
                resString=resString + current+"\n";
            }

            } catch (Exception e) {
                e.printStackTrace();
            }
        return resString;
        }
}

php part:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="de">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Tutorial index page</title>
</head><body bgcolor=#cccccc>
<div align="center">
<!--index page of tutorial-->
<?php 
                echo "create a connection to webservice\n";
                echo "<hr>";

                $client  = new SoapClient("http://localhost:8080/PingService/Ping?wsdl");
                $query ="SELECT * FROM tutorial preferring ID around 1";
                try {
                        $result = $client->getQuery(array("query" => $query));
                } catch (SoapFault $exception) {
                }
                echo "Result = "; 
                print_r($result->return);
?>
</div><br></body></html>

if you now call index.php in your browser you see this:

so what we did?

  • send a query over soap-protocol to webservice
  • execute query with preference SQL
  • send a String result to client

Success!

TRANSAKSI PENJUALAN

Langkah 1:
Pindahkan StoreBooks – Transformer ke dalam sembarang direktori. Disini kami menaruh di My Document-NetbeansProjects

Langkah 2 :
Buku Netbeans, lalu Open Project, Pilih StoreBooks – Transformer.

Langkah 3 :
Simpan / Copy Paste file jasperreport-2.0.5.jar di direktori C:\lib\

Langkah 4 :
Kembali ke Netbeans, klik kanan project StoreBooks lalu pilih Resolve References Problem…

Langkah 5 :
Lalu pilih Opsi yang bawah terlebih dahulu. Lalu klik Resolve…

Langkah 6 :
Lalu arahkan ke file jasperreport-2.0.5 yang telah di copy sebelumnya

Langkah 7 :
Bila sudah benar, pilih opsi yang pertama lalu klik Resolve…

Langkah 8 :
Akan muncul jendela Library Manager.

Langkah 9:
Tekan tombol New Library…lalu ketikan persis pada gambar dibawah ini.

Langkah 10 :
Bila sudah seperti pada gambar dibawah ini.

Langkah 11 :
Tekan Add JAR/Folder…lalu pilih file jasperreport-2.0.5 yang sebelumnya telah di copy di C:/lib

Langkah 12:
Pastikan tampilan seperti gambar dibawah ini

Langkah 13:
Bila sudah klik OK saja. Dan pastikan proses setting telah berhasil seperti gambar dibawah ini

Langkah 14:
Kalau sudah di setting,,pastikan library telah terpasang semua. Terlihat pada gambar dibawah ini.

Langkah 15:
Bila sudah sekarang kita setting directory run untuk caranya, klik kanan pada project StoreBooks lalu arahkan ke Properties.

Langkah 16:
Akan muncul window Project Properties, lalu arahkan ke bagian Run. Seperti gambar dibawah ini.

Langkah 17 :
Pada Working Directory, Klik tombol Browse… Lalu pilih project StoreBooks Transformer – Built – Classes . Lalu tekan Open. Seperti gambar dibawah ini.

Langkah 18:
Bila sudah klik Ok saja, lalu sekarang kita sesuaikan database kita dengan setting coding di program. Lihat ke package bookstore.model file koneksi.java. Sesuaikan settingan computer anda dengan koding program. Lihat koding yang di block.
Database name : bookstore
User name : root
User password : [kosong]
Itu adalah setting pada computer saya dengan menggunakan XAMPP. Sesuaikan dengan settingan computer anda.

Langkah 19:
Bila sudah, sekarang kita buat import database, caranya buat database name ‘bookstore’ lalu klik import pada jendela phpmyadmin dan pilih file bookstore-fix.sql. Bila sudah benar seperti gambar dibawah ini :

Langkah 20:
Bila sudah selesailah settingannya. Sekarang masuk lagi ke Netbeans, lalu setting bookstore menjadi main project dan lakukan clean and build project. Lalu setelah itu run dengan menekan tombol F6. Tampilan awal seperti gamba dibawah ini :

Langkah 21:
Lalu setelah itu, lakukan login terlebih dahulu. Tekan Data Kasir lalu Arahkan ke Login Kasir.

Langkah 22:
Akan muncul window login, masukan username ‘adiputra’ dan password ‘artupida’ lalu tekan Login. Bila benar proses login berhasil.

Setelah Login Anda bisa masuk ke data buku atau langsung ke data transaksi.

Langkah 23:
Berikut adalah data buku. Pada data buku, anda bisa melakukan proses pencarian, tambah, edit, hapus buku.

Langkah 24:
Pada window Tambah Transaksi. Anda dapat melakukan proses tambah, edit, hapus transaksi item pada buku yang hendak dibeli. Berikut adalah contoh gambarnya :

Langkah 25:
Bila telah selesai, simpan transaksi atau membatalkannya. Namun apabila anda menekan tombol Simpan Transaksi, Anda dapat melakukan Cetak Transaksi dengan menekan tombol Cetak Transaksi. Tampilan Cetak Transaksi dapat dilihat gambar dibawah ini.

Mohon maaf klu codingnya kurang komentar,,
Moga bermanfaat ya,,

Siapkan databasenya dan Tabelnya

badi@localhost ~]$ mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 32
Server version: 5.1.32 Source distribution

Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.

mysql> use simpeg;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select * from pegawai;
+-------+-----------------------+--------+------+-------+
| NIP | NAMA | ALAMAT | SEKS | AGAMA |
+-------+-----------------------+--------+------+-------+
| 10002 | Endang Susilowati sss | Madiun | P | ISLAM |
| 10003 | Made Saputra | Bali | L | HINDU |
| 10004 | Bejo | Bantul | L | BUDHA |
+-------+-----------------------+--------+------+-------+
3 rows in set (0.00 sec)

Membuat Program Koneksi dalam Kelas

 Lihat contoh program berkut :

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package jdbc1a;
import java.sql.*;
import javax.swing.*;
/*****************************************
*
* @author badiyanto
* STMIK AKAKOM Yogyakarta
*******************************************/
public class KoneksiDb {
public Connection conn;
public Statement st;
public ResultSet rs;
// Fungsi koneksi
public void koneksi()
{
// memangil fungsi konek() untuk melakukan koneksi
konek("localhost","simpeg","root","");
}
// Program untuk melakukan koneksi
public void konek(String server,String db, String user,String passwd){
System.out.println("Keterangan");
//memanggil driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println(
"Ada kesalahan Driver ODBC tidak barhasil Load");
e.printStackTrace();
return;
}
System.out.println("Mysql JDBC Driver berhasil di Load");
conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://"+
server+":3306/"+db,user,passwd);
} catch (SQLException e) {
System.out.println("Tidak bisa koneksi ke database");
e.printStackTrace();
return;
}
if (conn != null)
System.out.println("Berhasil Koneksi!");
else
System.out.println("Koneksi Gagal........ !");
}
 // program mengisikan kombobox
public void IsiKombo(JComboBox kombo, String tabel, String isi, String urut ){
koneksi();
String sql="SELECT "+isi+" as hasil FROM "+tabel+" ORDER BY "+urut;
kombo.removeAllItems();
try
{
st = conn.createStatement();
rs = st.executeQuery(sql);
}
catch (SQLException e){
return;
}
try{
while (rs.next())
{
kombo.addItem(rs.getString("hasil").toString());
}
rs.close();
st.close();
}
catch (SQLException e){
return;
}
}
// Program mencari data dengan kunci
public String CariData(String tabel, String fHasil, String fKunci, String fCari ){
String hs="";
String sql="SELECT "+fHasil+" as hasil FROM "+tabel+" WHERE "+fKunci+"='"+fCari+"'";
koneksi();
try
{
st = conn.createStatement();
rs = st.executeQuery(sql);
}
catch (SQLException e){
return("");
}
try{
while (rs.next())
{
hs = rs.getString("hasil").toString();
}
rs.close();
st.close();
}
catch (SQLException e){
return("");
}
return(hs);
}
// Program menampilkan isikombo
public void CariIsiKombo(JComboBox k,String c){
int i=0;
int ketemu=0;
while (i<=k.getItemCount()-1 )
{
if (c.equals(k.getItemAt(i).toString()))
{
ketemu=i;
}
i++;
}
k.setSelectedIndex(ketemu);
}
}
 
Rancangan Form untuk input data

Buatlah seperti rancangan berikut :

<!-- @page { margin: 0.79in } P { margin-bottom: 0.08in } A:link { so-language: zxx } -->

Kode Program :

package jdbc1a;
import java.sql.*;
/****************************************
*
* @author badiyanto
* STMIK AKAKOM Yogyakarta
*******************************************/
public class NewJFrame1 extends javax.swing.JFrame {
KoneksiDb x; //deklarasi kelas
/** Creates new form NewJFrame1 */
public NewJFrame1() {
initComponents();
x = new KoneksiDb();
x.koneksi(); //panggil koneksi
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*
*/
public void konek(String server,String db, String user,String passwd){
System.out.println("Keterangan");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Driver JDBC tidak barhasil Load");
e.printStackTrace();
return;
}
System.out.println("Driver berhasil di Load");
x.conn = null;
try {
x.conn = DriverManager.getConnection(
"jdbc:mysql://"+server+":3306/"+db,user,passwd);
} catch (SQLException e) {
System.out.println("Tidak bisa koneksi ke database");
e.printStackTrace();
return;
}
if (x.conn != null)
System.out.println("Berhasil Koneksi!");
else
System.out.println("Koneksi Gagal........ !");
}
private void jButtonSimpanMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String nip,nama,alamat,jk,agama,sql;
nip = jTextFieldNip.getText();
nama =jTextFieldNama.getText();
alamat=jTextFieldAlamat.getText();
if (nip.equals("") )
{
System.out.println("Nip tidak boleh kosong");
jTextFieldNip.requestFocus();
return;
}
if (nama.equals(""))
{
System.out.println("Nama tidak boleh kosong");
jTextFieldNama.requestFocus();
return;
}
if (jRadioButton1.isSelected()==true)
jk ="L";
else
jk="P";
agama=jComboBoxAgama.getItemAt(
jComboBoxAgama.getSelectedIndex()).toString();
sql="INSERT INTO pegawai(nip,nama,alamat,seks,agama) VALUES "+
"('"+nip+"','"+nama+"','"+alamat+"','"+jk+"','"+agama+"')";
jTextField1.setText(sql);
try
{
x.st = x.conn.createStatement();
x.st.execute(sql);
}
catch (SQLException e){
System.out.println("Penyimpanan Gagal ");
return;
}
System.out.println("Data sudah tersimpan!");
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButtonSimpan;
private javax.swing.JComboBox jComboBoxAgama;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextFieldAlamat;
private javax.swing.JTextField jTextFieldNama;
private javax.swing.JTextField jTextFieldNip;
// End of variables declaration
}

Mengubah Rekaman

Buatlah rancangan berikut :

Kode Program :

/*
* NewJFrame2.java
*
* Created on May 22, 2011, 9:27:12 PM
*/
package jdbc1a;
import java.sql.*;
/***************************************
*
* @author badiyanto
* STMIK AKAKOM Yogyakarta
*******************************/
public class NewJFrame2 extends javax.swing.JFrame {
KoneksiDb x;
/** Creates new form NewJFrame2 */
public NewJFrame2() {
initComponents();
x = new KoneksiDb();
x.koneksi();
}
private void jButtonSimpanMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String nip,nama,alamat,jk,agama,sql;
nip = jComboBoxNip.getItemAt(jComboBoxNip.getSelectedIndex()).toString();
nama =jTextFieldNama.getText();
alamat =jTextFieldAlamat.getText();
agama =jComboBoxAgama.getItemAt(jComboBoxAgama.getSelectedIndex()).toString();
if (jRadioButton1.isSelected()==true)
jk="L";
else
jk="P";
sql = "UPDATE pegawai SET nama='"+nama+"',"+
"alamat='"+alamat+"',"+
"seks='"+jk+"',"+
"agama='"+agama+"'"+
" WHERE nip='"+nip+"'";
jTextField1.setText(sql);
try {
x.st = x.conn.createStatement();
x.st.execute(sql);
} catch (SQLException e){
System.out.println("Penyimpanan Gagal ");
return;
}
 System.out.println("data sudah tersimpan!");
 }
private void formWindowOpened(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
// Memgisi kombo dengan tidak memanggil fungsi di kelas KonekDB
String sql="SELECT nip FROM pegawai ORDER BY nip";
jTextField1.setText(sql);
jComboBoxNip.removeAllItems();
try
{
x.st = x.conn.createStatement();
x.rs = x.st.executeQuery(sql);
}
catch (SQLException e){
return;
}
try{
while (x.rs.next())
{
jComboBoxNip.addItem(x.rs.getString("nip").toString());
}
x.rs.close();
x.st.close();
}
catch (SQLException e){
return;
}
}
private void jComboBoxNipMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
// Menampilkan data ketika comboNip di Klik
String nip=jComboBoxNip.getItemAt(jComboBoxNip.getSelectedIndex()).toString();
String sql="SELECT * FROM pegawai WHERE nip='"+nip+"';";
try
{
x.st = x.conn.createStatement();
x.rs = x.st.executeQuery(sql);
}
catch (SQLException e){
return;
}
try{
while (x.rs.next())
{
jTextFieldNama.setText(x.rs.getString("nama").toString());
jTextFieldAlamat.setText(x.rs.getString("alamat").toString());
if (x.rs.getString("seks").equals("L"))
jRadioButton1.setSelected(true);
else
jRadioButton2.setSelected(true);
int i=0;
int ketemu=0;
while (i<=jComboBoxAgama.getItemCount()-1 )
{
if (x.rs.getString("agama").equals(
jComboBoxAgama.getItemAt(i).toString()))
{
ketemu=i;
}
i++;
}
jComboBoxAgama.setSelectedIndex(ketemu);
}
x.rs.close();
x.st.close();
}
catch (SQLException e){
return;
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame2().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButtonSimpan;
private javax.swing.JComboBox jComboBoxAgama;
private javax.swing.JComboBox jComboBoxNip;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextFieldAlamat;
private javax.swing.JTextField jTextFieldNama;
// End of variables declaration
}
Menghapus Rekaman
Rancangan Form Berikut :
Kode Program<!-- @page { margin: 0.79in } P { margin-bottom: 0.08in } -->
/***********************************************
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/************************************************
/***********************************************
* NewJFrame3.java
*
* Created on May 30, 2011, 9:28:42 PM
***********************************************/
package jdbc1a;
import java.sql.*;
import javax.swing.JOptionPane;
/*********************************************
*
* @author badiyanto
* STMIK AKAKOM Yogyakarta
*********************************************/
public class NewJFrame3 extends javax.swing.JFrame {
KoneksiDb y;
/** Creates new form NewJFrame3 */
public NewJFrame3() {
initComponents();
y=new KoneksiDb();
y.koneksi();
}
/** This method is called from within the constructor to
private void formWindowOpened(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
// memanggil fungsi kosongkan isian
kosongkan();
}
private void jComboBoxNipMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String nip=jComboBoxNip.getItemAt(jComboBoxNip.getSelectedIndex()).toString();
///menampilkan isian dengan memanggil fungsi y.Caridata(......);
jTextFieldNama.setText(y.CariData("pegawai","nama","nip", nip));
jTextFieldAlamat.setText(y.CariData("pegawai","alamat","nip", nip));
if (y.CariData("pegawai","seks","nip", nip).equals("L"))
jRadioButton1.setSelected(true);
else
jRadioButton2.setSelected(true);
y.CariIsiKombo(jComboBoxAgama,y.CariData("pegawai","agama","nip", nip).toString());
}
//proses menghapus rekaman//
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String nip=jComboBoxNip.getItemAt(jComboBoxNip.getSelectedIndex()).toString();
// dialog konfirmasi //
int jawab=JOptionPane.showConfirmDialog(this,"Anda yakin ingim menghapus data ini","Konfimasi",JOptionPane.YES_NO_OPTION);
if (jawab == 0)
{
try
{
y.st = y.conn.createStatement();
y.st.execute("DELETE FROM pegawai WHERE nip='"+nip+"'");
}
catch (SQLException e){
System.out.println("Gagal mengapus Gagal ");
return;
}
System.out.println("Data Berhasil dihapus!");
kosongkan();
}
}
void kosongkan()
{
jTextFieldAlamat.setText("");
jTextFieldNama.setText("");
jRadioButton1.setSelected(false);
jRadioButton2.setSelected(false);
jComboBoxAgama.setSelectedIndex(0);
jComboBoxNip.requestFocus();
y.IsiKombo(jComboBoxNip,"pegawai","nip", "nip");
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame3().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JComboBox jComboBoxAgama;
private javax.swing.JComboBox jComboBoxNip;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JTextField jTextFieldAlamat;
private javax.swing.JTextField jTextFieldNama;
// End of variables declaration
}

Membuat Form dengan HTML

di bawah ini dari membuat form dengan HTML adalah kode HTML:


br />

<body> <br />

<form><span><br />

<table cols=2 border=”0″><center>

FORM REGISTRASI

</center>

<tr>

<td> Nama Anda : <br />

<td>  <br />

<input type=”text” name=”textbiasa”>  <br />

</tr><br />

<br />

<br />

<tr>       <br />

<td> Password Anda : <br />

<td> <br />

<input type=”password” name=”textpassword”> <br />

</tr><br />

<br />

<br />

<tr> <br />

<td> Jenis Kelamin : <br />

<td> <br />

<input type=”radio” name=”pilihan” value =”M”> Laki-laki  <br />

<td> <br />

<input type=”radio” name=”pilihan” value=”F”> Perempuan <br />

<br />

</tr><br />

<br />

<tr> <br />

<td> Binatang Kesayangan <br />

<td> <br />

<select name=”BinatangKesayangan”size=”1″> <br />

<option value=”Kcng”>Kucing <br />

<option value=”Klnc”>Kelinci <br />

<option value=”Hmst”>Hamster <br />

<option value=”Sp”>Sapi <br />

<option value=”Hrm”>Harimau <br />

</select> <br />

<br />

</tr><br />

<br />

<tr> <br />

<td> <br />

<input type=”submit”value= “Kirimkan Data”> <br />

<td> <br />

<input type=”reset” value=”Hapus Formulir”> <br />

<br />

</tr><br />

<br />

</table><br />

</form><br />

</body> <br />

Menghitung Umur

ini adalah kode program dari Menghitung Umur dengan menggunakan ConsoleApplication di Visual Studio C# 2005:

using System;
using System.Collections.Generic;
using System.Text;

namespace Menghitung_Umur
{
class Program
{
public static void Main(string[] args)
{
int day;
int month;
int year;

Console.Out.WriteLine(“Menghitung Umur “);
Console.Out.WriteLine(“====================”);
try
{
Console.Out.Write(“Masukkan Tanggal: “);
day = Convert.ToInt32(Console.In.ReadLine());
Console.Out.Write(“Masukkan Bulan: “);
month = Convert.ToInt32(Console.In.ReadLine());
Console.Out.Write(“Masukkan Tahun : “);
year = Convert.ToInt32(Console.In.ReadLine());
DateTime birthDate = new DateTime(year, month, day);
DateTime today = DateTime.Now;
TimeSpan age = today.Subtract(birthDate);
Console.Out.WriteLine(“Saat ini umur anda adalah: {0} hari, {1} jam, ”
+ “{2} minutes.”, age.Days, age.Hours, age.Minutes);
}

catch (FormatException e)
{
Console.Out.WriteLine(“Data tanggal, bulan dan tahun harus berupa angka.”);
}

catch (Exception e)
{
Console.Out.WriteLine(“Terjadi kesalahan: ” + e.Message);
}

}
}
}

Selamat Mencoba,
Ridon-Na70

Email ThisBlogThis!Share to TwitterShare to Facebook

Posted By Ridon Jan Antoro Napitupulu

Link ke posting ini Label: Pemrograman Berorientasi Objek

Membuat Kalkulator Sederhana dengan operator +, -, /, *

ini kode program dengan menggunakan Visual Studio C# 2005, yakni dengan menggunakan
Windows Application:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Calculator
{
public partial class frm_Calculator : Form
{
public frm_Calculator()
{
InitializeComponent();
}

private void btn_tambah_Click(object sender, EventArgs e)
{
double bil1;
double bil2;
double total;

bil1 = double.Parse(txt_bil1.Text);
bil2 = double.Parse(txt_bil2.Text);

total = bil1 + bil2;
lbl_cetak.Text = total.ToString();
}

private void btn_kurang_Click(object sender, EventArgs e)
{

double bil1;
double bil2;
double total;

bil1 = double.Parse(txt_bil1.Text);
bil2 = double.Parse(txt_bil2.Text);

total = bil1 – bil2;
lbl_cetak.Text = total.ToString();
}

private void btn_bagi_Click(object sender, EventArgs e)
{

double bil1;
double bil2;
double total;

bil1 = double.Parse(txt_bil1.Text);
bil2 = double.Parse(txt_bil2.Text);

total = bil1 / bil2;
lbl_cetak.Text = total.ToString();
}

private void btn_kali_Click(object sender, EventArgs e)
{

double bil1;
double bil2;
double total;

bil1 = double.Parse(txt_bil1.Text);
bil2 = double.Parse(txt_bil2.Text);

total = bil1 * bil2;
lbl_cetak.Text = total.ToString();
}

private void btn_clear_Click(object sender, EventArgs e)
{
txt_bil1.Text = “”;
txt_bil2.Text = “”;
}

}
}
Nb:
Teman2 mulai mengetik kode program mulai dari btn_tambah_Click sampai btn_clear_Click

Keterangan dari tombol-tombol yang digunakan:

1. txt_bil1 adalah textbox buat bil1
2. txt_bil2 adalah textbox buat bil2
3. btn_tambah adalah button dari +
4. btn_kurang adalah button dari –
5. btn_bagi adalah button dari /
6. btn_kali adalah button dari *
7. btn_clear adalah button dari clear

Selamat Mencoba,

Komentar
  1. lutfia mengatakan:

    makasi atas informasinya cozzzzz

  2. markon mengatakan:

    jempol aja deh

  3. Adit mengatakan:

    enak an ketemu langsung ama yang punya ckckckckkc

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s