NETBEANS JAVA TUTORIALS FOR BEGINNERS
JAVA Coding simplified
NETBEANS JAVA TUTORIAL FOR BIGINNERS
Manoj A.P
I
used this material for training program of the young and
provid-ed as an additional material for students.These tutorial collections
proved extreamely helpfull for beginners of Java and Netbean
pro-gramming platform.
Anybody who would like to use and distribute this book can find link
to download the current version of this e-book from author’s blog/
twitter accounts. We also love to hear what you are thinking about
this
e-book.
Thank
you,
MANOJ
http://twiitter/manojMelattur
Contents
How to add nodes to a swing tree control in java Netbeans?
5
create database and tables in Java DB/JDB ? 9
Make a Tabbed dialog in Java Netbeans 11
Database programming with Netbeans and Java
12
Play with Tables & views in Java DB
17
Playing with swing ComboBox in Netbeans: Adding an array to
jCombo-Box 19
Utility Classes : Return multiple values using Vectors in Java
21
Develop applications using Netbeans persistence 23
How to use ArrayList in Java to store objects? 25
How to obtain value from an ArrayList into an Array in Java?
27
Functions returning ArrayList in JAVA
28
TreeSets for fast accessing and retrieval of objects in Java. 29
Getting the current date and time 30
Accessing date components with Calendar Object 33
Gregorian calendar and leap year in Java
35
Random numbers and Random class in Java 38
How to use Obervable and Observe Objects 39
How to Schedule a task in Java
43
How to Bind a Swing Table compenent with DB connection Netbeans 45
Binding selected columns of a table into Swing table in NB
46
Observing more than one class and types of changes in those classes. 47
Files and FileNameFilter Interface 52
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
How to add nodes to a swing tree control in java
Netbeans?
A Swing Tree control will be a good option for an application in which users need to select items from a variety of groups. Using a swing Tree component in Netbeans is so easy. If you don’t want touch much of the code you can use the Model property to set up your tree nodes.
Lets begin just another Netbeans Java application
1. Add a Java Project- Java-Java Application (Leave the main class blank)
2. Add a New JFrame Form and Drag the Swing Tree component in Design mode. PLAY WITH MODEL
The Model property of the JTree control let you customize your tree. Netbeans simplifies the use of the Tree and it will look like
Click on the Model property of the tree control and start adding the parent and childs. You can create as many parent and child , just using space before the text you enter. DRESS THE NODES USING THE CODE.
Here we use instance of defaultMutableTreeNode which extends Mutable Node interface. First up all we need the top level note, the root node which is the parent of all the others, then add childs. Finally we add all these to the Jtree1 using the Add method.
Drop the following codes to the constructor of the JFrame form just after init() method.
DefaultMutableTreeNode top=new DefaultMutableTreeNo-de(“Items”);
DefaultMutableTreeNode Juices=new DefaultMutableTreeNo-de(“Juices”);
DefaultMutableTreeNode ic=new DefaultMutableTreeNo-de(“IceCream”);
top.add(ic); // add the “IceCreame” node to the “top” node as child
top.add(Juices);
NETBEANS JAVA TUTORIALS
DefaultMutableTreeNode m=new DefaultMutableTreeNode(“man-go”);
DefaultMutableTreeNode p=new DefaultMutableTreeNo-de(“Pinwapple”);
DefaultMutableTreeNode g=new DefaultMutableTreeNo-de(“Grapes”);
DefaultMutableTreeNode o=new DefaultMutableTreeNo-de(“Orange”);
Juices.add(m); //add “mango” child node to the “Juice” node as child
Juices.add(p);
Juices.add(g);
Juices.add(o);
DefaultMutableTreeNode fs=new DefaultMutableTreeNode(“-Fruit Salad”);
DefaultMutableTreeNode fl=new DefaultMutableTreeNode(“Fa-looda”);
DefaultMutableTreeNode ch=new DefaultMutableTreeNo-de(“Choclate Shake”);
DefaultMutableTreeNode ms=new DefaultMutableTreeNode(“-Misc”);
ic.add(fs);
ic.add(fl);//add “Fruit Salad” to the “IceCreame” node as child.
ic.add(ch);
jTree2.setModel(new DefaultTreeModel(top));
DefaultMutableTreeNode Juices=new DefaultMutableTreeNode(“Juic-es”);
DefaultMutableTreeNode ic=new DefaultMutableTreeNode(“Ice-Cream”);
top.add(ic); // add the “IceCreame” node to the “top” node as child
NETBEANS JAVA TUTORIALS
top.add(Juices);
DefaultMutableTreeNode m=new DefaultMutableTreeNode(“man-go”);
DefaultMutableTreeNode p=new DefaultMutableTreeNode(“Pin-wapple”);
DefaultMutableTreeNode g=new DefaultMutableTreeNode(“Grapes”); DefaultMutableTreeNode o=new DefaultMutableTreeNode(“Or-ange”);
Juices.add(m); //add “mango” child node to the “Juice” node as child
Juices.add(p); Juices.add(g); Juices.add(o);
DefaultMutableTreeNode fs=new DefaultMutableTreeNode(“-Fruit Salad”);
DefaultMutableTreeNode fl=new DefaultMutableTreeNode(“Fa-looda”);
DefaultMutableTreeNode ch=new DefaultMutableTreeNo-de(“Choclate Shake”);
DefaultMutableTreeNode ms=new DefaultMutableTreeNode(“-Misc”);
ic.add(fs);
ic.add(fl);//add “Fruit Salad” to the “IceCreame” node as child.
ic.add(ch);
jTree2.setModel(new DefaultTreeModel(top));
NETBEANS JAVA TUTORIALS
GETTING THE PATH OF THE SELECTION
So how would you get the selection path, it is easy .Drag an addition Label control On the click event of the JTree put these freaky codes.
TreePath tp;
tp=jTree2.getSelectionPath();
DefaultMutableTreeNode t=new DefaultMutableTreeNo-de(tp);
if (t!=null){
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
create database and tables in Java DB/JDB ?
Most of the program require a database ,Java comes up with an inbuilt database called JavaDB. It is an unique SQL data base.Using the service menu you can operate the JDB in Netbeans Java IDE.
Creating your first Database using JavaDB
Access the services window from the package explorer /from Windows menu(Ctrl+5) . Expand Data Base ->JavaDB.
Database Connection in Netbeans
Right click the Java DB and use create database command to create user a n d database.
Create Java DB database
# After the database creation a new connection will appeared in the just below the Driver folder.
Expand the connection node which will list different schema you can use. Schema
Expand one of the schema which will list Tables,Views and Procedures. Lets create the first table
Right click table and using create table command design your first table. Table dialog in Netbeans
Data can be entered to the table from the view data window, where you can also execute SQL queries.(Using the right click of the Table folder you can access the window)
Views
“ Views are the logical tables which may represent only a part of a table.Creating a view in JavaDB is so simple and easy.You can combine tables using the views.
NETBEANS JAVA TUTORIALS
 Right click the views folder use create view window to create view based on the table or a group of tables. Avoid semicolon(;) at the end of the SQL statement.
 Create view dialog
Here is an example based on the product table. View Name: Available Products
select * from product where available=’TRUE’ Procedures
 Using procedures just run few SQL commands.Just right click the folder and select execute command and run.
You can connect and disconnect connection to the database or table using t h e connect/disconnect command.
# *Netbeans is a free Java IDE for developing Java application.Get your copy from Or-acle.com
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Make a Tabbed dialog in Java Netbeans
Java Netbeans , an IDE that simplify the coding for Java application development, provide rich set of visual tools which can be used to design your windows with Swing and AWT containers and components.
Tabbed windows is featured most of application , especially on Windows OS apps.So how do we use the Tabbed forms in Netbeans and Java. Most of the languages like Visual BASIC let us tabbed dialogues with single component. But in Java’s way things becomes different.
Swing provides two types of components containers and con-trols .Containers just hold the concon-trols.In order make tabbed dialog we need a tabbed container and and Internal Frame.
± Start a Java Project and leave the main class blank.
Add a JFrame Form to the project.Go to New - Swing GUI Form - JFrame Form.
Open the Form by double click in the Project - Source Packages - Form.
Drag a Tabbed Pane container to the JFrame Form to the Swing Pallet. No tabs appeared ,isn’t it?
Now drag JInternal Frame from container and it will show up the tab.To change the tab title double click.
In order to arrange controls on the Internal frame use panel container, it let you group items.
# Move between tabs ,using code is pretty simple; ‘SelectedIndex(0) ‘property let move through tabs.
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Database programming with Netbeans and Java
You can create powerful database applications using the Java language and Netbeans IDE.Java uses JDBC for connecting SQL databases.The language has rich set of SQL and database func-tionality classes.This tutorial will teach how you can create a data base application.
Project Components
In our example we create an MDI Application which saves the Expense of date.It is a personal application.
 We use a Internal Frame and JFrameForm plus a split pan to add few buttons.  In addition we had a class contact with members to add database functionality. Learn the complete tutorial and master Java and JDBC programming
The MDI Window and Childs
Start a Java Application project with
Swing GUI Forms; JFrame Form and then Internal Frame Form,Desktop pane from the Swing container pallets.
Panel container with Buttons,list boxes, combo boxes and a text field to input data. Also add the following code to the main form(JFrame Form) in order to load the child
form in response to the button click
private void NewXpnsButtonMouseClicked(java.awt.event. MouseEvent evt) {
EntryForm ef=new EntryForm();jDesktopPane1.add(ef);ef. setVisible(true);
}
The Xpense Class
Add Java class to add database functionality with name ‘Expenses’. In the Constructor please add the following code.’
Analyse the code.
Connection con=null;Statement st=null;ResultSet re=null;-public Xpenses() {try {Class.forName(“org.apache.derby. jdbc.ClientDriver”);con=DriverManager.getConnection(“jdb
NETBEANS JAVA TUTORIALS
c:derby://localhost:1527/TechDB”,”tech”,”manujan”);System. out.print(“DataBase Connection established”);} catch (Ex-ception e) {System.out.print(“DataBase error”+e.getMes-sage());}}
aThe Class.Forname specifies the Database Driver.You can access this information using the Services Panel (Project Explorer).
aJust go to the connection properties.
The Connection object con specifies the database URL along with us-ername and password.
CURD Operations
Now your program ready to accept connection from database.Lets Just do some CURD opera-tions.
Add a method called AddNewXpense and add the following codes.
public void AddNewXpense() {try {st=con.createState-ment();String SQL;SQL=”INSERT INTO TECH.XPENSE VAL-UES(‘”+xd+”’,’”+XItem+”’,’”+X
Cat+”’,’”+Xtype+”’,”+Xamount+”)”;st.executeUp-date(SQL);System.out.print(“One record added”);} catch (Exception e) {System.out.print(“Error couc-cured:”+e.getMessage());}
}
aHere st create and execute SQL statements. Simply insert the SQL commands.
aWe use string variable to avoid problem with SQL data type and Java types.
st.executeUp-date(SQL); will execute the SQL statement and insert rows. # You can do all the CURD operation like this.
The complete Xpense class will look like
package ChildForms;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet;
NETBEANS JAVA TUTORIALS
import java.sql.Statement;import java.util.Date; public class Xpenses { Connection con=null; Statement st=null; ResultSet re=null; public String xd=null; public String XItem=null;; public String XCat=null; public String Xtype=null;; String Xamount=null; public Xpenses() { try { Class.forName(“org.apache.derby.jdbc.ClientDriver”); con=DriverManager.getConnection(“jdbc:derby://local-host:1527/TechDB”,”tech”,”manujan”);
System.out.print(“DataBase Connection established”); } catch (Exception e) {
System.out.print(“DataBase error”+e.getMessage()); }
}
public void SetDate(String d){ this.xd=d;
}
public void SetItem(String it){ this.XItem=it;
}
public void SetCate(String ca){ this.XCat=ca;
}
public void SetType(String ty){ this.Xtype=ty;
NETBEANS JAVA TUTORIALS
}public void SetAmount(String am){ this.Xamount=am;
}
public void AddNewXpense() { try {
st=con.createStatement(); String SQL;
SQL=”INSERT INTO TECH.XPENSE VALUES(‘”+xd+”’,’”+X-Item+”’,’”+XCat+”’,’”+Xtype+”’,”+Xamount+”)”;
st.executeUpdate(SQL);
System.out.print(“One record added”); } catch (Exception e) {
System.out.print(“Error couccured:”+e.getMessage()); }}
}
Xpense object and invoking memebers
Now you need to create an object of the class and use it to insert a row to y o u r database table
Add the following code to the Update button of the child form (Internal Frame Form)
private void UpdateTButtonMouseClicked(java.awt.event.Mou-seEvent evt) {
Xpenses x=new Xpenses(); try { x.SetDate(dateTxt.getText()); x.SetAmount( amountTxt.getText() ); x.SetCate(CatCom.getSelectedItem().toString()); x.SetType(TypeCom.getSelectedItem().toString()); x.SetItem(itemCom.getSelectedItem().toString());
NETBEANS JAVA TUTORIALS
System.out.println(Date.valueOf(dateTxt.getText()).to-String());
x.AddNewXpense();
} catch (Exception e) {
System.out.println(“Reading error coccured:”+e.getMes-sage());
} }
Now add some library for the support of the Java DB project which can be found on the db - lib folder of the Javasdk.
Right click your project from the from the package explorer and access p r o j -ect properties.
Access the Libraries add derby and derby client Jar using the Add Jar / Folder button.Now you are ready for first run
OK ,start your database and run the project. }
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Play with Tables & views in Java DB
Database programming with Java-DB and Netbeans is so easy.Some times we had tables with too many columns which is not essential for the application.But the data is being used by other users.In this case logical views of tables are great help to the programmer.
What is a view ?
Views are logical tables.We can create a view of a table with few columns needed based on a table or another view.View can be worked like table, but it didn’t occupy any physical memory.
View structure on service window Creating a view?
In this example we used Java-DB default sample database and a table called “MANUFACTUR-ER”. We want only few records who were in the city of “Santa Clara”.
Access the Service window - Expand your Database connection (sample)-APP (schema) Expand the table node and then the Manufacturer sample table.
Right click the View node and create a new(SanatClara)
Select manufacturer_id,name,state,email,rep from manufac-turer where city = ‘Santa Clara’
Now time to take a look at the view you just made. Right click the view and select view data Preparing the Project
Start a Java Application [Leave the main class alone]
Add libraries to the project. Access the Project Properties - Libraries.
Add the derby client jar files to the project inorder to provide support for the JavaDB. Create following instances above the constructor
Connection c=null; Statement s=null; ResultSet rs=null;
NETBEANS JAVA TUTORIALS
Insert the following code in the constructor of the form try { Class.forName(“org.apache.derby.jdbc.ClientDriver”); c=DriverManager.getConnection(“jdbc:derby://local-host:1527/sample”,”app”,”app”); System.out.println(“Connection established”); } catch (Exception e) { System.out.println(“JDB Error:”+e.getMessage()); }
athis will set up the connection and ready for executing the queries and commands.
On the click event of the jButton insert the following
try {
String SQL=”SELECT * FROM APP.SANTACLARA”; s=c.createStatement();
rs= s.executeQuery(SQL); while(rs.next()){
System.out.println(rs.getString(“MANUFACTURER_ ID”)+” | “+rs.getString(“NAME”)+” |
String(“STATE”)+” | “+rs.getString(“EMAIL”)+” | “+rs.get-String(“REP”)); } } catch (Exception e) { System.out.println(“Table Error:”+e.getMessage()); }
Now you can run the project.
# Just like in table you can perform all CURD operations on affected rows.
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Playing with swing ComboBox in Netbeans: Adding
an array to jComboBox
ComboBox component allows users to select an item from a list of item or enter a new text / value. ComboBox is an important GUI component for every desktop application.J ava provide jComboBox through the Javax.Swing package.
We can add an item to combo at design mode and at run time too. Lets see the common method to add items to jComboBox at run time.
Start a Java Application Add a JFrame Form Combobox
Command button.
Add the code to the click event of button for adding a single Item
jComboBox2.addItem(“Duma”);
Adding a single object or a group of object
Sometimes we need to add object arrays to Combobox.Java let it do using the SetModel method. Drag another button and drop these code to the Click event.
We are going to add a set of strings using the String class.then add it to the jComboBox.This is good practice instead of using Ad-ditem in a loop.
String [] s=new String[5]; s[0]=”Onam”; s[1]=”Vishu”; s[2]=”Bakreed”; s[3]=”Holly”; s[4]=”Christmas”; jComboBox1.setModel(new javax.swing.DefaultComboBoxMod-el(s));
NETBEANS JAVA TUTORIALS
Now Run the project
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Utility Classes : Return multiple values using Vectors
in Java
Methods in Java is an essential feature at all. Methods can return object and value. Lets consider a situation where you want to return a specific rows from database table.There may be plenty of row say 50 or a 1000s. So we had huge data to gather and return.
Using Vector class we can store what ever object in it. It auto-matically increase its size as we add the data.
Lets check out the method
public Vector GetItems(){ Connection con=null; Statement st=null; ResultSet re=null;
Vector li=new Vector(3,1); try { Class.forName(“org.apache.derby.jdbc.ClientDriv-er”); con=DriverManager.getConnection(“jdbc:derby://lo-calhost:1527/TechDB”,”tech”,”123”); st=con.createStatement(); String SQL;
SQL=”SELECT CATE FROM TECH.XPENSE”; re=st.executeQuery(SQL); while(re.next()){ li.addElement(re.getString(“cate”)); } System.out.println(li.size()+”Elements fectched”); } catch (Exception e) {
NETBEANS JAVA TUTORIALS
System.out.println(“Error couccured while fetching:”+e. getMessage());
}
return li;
}
aHere the Vector object list will hold the data.
aThe initial size of the vector was 3 and it will increased by one.So we had plenty of place to
hold the rows.
# The database portion of the method is already discussed ,please refer the previous posts.
Now time to call the methods. I invoke them in JFrame Form’s construc tor,after the initCocomponent().
Xpenses x=new Xpenses(); Vector s=new Vector(); s= x.GetItems();
You can also add the vector object to directly to Combo-Box.The defaultComboBoxModdel method support the Vector argument.
CategoryCom.setModel(new DefaultComboBoxMod el(s));
Vectors can’t be directly to output to console.You have to use Iterator or enumeration class to extract the values.
Iterator i=s.iterator(); while (i.hasNext()){
System.out.println(i.next()); }
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Develop applications using Netbeans persistence
Netbeans Java IDE speed up the application development.Along with some power up plugins the IDE make development process rapid and effective.We are talking about Netbeans Persistence feature.Persistence module make database application development so simple and easy.
Using the persistence wizard you can instantly creates per-sistence class for table.Using EntityManagerFactory and Entity Manager object we can operate the database with simplicity.
Let me show how you can build an sample persistence operation. ± Start a Java application project
Leave the main class alone.(Project Name:Persistence) Add a Swing GUI Form-JFrame Form
Drag a Swing JButton
± Lets create the sample Persistence class(We use the default sample database and Discount code table)
Go to File-New-Select Persistence-Entity Class From Database. Select the database connection and add the tables , click Next
Add a new package (persistence will not work on default package) and hit finish button. Now you have the Entity class for the table you chosen.
# You also should note the persistence and find the persistence unit name property. You can view this by opening the XML file or just by Navigator(Ctrl+7). It will look like” PersistencePU”
± Now you are ready to code the action.Drop the following code in click event of the button on JFrame Form.
EntityManagerFactory ef = Persistence.createEntityMan-agerFactory(“PersistancePU”);
EntityManager em=ef.createEntityManager();
aThis will create the EntityManager factory and EntityManager objects.Lets begin the
NETBEANS JAVA TUTORIALS
The Transaction begin with calling of begin().
em.getTransaction().begin();
DiscountCode d=new DiscountCode(); d.setDiscountCode(‘D’); d.setRate(BigDecimal.ZERO.valueOf(12.00)); em.persist(d); em.getTransaction().commit(); ef.close(); em.close();
The Discount Entity object was used to store value and then it is passed to the EntityManager. The Persist() will add the transaction to the table and it will be saved after the calling of com-mit().
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
How to use ArrayList in Java to store objects?
ArrayList class extends the AbstractList interface, which implements List Interface (extends col-lection). List is a collection Frame work. Collection are are great help while you are working with a group of objects. In addition to the Collection class members, List also had many useful members.
In general Arrays in Java lies under the category of static Array, in which the size of the Array should be given at before use it. At runtime user can’t change the size at runtime. ArrayList can be used to define variable length arrays which can automatically resize at runtime.
Adding Object into an ArrayList.
ArrayList a=new ArrayList(); a.add(“C Programming”); a.add(“Java Programming”); a.add(“C++ Programming”); System.out.println(“Size:”+a.size()); a.add(“Python Programming”); a.add(0,”Rubby”); System.out.println(“Size:”+a.size()); Fetching elements int i; i=0; while(i<a.size()){ System.out.println(“\n”+a.get(i).toString()); i++; } } }
The size of the ArrayList will increase automatically as new Objects were inserted to the List. Size() will get you the size of the array. The Objects can be fetched using get() method. a.ad-d(0,”Rubby”); statement will insert the object as the first element into the ArrayList.
NETBEANS JAVA TUTORIALS
ArrayList a1=new ArrayList(); a1.add(1); a1.add(12); a1.add(1); Fetching elements i=0; int s=0; while(i<a1.size()){ s+=Integer.parseInt(a1.get(i).toString()); i++; } System.out.println(“\nSum=”+s);
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
How to obtain value from an ArrayList into an Array
in Java?
The ArrayList is like a variable array, it let Java programmers to insert object any type. When handling a group of objects, Lists would be useful.
We already saw the basic operation on lists on last post. This post will let you learn how to ex-tract object into an Array.
This can be accomplished using an Object array and toArray() method of the ArrayList.
Object ob[]=a1.toArray(); int s=0; while(i<ob.length){ s+=((Integer)ob[i]).intValue(); i++; } System.out.println(“\nSum=”+s);
The intValue() method of Wrapper class Integer utilized to get the Integer value from the Object.
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Functions returning ArrayList in JAVA
ArrayList is one of the interesting collections extensions which will help programmers to return multiple objects. In general all function s can return a single value in Java. By using the List col-lection object ArrayList we return multiple objects.
In this example we have an array and a function which is declared as static in another class. The function will filter all the odd numbers into ArrayList and return. In effect our Java function would return as many objects we want.
The Function body
static ArrayList GetOdd(int x[]){
ArrayList out=new ArrayList(); int i=0; while(i<x.length){ if(x[i]%2!=0){ out.add(x[i]); }i++; } return out; }
Calling the function
int x[]={2,4,5,6,7,11};
ArrayList a=new ArrayList(); a=NewClass.GetOdd(x); int i; i=0; while(i<a.size()){ System.out.println(“\n”+a.get(i).toString()); i++; } }
The GetOdd() function will fetch all odd elements into ArrayList. You can also fetch those ele-ments into an array from List (See how)
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
TreeSets for fast accessing and retrieval of objects
in Java.
TreeSets are a collection framework, ideal for storing retrieving objects. It works faster com-pared to other collection frameworks. TreeSets implements Set interface; they can store unique values, in a sorted order. When programmer need large amount of sorted data to be stored and maintain, the TreeSet is recommended.
Following code will illustrate use of Tree list
TreeSet ts=new TreeSet();
ts.add(12);ts.add(1);ts.add(121);ts.add(22);ts.add(121);ts. add(-12);
System.out.println(ts);
Output:
[-12, 1, 12, 22, 121]
TreeSets stores only unique values. Here in the out put the duplicate of 121 is removed from the list.
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Getting the current date and time
The Date class is an old class which included in the old versions Java. The Date will not help you to access individual members of the Date. The date can only return default string or in milli-seconds. For accessing the most of the components of date you have to use the new Calendar Object. package date.example; import java.util.Date; /** * * @author Techietalk.in */
public class DateExample { /**
* @param args the command line arguments */
public static void main(String[] args) { Date dt=new Date();
//Using default toString()
System.out.println(“Current Date is:”+dt); //Date and Time in Milliseconds
long d=dt.getTime();
System.out.println(“Current Date[Millisec-onds]:”+d);
} }
The Date class has following methods for comparison
After, before, equals, compareTo which uses Comparable interface (Date class). There are different constructors you can construct date value.
package date.comparison; import java.util.Date; /**
NETBEANS JAVA TUTORIALS
** @author Techietalk.in */
public class DateComparison { /**
* @param args the command line arguments */
public static void main(String[] args) { Date d1=new Date(99,2,17);
Date d2=new Date(99,2,1);
if (d1.after(d2)==true){
System.out.println(“Using After:The date is new[“+d1+”- than -”+d2+”]”);
}
Date d3=new Date(“2/1/2010”);
if (d1.before(d3)==true){
System.out.println(“Using Before:This is an earlier date[“+d1+”- than -”+d3+”]” );
}
Date d4=new Date(); d4=d3;
if(d4.equals(d4)==true){
System.out.println(“Using Equal:Both dates are equal[“+d3+”- than -”+d4+”]” );
}
//Compare to method illustration Date d5=new Date(“1/1/2010”);
NETBEANS JAVA TUTORIALS
System.out.println(“____________________________________ ______________\n” );
if(d5.compareTo(d4)==0){
System.out.println(“CompareTo[0]::Both dates are equal[“+d5+”- than -”+d4+”]” ); } else if(d5.compareTo(d4)>0){ System.out.println(“CompareTo[>0]:This is an newer date[“+d5+”- than -”+d4+”]” ); } else if (d5.compareTo(d4)<0){ System.out.println(“CompareTo[<0]::This is an ear-lier date[“+d5+”- than -”+d4+”]” );
}
} }
 The CompareTo method returns 3 values as follows. CompareTo Function and returning values.
If the calling object is equal with arg the function will return 0
If the calling object is an earlier than the given one and the function will return >0 If the calling object is a newer than the given one and the function will return <0 I believe that the two program illustration will clarify the use of Date class and methods.
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Accessing date components with Calendar Object
We already saw that how a Date object works and how the comparison of two dates is possible. The Calendar class support more components and operations on date and time. It is an abstract class which made conversion of time to useful components. Calendar provides different type of protected variables such as DAYS_OF_WEEK, DAYS_OF_YEAR, and MONTH etc.
Calendar class didn’t provide any public constructor to construct new date value. We have to use Overloaded Set method for constructing new date. To access the current date you simply call the getInstance method.
Following program will illustrates how to use a Calendar Object.
package calendarobject; import java.util.Calendar; import java.util.Locale; /** * * @author Techietalk.in */
public class CalendarObject { /**
* @param args the command line arguments */
public static void main(String[] args) {
String mName[]={“Jan”,”Feb”,”Mar”,”Apr”,”May”,”Jun”,”-Jul”,”Aug”,”Sep”,”Oct”,”Nov”,”Dec”}; String Days[]={“Sun”,”Mon”,”Tue”,”Wed”,”Thu”,”Fri”,”-Sat”}; Calendar Cal=Calendar.getInstance(); System.out.println(Cal.get(Calendar.YEAR)+ “ “+mName[-Cal.get(Calendar.MONTH)]+” “+Cal.get(Calendar.DATE)+” “+Days[Cal.get(Calendar.DAY_OF_WEEK)-1]);
NETBEANS JAVA TUTORIALS
System.out.println(Cal.get(Calendar.HOUR)+ “:”+Cal.get(-Calendar.MINUTE)+”:”+Cal.get(Calendar.SECOND));
Calendar CDate =Calendar.getInstance(); CDate.add(Calendar.YEAR,1);
System.out.println(CDate.get(Calendar.YEAR)); Calendar Edate = Calendar.getInstance();
System.out.println(“__________________________________ ______\n”); Edate.clear(); Edate.set(2013,7,18); System.out.println(Edate.get(Calendar.YEAR)+” “+mName[Edate.get(Calendar.MONTH)-1]+ “ “+Edate.get(Calen-dar.DATE)); } }
aSince Month and Day of the week are represented in integer values, we have taken
neces-sary care to build Arrays for Days and Month.
# Calendar object made the date operation simple, we can access each of single com ponents for advanced date and time operations.
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Gregorian calendar and leap year in Java
Java had rich set of classes to perform advanced date and time operations. Gregoriancalender is one of the classes you can use where date and time operation required. The class inherited the features of Calendar object. Unlike Calendar class it has many constructors to full fill the needs of the programmers.
GregorianCalendar (int year, int month, int dayOfMonth)
GregorianCalendar (int year, int month, int dayOfMonth, int hours, int minutes)
GregorianCalendar (int year, int month, int dayOfMonth, int hours, int minutes, int seconds) GregorianCalender do all the Date and time operations, it also provide some extra function such as isLeapyear.
The Class can also use locales and Time zones as the arguments for the Gregoriancalender ob-ject.
GregorianCalendar(Locale locale)
GregorianCalendar(TimeZone timeZone)
GregorianCalendar(TimeZone timeZone, Locale locale)
The following example will clarify the use of GregorianCalendar class and objects.
/*
* To change this template, choose Tools | Templates * and open the template in the editor.
*/ package georgiancalendar; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; /** *
NETBEANS JAVA TUTORIALS
*/public class GeorgianCalendar { /**
* @param args the command line arguments */
public static void main(String[] args) { String months[] = {
“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”,
“Sep”, “Oct”, “Nov”, “Dec”};
GregorianCalendar gcal=new java.util.GregorianCalen-dar(2016, 1, 1);
Locale loc=new Locale(“Malayalam”,”CANADA”);
GregorianCalendar lg=new java.util.GregorianCalen-dar(loc); System.out.println(gcal.get(Calendar. YEAR)+”/”+months[gcal.get(Calendar.MONTH)]+”/”+gcal.get(-Calendar.DATE )); if(gcal.isLeapYear(gcal.get(Calendar.YEAR))){ System.out.println(“This is a leap year !”); }
else {
System.out.println(“Not a leap year !”); } System.out.println(lg.get(Calendar.YEAR)+”/”+months[lg. get(Calendar.MONTH)]+”/”+lg.get(Calendar.DATE )+” “+loc. getCountry()+” “+loc.getDisplayLanguage());}}
NETBEANS JAVA TUTORIALS
# Locale is another class supplied with Java SDK, which stores locales information such as language and country to Calendar objects. The class possesses three con structors.
# There is also the Time Zone class which can hold time zone information. The two classes are useful when handling Calendar and GregorianCalender objects.
# The Locale class support many useful methods, such as getCountry, getDisplayLan guage, which extract Country and Language from the Locale objects.
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Random numbers and Random class in Java
Random is the pseudorandom number generating class which can produce random numbers. The class can generate float, int, Boolean, byte random numbers.
The nextBoolean(), nextBytes(), nextLong(), nextDouble(), nextFloat(), nextGuassian() are the different functions used to generate random numbers. Following example will clarify the con-cept of Random class.
package random.example; import java.util.Random; /** * * @author NEIT */
public class RandomExample { /**
* @param args the command line arguments */
public static void main(String[] args) { Random r=new Random();
System.out.println(r.nextInt(100)); System.out.println(r.nextDouble()); System.out.println(r.nextGaussian()); System.out.println(r.nextLong()); } }
The overloaded nextInt(arg) method can accept a value as argument , and it will generate ran-dom values take the argument as starting value. If you don’t specified any starting value it will use current time starting string.
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
How to use Obervable and Observe Objects
Observable class is an abstract class which is used to create object that can observe by another class.
In real world such application exists. Suppose in case of Shopping cart list, when new items add-ed to the list, it should be notifiadd-ed to purchase object.
 Observable class can notify when changes undergoes with the help of setChanged () and notifyObserver () method.
 When notifyObservers called the changes were informed through update () method.  Observable class should subclassed from java.utils.
 Observable and the Observer class implements the Observer interface.
There were only two golden rules for observable object, first one: while any changes undergoes to the observable, need to invoke setChanged.
Secondly setChanged should be called before notifyObservers method invoke, when it is ready to inform the observers. Without the SetChanged there will be no action take place.
Using the add Observer you can add observers for the class.
Following Scoreboard example will explain how the Observable class and Observer interface works.
We had three classes namely Player Scorecard Scoreboard. Player Class package scoreboard; import java.util.Observable; /** *
NETBEANS JAVA TUTORIALS
* @author Techietalk.in*/
public class Players extends Observable{ String player_name; int goals; String descr; String team; public Players( ) { }
public void newGoals(String p,String te,int g){ goals=g; player_name=p; team=te; setChanged(); notifyObservers(this); }
public void newGoals(String p,String te,int g,String des){ goals=g; player_name=p; descr=des; team=te; setChanged(); notifyObservers(this); } }
Player class holds Player information. With newGoal method new goal details can be added to the observable object. The Scorecard is the observer class, whenever a core is added to the Player object using newGoal it will be reported to observer class [Scorecard] and the update method will print the result.
NETBEANS JAVA TUTORIALS
Scorecard package scoreboard; import java.util.Observable; import java.util.Observer; /** * * @authorTechietalk.in */public class ScoreCard implements Observer{ @Override
public void update(Observable o, Object o1) {
System.out.println(Players.class.cast(o1).player_ name +”[“+Players.class.cast(o1).team +”] “+”(“+Players. class.cast(o1).goals +”)”);
if (Players.class.cast(o1).descr!=null){
System.out.print(“ -> lol “ +Players.class. cast(o1).descr);
} } }
# Remember the observer class should implements the Observer interface and use up date () to perform action required.
The Live Scoreboard class
/*
* To change this template, choose Tools | Templates * and open the template in the editor.
*/
NETBEANS JAVA TUTORIALS
/***
* @authorTechietalk.in */
public class ScoreBoard { /**
* @param args the command line arguments */
public static void main(String[] args) throws Inter-ruptedException {
Players p=new Players();
ScoreCard sc=new ScoreCard(); p.addObserver(sc); System.out.print(“---\n SCORE BOARD\n---\n”); p.newGoals(“Messie”,”MU”,1); Thread.sleep(3500); p.newGoals(“Roonie”,”Arsenel”, 5); Thread.sleep(4500); p.newGoals(“Ronaldo”,”TotelDam”, 1); Thread.sleep(4500);
p.newGoals(“Beckham”,”Manchester City”, 2,”Corner Kick”);
} }
Finally the main class scoreboard will create objects of Player and Scorecard and add Scorecard object as observer. Whenever a new object player score is added it will automatically add the information to the scoreboard. We also used sleep method of Thread to place a delay between score display, so that it can be live.
More source code will be make available through www.techietalk.in , you can too contribute to
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
How to Schedule a task in Java
Scheduling task is an application of threading in Java. Timer and TimerTask classes provide functionality for scheduling the exe-cution of a piece of code for future.
TimerTask class implements the runnable interface, so it can use the thread execution using the Timer class instance. If you are familiar with run (Threads and multi-threaded programming Java) method, will understand the working of a thread. It is a member defined by runnable. ± The overridden run method hold execution part of your task; you can drop those operations
come under the task you want to schedule.
package tasksheduler; import java.util.TimerTask; /** * * @author Techietalk.in */
public class Tasks extends TimerTask{ @Override
public void run() {
System.out.println(“The Meeting was Over”); }
}
Now Schedule the task, can achieve using the Timer object which work exactly as a Thred.
NETBEANS JAVA TUTORIALS
public class TaskSheduler {package tasksheduler; import java.util.Timer; /** * * @author Techietalk.in */
public class TaskSheduler { /**
* @param args the command line arguments */
public static void main(String[] args) {
Tasks tsk=new Tasks(); Timer tm=new Timer();
tm.schedule(tsk,500); //half second }
}
You can schedule as many tasks, just by sub classing the TimerClass. Note:
The task will scheduled to run in every half second with initial delay of one second.
1 second=1000
½ second=500
Scheduling the task for a future date
The schedule method has many forms. You can run a task on specific date using following for-mat
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
How to Bind a Swing Table compenent with DB
con-nection Netbeans
Java Netbeans becomes an easy tool for database powered program development. You can create and manage database connections instantly with Service window using the connection wizard.
# By default Java Netbeans come with JDB , the derby database.
# Other database connection require the driver so databases like MS Access will not work without proper driver (jar file).
The JavaDB tutorials will help you to tune your inbuilt Java Database.
± The bind feature allow you to display rows from your tables without coding. Lets figure it out Add a Java Application Project ( leave the main class blank)
New File –Swing GUI Form – JFrame Form. Now drag a Swing Table control from Swing Pallet Access the service Window – expand the Database Node
Start the Java DB service by clicking Start command (right click)
Now right click the Swing table – Bind – Elements, now you will get the bind dialog.
± Using the Click import data to form you can easily import rows from a connection. Click the import data to form and select a connection and a table
Choose the columns you want to add to the table and hit OK ± Now run the project
aThe table component will hold all the rows from the connection.
aYou can see the connection navigator just below the service window which is help full for
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Binding selected columns of a table into Swing
ta-ble in NB
Binding in Java Netbeans refers to extracting the data from other components without pain of coding, i.e. no code is required. Netbeans will code for you. In our last Data Binding tutorial we demonstrate how you can bind a Database table using the service window and the binding feature. You can also bind the selected columns to Table control too.
± Lets do it
Add a New Java Application Project(Leave the main class option unchecked) Add a new Swing Frame Form and drag a table control
Make sure that the Java DB or any database service is running. Right click the table and choose the Table Contents.
Use bound option to import rows from table. Select the Column tab
Insert for adding a new colum Select the new column
set the column from Expression and Title as Column head.
You can also choose the width, height and type of the value for the column you inserted. Close the window and Run the App
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Observing more than one class and types of changes
in those classes.
“An observer class can observe any no of classes as an observ-able class can add any number of observers”
Observing interface and Observable class provide a great tool for a programmer, we already saw that how to of Observable in our last tutorial. A class can be observed by many observers, how about class that can observe more than one. Let’s explore
± Here is two observable classes which can notify different type of changes occurred. Nos Class package ob1; import java.util.Observable; /** * * @author Techietalk.in */
public class Nos extends Observable{ int x;
int y;
public Nos() { }
public void SetNos(int x,int y){ this.x=x; this.y=y; setChanged(); notifyObservers(new Integer(y)); } } OBSL Class package ob1;
NETBEANS JAVA TUTORIALS
import java.util.Observable;public class OBSL extends Observable{ int x; float f; String s; public OBSL() { } public OBSL(int x) { this.x = x; setChanged(); notifyObservers(this); }
public void Set(int x){ this.x=x;
setChanged();
notifyObservers(new Integer(x)); }
public void Set(float x){ this.f=x;
setChanged();
notifyObservers(new Float(x)); }
public void Set(String x){ this.s=x;
setChanged();
notifyObservers(new String(x)); }
}
No lets Observe the change they made, add a main class.
import java.util.Observable; import java.util.Observer; import ob1.*;
NETBEANS JAVA TUTORIALS
public class Ob1 implements Observer{public static void main(String[] args) { OBSL ob=new OBSL();
Nos n=new Nos(); Ob1 o=new Ob1(); ob.addObserver(o); n.addObserver(o); ob.Set(10); ob.Set(new Float(12.34)); ob.Set(“Welcome”); ob.Set(new Float(1.34)); n.SetNos(1, 1); n.SetNos(1, 1); } @Override
public void update(Observable o, Object o1) { System.out.println(“Integer:”+Integer.class. cast(o1).toString() + “ changed!”); System.out.println(“Flaot:”+Float.class.cast(o1). toString() + “ changed!”); System.out.println(“String:”+String.class. cast(o1).toString() + “ changed!”);
System.out.println(“\nInstance of Class “+o.get-Class().getName()+”\n”); System.out.println(“Integer:”+Integer.class. cast(o1).toString() + “ changed!”); System.out.println(“Flaot:”+Float.class.cast(o1). toString() + “ changed!”); System.out.println(“String:”+String.class. cast(o1).toString() + “ changed!”); } }
NETBEANS JAVA TUTORIALS
Lets observe the result
The update method of the observer class returns some error. So we have to keep track of chang-es made according to the changing object as well as observing objects. Lets modify the Update method as follows
if(OBSL.class.isInstance(o)){
System.out.println(“Instance of Class “+o.get-Class().getName()+”\n”); if(Integer.class.isInstance(o1)==true){ System.out.println(“Integer:”+Integer.class. cast(o1).toString() + “ changed!”); } else if(Float.class.isInstance(o1)) { System.out.println(“Flaot:”+Float.class.cast(o1). toString() + “ changed!”); } else if(String.class.isInstance(o1)){ System.out.println(“String:”+String.class. cast(o1).toString() + “ changed!”); } }
NETBEANS JAVA TUTORIALS
if(Nos.class.isInstance(o)){System.out.println(“\nInstance of Class “+o.get-Class().getName()+”\n”); if(Integer.class.isInstance(o1)==true){ System.out.println(“Integer:”+Integer.class. cast(o1).toString() + “ changed!”); } else if(Float.class.isInstance(o1)) { System.out.println(“Flaot:”+Float.class.cast(o1). toString() + “ changed!”); } else if(String.class.isInstance(o1)){ System.out.println(“String:”+String.class. cast(o1).toString() + “ changed!”); } } }
Lets Run it again
Here the isinstance method used to check the type of the changing objects and Observable class. So we can add necessary code for handling different classes and avoid the errors.
How to
http://techietalkcat.blogspot.inNETBEANS JAVA TUTORIALS
Files and FileNameFilter Interface
We alreaddy seen how File Object work with directories and Files. Sometimes we need to filter out those files which lies under particular formats. It can be few .pdf files or .java files or .txt files. Java itself has the capability to handle these type of operations with the help of FileNameFilter Interface.
The interface defines a single method accept , which is called once for a file in a list and returns true for file in the directory spec-ified by the directory that should included in the list.
± Now lets start with Netbeans Project, or an Eclipse project. Start New Project with main class.
Add and an additional Java class to the project which implements the ‘FileNameFilter’ interface and drop the code.
public class FilefilterEx implements FilenameFilter{ String ext;
public FilefilterEx(String ext){ this.ext=”.” + ext;
}
@Override
public boolean accept(File file, String string) { return string.endsWith(ext);
}
The overriden method ‘accept’ will check out the extention for files. The Object of the FIefilterEx can be used as an argument with list method of File object, which extratct files to an array of strings. You can pass the the filter class object with ‘list’ which will fetch the files.
± Now do the main() part
String Dir=”D:/Lycons”;
NETBEANS JAVA TUTORIALS
FilefilterEx fil=new FilefilterEx(“exe”); String s[]=f1.list(fil);
for(int i=0;i<s.length;i++){ System.out.println(s[i]); }
and the out put will be look like
200406.pdf 200407.pdf 200408.pdf 200409.pdf
Advanced Javascript.pdf
Encyclopedia Britannica 2009 - Book of the Year.pdf introduction2vb1.pdf
j-classloader-ltr.pdf
Java 2 - The Complete Reference (5th Edition).pdf Java Game Programming For Dummies .pdf
# There is an alternative for ‘list’ method which offer sosame filtering capabilities. The only difference is with list is that ListFiles return files as an array of File objects instead of the array of String . The ListFiles method of File object comes with three signature
File[ ] listFiles( )
File[ ] listFiles(FilenameFilter FFObj) File[ ] listFiles(FileFilter FObj)
± Rewrite the code of main method as
String Dir=”D:/Lycons”;
File f1=new File(Dir);
FilefilterEx fil=new FilefilterEx(“pdf”); File s[]= f1.listFiles(fil);
for(int i=0;i<s.length;i++){ System.out.println(s[i]); }
The following method of applying Filter class is also leagal