Bagi yang pengen membuat calculator dengan menggunakan bahasa java silahkan download sorce code nya disini:
http://www.ziddu.com/download/8242962/calculator.rar.html
Aplikasi ini dibuat dengan menggunakan NetBeans.
Selamat Berkreasi
Calculator dengan Java - NetBeans
by Son Rokhaniawan Perdata, S.T | 2:15 PM in Java, Netbeans, Project | comments (0)
GlassFish Project - Java Persistence Example
by Son Rokhaniawan Perdata, S.T | 12:30 AM in Project | comments (0)
Overview
This is a very simple example that uses only 2 entities - a Customer and an Order, with OneToMany relationships between them. The Customer and the Order classes are Plain Old Java Classes (POJOs). These classes, as well as the code that manipulates POJO instances, can be used without any changes in Java SE or Java EE environment.
Accessing an EntityManagerFactory and an EntityManager depends on the environment and is described in more details below.
We will create a customer and two related orders, find the customer, and navigate from the customer to its orders, and then merge and remove all the objects. All these operation will be performed using Java Persistence API and require JDK 5.0.
Click here to get the ZIP file with the complete Java SE example as a netbeans project. This example works with Java DB or with Oracle.
Click here to get the ZIP file with the complete Java SE example. This example works with Oracle.
Click here to get the ZIP file with the complete Java EE example.
Refer to Java Persistence API document of JSR-220: Enterprise JavaBeansTM 3.0 Specification for further details on annotations and APIs.
Check example sources for the necessary import statements.
Mapping to Existing Tables
In the first example we will use only two tables:| CUSTOMER |
| ID |
| NAME |
| ORDER_TABLE |
| ORDER_ID |
| SHIPPING_ADDRESS |
| CUSTOMER_ID |
CUSTOMER_ID column in the ORDER_TABLE is the Foreign Key (FK) to the ID column from the CUSTOMER table. The files sql/tables_oracle.sql and sql/tables_derby.sql in the example contains DDL to create both tables for Oracle and Apache Derby.
POJO Classes
Now let's look at the corresponding persistence classes. Both entities in this example use property based persistence. There is no access annotation element on the entity, so it defaults to access=PROPERTY. This is the reason why @Column annotation is specified for the get methods and not for the fields. The classes that are used as an argument or a return type between a remote client and a container must implement java.io.Serializable interface.The POJO classes in the examples belong to an entity package.
Customer
The Customer entity is mapped to the CUSTOMER table, and looks like this:@Entity
public class Customer {
private int id;
private String name;
private Collection orders;
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(cascade=ALL, mappedBy="customer")
public Collection getOrders() {
return orders;
}
public void setOrders(Collection newValue) {
this.orders = newValue;
}
}
Note that there are no @Table and @Column annotations. This is possible because the persistence provider will use the default rules to calculate those values for you. See chapter 9 of the Java Persistence API Specification for detailed rules of the mapping annotations.
Order
The Order entity is mapped to the ORDER_TABLE table. It requires both @Table and @Column mapping annotations because table and column names do not match class and properties names exactly. @Column annotations are specified for the corresponding get methods:@Entity
@Table(name="ORDER_TABLE")public class Order {
private int id;
private String address;
private Customer customer;
@Id
@Column(name="ORDER_ID") public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="SHIPPING_ADDRESS") public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@ManyToOne()
@JoinColumn(name="CUSTOMER_ID")
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
Note that Customer and Order have bidirectional relationships between the entities.
Persisting POJO Entities
Now, let's create new instances, set up the relationships and persist all of them together using the CASCADE option that we set on the Customer entity. This code must be executed in a context of an active transaction.
// Create new customer
Customer customer0 = new Customer();
customer0.setId(1);
customer0.setName("Joe Smith");
// Persist the customer
em.persist(customer0);
// Create 2 orders
Order order1 = new Order();
order1.setId(100);
order1.setAddress("123 Main St. Anytown, USA");
Order order2 = new Order();
order2.setId(200);
order2.setAddress("567 1st St. Random City, USA");
// Associate orders with the customer.
Note that the association must be set on both sides of the relationship: on the customer side for the orders to be persisted when transaction commits, and on the order side because it is the owning side:
customer0.getOrders().add(order1);
order1.setCustomer(customer0);
customer0.getOrders().add(order2);
order2.setCustomer(customer0);
When this transaction commits, all three entities will be persisted in the database.Query and Navigation
We'll use a new EntityManager to do the query, but will execute the query without an active transaction:// Create new EntityManager
em = emf.createEntityManager();
Query q = em.createQuery("select c from Customer c where c.name = :name");
q.setParameter("name", "Joe Smith");
Our query is supposed to return a single customer, so we will use the Query method getSingleResult() to execute the query. This method would throw an exception if there is no or more than one matching customers.
Customer c = (Customer)q.getSingleResult();Now let's verify that the orders were also created by navigating from the Customer.
You can print the orders, but we'll just check the size:
Collection orders = c.getOrders();
if (orders == null || orders.size() != 2) {
throw new RuntimeException("Unexpected number of orders: "
+ ((orders == null)? "null" : "" + orders.size()));
} Merge and Removal of Persistent Instances
To remove an instance, it must be managed by this EntityManager. The code below uses a customer 'c' that had been detached from its persistence context. Removal of the Customer also removes related orders because of the CASCADE option set on the corresponding relationship. This code must be executed in a context of an active transaction. // Merge the customer to the new persistence context
Customer c0 = em.merge(c);
Note that merge() is not a void operation. It returns back a managed copy of the argument (and its related objects). Only this copy can be used for EntityManager operations.
// Delete all records
em.remove(c0);
Putting It All Together
Using in Java SE
First, we need to create an EntityManagerFactory that we will use in the example. An EntityManagerFactory is created once for each PersistentUnit. Persistent unit in this example is called "pu1". // Create EntityManagerFactory for persistent unit named "pu1"
// to be used in this test
emf = Persistence.createEntityManagerFactory("pu1");For each business method in the example, a new EntityManager is created:
// Create new EntityManager
em = emf.createEntityManager();
If a transaction required, it is started: // Begin transaction
em.getTransaction().begin();
And then the business logic is executed in a separate business method:// Business logicmybusinessmethod(...);If transaction has been started it must be committed:
// Commit the transaction
em.getTransaction().commit();
And EntityManager should always be closed if it won't be used again: // Close this EntityManager
em.close();
Java SE client code in this example is located in the class client.Client.To run the test, you need to create META-INF/persistence.xml file in the classpath. Copy META-INF/persistence.xml.template file from the classes directory in the example to META-INF/persistence.xml and populate the values of the corresponding properties with the database settings that you are using. Note that persistence-unit name is set to "pu1" and all entity classes are explicitly listed.
Add your database driver and classes directory from the unzipped example to the classpath, load the tables into the database, then run:
java -javaagent:${glassfish.home}/lib/toplink-essentials-agent.jar client.Client
Using the Java SE Example in Netbeans
- Download Netbeans 5.5 and install the bundle
- Download and install Java DB/Derby if you plan on using Java DB/Derby instead of Oracle.
- Configure Netbeans to use Java DB/Derby by following the steps in this tutorial .
- Install the JAVA SE Persistence Example project .
Configuring the JDBC driver
To configure the JDBC driver to be used when running the project, right-click on the project, select properties. Click on the libraries and then click on the 'Add JAR/Folder' button to add the jars for the JDBC driver being used. In the example below, the Java DB/Derby JDBC Client Driver is added.
Creating the tables
Scripts are provided to create the tables needed for the example for either Java DB/Derby or Oracle.
Note:If you are using Oracle, go to the runtime tab, click databases and then right click drivers to add the Oracle driver so that it can be used with the SQL Editor.
- Create a connection to the database
- expand the drivers folder and right click on the Oracle or Java DB/Derby driver and create a connection to the database. For Java DB/Derby you can enter: jdbc:derby://localhost:1527/testDB;create=true and enter APP for the username and password.
- If you are using Java DB/Derby and the server is not started, Select Tools->Java DB Database ->Start Java DB server
- Open the appropriate sql script by typing Ctrl-O or selecting 'Open File' from the file menu. The SQL scripts are in the sql directory of the project.
- Select the connection to use (for Java DB/Derby you can use jdbc:derby://localhost:1527/testDB;create=true [APP on APP] .
- Click the Run SQL icon
on the right of the Connection drop-down box. This will open the Connect dialog. Enter the password for your connection. . Click OK to connect and run the SQL script.
Configuring the persistence unit
To configure the persistence unit for the sample, click on source packages and then click on META-INF. Double click on persistence.xml. Your configuration should look like the following if you are using Java DB/Derby:
Running the project:
To run the the sample application. Right click on the project and select 'Run Project'.
Using in Java EE
In a Java EE container, the client code will not create an EntityManagerFactory - it is done by the container.There are several option to get a hold of an EntityManager:
- An EntityManagerFactory or an EntityManager can be injected by the container or looked up in JNDI.
- An EntityManager instance can be acquired from an EntityManagerFactory via the corresponding API call.
- A JTA EntityManager participates in the current JTA transaction that is either controlled by the container or by a user via javax.transaction.UserTransaction API.
- A resource-local EntityManager uses the same Java Persistence API as in Java SE environment to control its transactions.
@PersistenceContext(unitName="pu1")
private EntityManager em;Transaction boundaries set to container-managed defaults.
The client code from the Java SE example is now divided between a Stateless Session Bean ejb.TestBean (implements ejb.Test remote business interface), which contains the business logic (i.e. exactly the same business methods as the Java SE client), and an application client client.AppClient that calls the corresponding methods and prints the output:
// Persist all entities
System.out.println("Inserting Customer and Orders... " + sb.testInsert());
// Test query and navigation
System.out.println("Verifying that all are inserted... " + sb.verifyInsert());
// Get a detached instance
Customer c = sb.findCustomer("Joe Smith");
// Remove all entities
System.out.println("Removing all... " + sb.testDelete(c));
// Query the results
System.out.println("Verifying that all are removed... " + sb.verifyDelete());In the Java EE environment META-INF/persistence.xml does not need to list persistence classes, or the
To test the example, unzip it and deploy ex1-ee.ear file:
${glassfish.home}/bin/asadmin deploy --retrieve . ex1-ee.ear
Then execute the appclient script:
${glassfish.home}/bin/appclient -client ./ex1-eeClient.jar -mainclass client.AppClient
The Result
This is the output (after several extra log messages) that will be printed:Inserting Customer and Orders... OK
Verifying that all are inserted... OK
Removing all... OK
Verifying that all are removed... OKpackage testing; Then remakes one class at same package
Swing is one of technology in Java to make one application desktop. This following I load one simple example with swing. One calculator plain. I utilize two numbers class. Class first is that of penampil frame and class second is program from that calculator is alone.
Its example following:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/**
*
* @author bagus
*/
public class SwingCalculator {
public static void main(String[] args) {
JFrame frame = new Calculator();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/**
*
* @author bagus
*/
class Calculator extends JFrame {
private final Font BIGGER_FONT = new Font("monspaced", Font.PLAIN, 20);
private JTextField textfield;
private boolean number = true;
private String equalOp = "=";
private CalculatorOp op = new CalculatorOp();
public Calculator() {
textfield = new JTextField("0", 12);
textfield.setHorizontalAlignment(JTextField.RIGHT);
textfield.setFont(BIGGER_FONT);
ActionListener numberListener = new NumberListener();
String buttonOrder = "1234567890 ";
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < buttonOrder.length(); i++) {
String key = buttonOrder.substring(i, i+1);
if (key.equals(" ")) {
buttonPanel.add(new JLabel(""));
} else {
JButton button = new JButton(key);
button.addActionListener(numberListener);
button.setFont(BIGGER_FONT);
buttonPanel.add(button);
}
}
ActionListener operatorListener = new OperatorListener();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 4, 4));
String[] opOrder = {"+", "-", "*", "/","=","C"};
for (int i = 0; i < opOrder.length; i++) {
JButton button = new JButton(opOrder[i]);
button.addActionListener(operatorListener);
button.setFont(BIGGER_FONT);
panel.add(button);
}
JPanel pan = new JPanel();
pan.setLayout(new BorderLayout(4, 4));
pan.add(textfield, BorderLayout.NORTH );
pan.add(buttonPanel , BorderLayout.CENTER);
pan.add(panel , BorderLayout.EAST );
this.setContentPane(pan);
this.pack();
this.setTitle("Calculator");
this.setResizable(false);
}
private void action() {
number = true;
textfield.setText("0");
equalOp = "=";
op.setTotal("0");
}
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (number) {
action();
textfield.setText("0");
} else {
number = true;
String displayText = textfield.getText();
if (equalOp.equals("=")) {
op.setTotal(displayText);
} else if (equalOp.equals("+")) {
op.add(displayText);
} else if (equalOp.equals("-")) {
op.subtract(displayText);
} else if (equalOp.equals("*")) {
op.multiply(displayText);
} else if (equalOp.equals("/")) {
op.divide(displayText);
}
textfield.setText("" + op.getTotalString());
equalOp = e.getActionCommand();
}
}
}
class NumberListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String digit = event.getActionCommand();
if (number) {
textfield.setText(digit);
number = false;
} else {
textfield.setText(textfield.getText() + digit);
}
}
}
public class CalculatorOp {
private int total;
public CalculatorOp() {
total = 0;
}
public String getTotalString() {
return ""+total;
}
public void setTotal(String n) {
total = convertToNumber(n);
}
public void add(String n) {
total += convertToNumber(n);
}
public void subtract(String n) {
total -= convertToNumber(n);
}
public void multiply(String n) {
total *= convertToNumber(n);
}
public void divide(String n) {
total /= convertToNumber(n);
}
private int convertToNumber(String n) {
return Integer.parseInt(n);
}
}
}
Its output result is as follows:
Create Database with Netbeans Program and Ms.Access
by Son Rokhaniawan Perdata, S.T | 11:32 PM in Database, Project | comments (0)
Hi all readers, this project we will create a database program using Netbeans IDE 6.5 Database and Ms.Access. Software may Netbeans is new for us. Yes the actual program Netbeans is a software used to create a program based on JAVA. We still use the first appearance of white Notepad to create JAVA applications. Akan NotePad but parallel development is replaced by slow start because TEXTPAD facilities provided by this TEXTPAD seems more complete and informative than the notepad. But when we look kebelakang shortages have appeared TEXTPAD again, that is we still have to type the script to make the program components. And that lack is covered by the Netbeans this. Namely to provide component parts without having to type the script to make the withdrawal other GUI Programming Languages. You can create our new project, we:
Here the view that the program will be created:
The Steps:
***> Create database tables and cooperation with the Member as follows:
==================================================================
Noang - Text - 5
Nama - Text - 25
Alamat - Text - 30
Jkel - Yes/no
Agama - Text - 1
NoKTP - Text - 15
NoTelp - Text - 12
Simpanan - Number - LongInt
============================================================1. Create a design form as shown in the picture. In the form there is a component JTextField, JComboBox, JRadioButton, JPanel, JButton.
2. Change the name of the components that we have entered, especially for components JTextField, JComboBox, JButton, JRadioButton engan way and conditions as follows:
Component Component Name Changes
JTextField No Anggota — no
JTextField Nama — nama
JTextField Alamat — alamat
JComboBox Agama — agama
JRadioButton Jkel — RPria dan RWanita
JTextField No KTP — noktp
JTextField No. Telp — notelp
JTextField Simpanan — simpanan
JButton Simpan — bsimpan
JButton Data Baru — bbaru
JButton Keluar — bkeluar
3. After you change the name of each component so it's time to process incoming Coding.
Program Code:
- Below the tab name of your project, click the source:
Under the package type you import the following command to retrieve the sql commands.
=======================================================
import java.sql;
=======================================================
- The declaration of a variable connection, resultset, statement and the other variables that are required
Public under the following class type variables;
=======================================================
//deklarasi variabel global
Connection Con;
ResultSet RsAng;
Statement StatAng;
//variabel for agama
String sagm = “1″;
//variabel for jenis kelamin
Boolean bjkel = true;
//variabel global where data ditemukan
Boolean ada = false;
- Then, under public nama_project (under the introduction of a variable) type the command database connection and table below:
//connection
try
{
String fdata = “z:\\java1\\NetBeans\\Koperasi.mdb”;
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);
// direct connection to the database without dsn
Con= DriverManager.getConnection(”jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=” + fdata);
//shows the search process can be in the resultset update
StatAng= Con.createStatement( RsAng.TYPE_SCROLL_SENSITIVE, RsAng.CONCUR_UPDATABLE );
RsAng = StatAng.executeQuery(”Select* from Anggota”);
}
catch(Exception e)
{ System.err.println(”Conection error !” + e.getMessage()); } //getMessage to display the message
- After the connection is successful then the time we go to the key store. Type the following code:
================================================== ====
private void bsimpanActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try
{
RsAng.updateString(”Noang”, no.getText());
RsAng.updateString(”Nama”, nama.getText());
RsAng.updateString(”Alamat”, alamat.getText());
RsAng.updateString(”Agama”, sagm);
RsAng.updateBoolean(”Jkel”, bjkel);
RsAng.updateString(”NoKTP”, noktp.getText());
RsAng.updateString(”NoTelp”, notelp.getText());
RsAng.updateDouble(”Simpanan”, Double.parseDouble(simpanan.getText()));
if(ada)
{
//mengedit data yang sudah ada
RsAng.updateRow();
javax.swing.JOptionPane.showMessageDialog(null, “Data Telah Diedit !”);
}
else
//menyisipkan record baru
RsAng.insertRow();
javax.swing.JOptionPane.showMessageDialog(null, “Data Telah Tersimpan !”);
}
catch(Exception e)
{
javax.swing.JOptionPane.showMessageDialog(null, “Data Belum Tersimpan !” + e.getMessage());
}
}
======================================================- Code Programs for RadioButton Male:
======================================================
private void RPriaActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
bjkel = true;
}
======================================================- Code Programs for Women's RadioButton:
======================================================
private void RWanitaActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
bjkel = false;
}
=====================================================- To type a ComboBox in the code the program:
=====================================================
private void agamaActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Baca Source objectnya masih JcomboBox
javax.swing.JComboBox soagama = (javax.swing.JComboBox)evt.getSource();
//Membaca Item Yang Terpilih — > String
String sagama = (String)soagama.getSelectedItem();
//pengujian sagama
if (sagama.equals(”Islam”))
sagm = “1″;
else if (sagama.equals(”Kristen”))
sagm = “2″;
else if (sagama.equals(”Hindhu”))
sagm = “3″;
else if (sagama.equals(”Budha”))
sagm = “4″;
else if (sagama.equals(”Konghu Chu”))
sagm = “5″;
}
==========================================================================================================
private void bbaruActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
no.setText(”");
nama.setText(”");
alamat.setText(”");
noktp.setText(”");
notelp.setText(”");
simpanan.setText(”");
}
=====================================================- To Exit Button component type in the code the program:
=====================================================
private void bkeluarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//Tutup Koneksi
try
{
Con.close();
RsAng.close();
StatAng.close();
Con = null; RsAng = null; StatAng = null;
}
catch (Exception e){}
System.exit(0);
}
====================================================Additional notes (rusted Bos)
- To fill the ComboBox religion you click on the ComboBox component on the properties and religious search model, then click the dialog box will appear as follows:
NetBeans IDE Java Quick Start Tutorial (Hello Word)
by Son Rokhaniawan Perdata, S.T | 11:10 AM in Netbeans, Project, Tutorial | comments (0)
This tutorial provides a very simple and quick introduction to the NetBeans IDE workflow by walking you through the creation of a simple "Hello World" Java console application. Once you are done with this tutorial, you will have a general knowledge of how to create and run applications in the IDE.
This tutorial takes less than 10 minutes to complete.
After you finish this tutorial, you can move on to the learning trails, which are linked from the Documentation, Training & Support page. The learning trails provide comprehensive tutorials that highlight a wider range of IDE features and programming techniques for a variety of application types. If you do not want to do a "Hello World" application, you can skip this tutorial and jump straight to the learning trails.
To complete this tutorial, you need the following software and resources.
| Software or Resource | Version Required |
|---|---|
| NetBeans IDE | version 6.5 |
| Java Development Kit (JDK) | version 6 or version 5 |
Setting Up the Project
To create an IDE project:
- Start NetBeans IDE.
- In the IDE, choose File > New Project (Ctrl-Shift-N), as shown in the figure below.
New Project menu item selected." class="margin-around" height="85" width="199">
- In the New Project wizard, expand the Java category and select Java Application as shown in the figure below. Then click Next.
- In the Name and Location page of the wizard, do the following (as shown in the figure below):
- In the Project Name field, type
HelloWorldApp. - Leave the Use Dedicated Folder for Storing Libraries checkbox unselected.
- In the Create Main Class field, type
helloworldapp.HelloWorldApp. - Leave the Set as Main Project checkbox selected.
- In the Project Name field, type
- Click Finish.
The project is created and opened in the IDE. You should see the following components:
- The Projects window, which contains a tree view of the components of the project, including source files, libraries that your code depends on, and so on.
- The Source Editor window with a file called
HelloWorldAppopen. - The Navigator window, which you can use to quickly navigate between elements within the selected class.
- The Tasks window, which lists compilation errors as well other tasks that are marked with keywords such as XXX and TODO.
Adding Code to the Generated Source File
Because you have left the Create Main Class checkbox selected in the New Project wizard, the IDE has created a skeleton class for you. You can add the "Hello World!" message to the skeleton code by replacing the line:
// TODO code application logic herewith the line:
System.out.println("Hello World!");
Save the change by choosing File > Save.
The file should look something like the following code sample.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package helloworldapp;
/**
*
* @author Patrick Keegan
*/
public class HelloWorldApp {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Compiling and Running the Program
Because of the IDE's Compile on Save feature, you do not have to manually compile your project in order to run it in the IDE. When you save a Java source file, the IDE automatically compiles it.
To run the program:
- Choose Run > Run Main Project (F6).
The next figure shows what you should now see.
Congratulations! Your program works!
If there are compilation errors, they are marked with red glyphs in the left and right margins of the Source Editor. The glyphs in the left margin indicate errors for the corresponding lines. The glyphs in the right margin show all of the areas of the file that have errors, including errors in lines that are not visible. You can mouse over an error mark to get a description of the error. You can click a glyph in the right margin to jump to the line with the error.
Building and Deploying the Application
Once you have written and test run your application, you can use the Clean and Build command to build your application for deployment. When you use the Clean and Build command, the IDE runs a build script that performs the following tasks:
- Deletes any previously compiled files and other build outputs.
- Recompiles the application and builds a JAR file containing the compiled files.
To build your application:
- Choose Run > Clean and Build Main Project (Shift-F11).
You can view the build outputs by opening the Files window and expanding the HelloWorldApp node. The compiled bytecode file HelloWorldApp.class is within the build/classes/helloworldapp subnode. A deployable JAR file that contains the HelloWorldApp.class is within the dist node.





