89% found this document useful (9 votes)
775 views55 pages

NetBeans Java Tutorials for Beginners

Java Oracle Netbeans IDE Tutorials for beginners. These tutorials will take you into the world advanced java programming.

Uploaded by

MANOJ AP
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
89% found this document useful (9 votes)
775 views55 pages

NetBeans Java Tutorials for Beginners

Java Oracle Netbeans IDE Tutorials for beginners. These tutorials will take you into the world advanced java programming.

Uploaded by

MANOJ AP
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.

NETBEANS JAVA TUTORIALS FOR BEGINNERS

JAVA Coding simplified

NETBEANS JAVA TUTORIAL FOR BIGINNERS Manoj A.P

Author's Note

used this material for training program of the young and provided as an additional material for [Link] tutorial collections proved extreamely helpfull for beginners of Java and Netbean programming platform. Anybody who would like to use and distribute this book can find link to download the current version of this e-book from authors blog/ twitter accounts. We also love to hear what you are thinking about this e-book. Thank you, MANOJ [Link]

Contents

How to add nodes to a swing tree control in java Netbeans? 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 jComboBox 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

Code is poetry

NETBEANS JAVA TUTORIALS

How to

How to add nodes to a swing tree control in java Netbeans?


[Link]

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 dont 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 DefaultMutableTreeNode(Items);

DefaultMutableTreeNode Juices=new DefaultMutableTreeNode(Juices); DefaultMutableTreeNode ic=new DefaultMutableTreeNode(IceCream); [Link](ic); // add the IceCreame node to the top node as child [Link](Juices);

NETBEANS JAVA TUTORIALS


DefaultMutableTreeNode m=new DefaultMutableTreeNode(mango); DefaultMutableTreeNode p=new DefaultMutableTreeNode(Pinwapple); DefaultMutableTreeNode g=new DefaultMutableTreeNode(Grapes); DefaultMutableTreeNode o=new DefaultMutableTreeNode(Orange); [Link](m); //add mango child node to the Juice node as child [Link](p);
[Link](g); [Link](o); DefaultMutableTreeNode fs=new DefaultMutableTreeNode(Fruit Salad); DefaultMutableTreeNode fl=new DefaultMutableTreeNode(Falooda); DefaultMutableTreeNode ch=new DefaultMutableTreeNode(Choclate Shake); DefaultMutableTreeNode ms=new DefaultMutableTreeNode(Misc); [Link](fs); [Link](fl);//add Fruit Salad to the IceCreame node as child. [Link](ch);

[Link](new DefaultTreeModel(top));
DefaultMutableTreeNode Juices=new DefaultMutableTreeNode(Juices); DefaultMutableTreeNode ic=new DefaultMutableTreeNode(IceCream); [Link](ic); node as child // add the IceCreame node to the top

NETBEANS JAVA TUTORIALS


[Link](Juices); DefaultMutableTreeNode m=new DefaultMutableTreeNode(mango); DefaultMutableTreeNode p=new DefaultMutableTreeNode(Pinwapple); DefaultMutableTreeNode g=new DefaultMutableTreeNode(Grapes); DefaultMutableTreeNode o=new DefaultMutableTreeNode(Orange); [Link](m); node as child [Link](p); [Link](g); [Link](o); DefaultMutableTreeNode fs=new DefaultMutableTreeNode(Fruit Salad); DefaultMutableTreeNode fl=new DefaultMutableTreeNode(Falooda); DefaultMutableTreeNode ch=new DefaultMutableTreeNode(Choclate Shake); DefaultMutableTreeNode ms=new DefaultMutableTreeNode(Misc); [Link](fs); [Link](fl);//add Fruit Salad to the IceCreame node as child. [Link](ch); //add mango child node to the Juice

[Link](new DefaultTreeModel(top)); Now it will look like

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=[Link](); DefaultMutableTreeNode t=new DefaultMutableTreeNode(tp); if (t!=null){ [Link]([Link]());}

NETBEANS JAVA TUTORIALS

How to

create database and tables in Java DB/JDB ?


[Link]

Most of the program require a database ,Java comes up with an inbuilt database called JavaDB. It is an unique SQL data [Link] 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 database. Create Java DB database a n d

## 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 [Link] a view in JavaDB is so simple and [Link] 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 [Link] 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 [Link] your copy from [Link]

NETBEANS JAVA TUTORIALS

How to

Make a Tabbed dialog in Java Netbeans


[Link]

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 [Link] 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 Javas way things becomes different.  Swing provides two types of components containers and controls .Containers just hold the [Link] 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 [Link] 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 ,isnt it?  Now drag JInternal Frame from container and it will show up the [Link] 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.  We can also re position the tabs.

NETBEANS JAVA TUTORIALS

How to

Database programming with Netbeans and Java


[Link]

You can create powerful database applications using the Java language and Netbeans [Link] uses JDBC for connecting SQL [Link] language has rich set of SQL and database functionality [Link] 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 [Link] 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([Link]. MouseEvent evt) { EntryForm ef=new EntryForm();[Link](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 {[Link]([Link]. [Link]);con=[Link](jdb

NETBEANS JAVA TUTORIALS


c:derby://localhost:1527/TechDB,tech,manujan);System. [Link](DataBase Connection established);} catch (Exception e) {[Link](DataBase error+[Link]());}} aaThe [Link] specifies the Database [Link] can access this information using the Services Panel (Project Explorer). aaJust go to the connection properties.  The Connection object con specifies the database URL along with username and password. CURD Operations Now your program ready to accept connection from [Link] Just do some CURD operations.  Add a method called AddNewXpense and add the following codes. public void AddNewXpense() {try {st=[Link]();String SQL;SQL=INSERT INTO [Link] VALUES(+xd+,+XItem+,+X Cat+,+Xtype+,+Xamount+);[Link](SQL);[Link](One record added);} catch (Exception e) {[Link](Error couccured:+[Link]());} aaHere st create and execute SQL statements. Simply insert the SQL commands. aaWe use string variable to avoid problem with SQL data type and Java types. [Link](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 [Link]; import [Link]; import [Link];

NETBEANS JAVA TUTORIALS


import [Link]; import [Link]; 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 { [Link]([Link]); con=[Link](jdbc:derby://localhost:1527/TechDB,tech,manujan); [Link](DataBase Connection established); } catch (Exception e) { [Link](DataBase error+[Link]()); } } public void SetDate(String d){ [Link]=d; } public void SetItem(String it){ [Link]=it; } public void SetCate(String ca){ [Link]=ca; } public void SetType(String ty){ [Link]=ty;

NETBEANS JAVA TUTORIALS


} public void SetAmount(String am){ [Link]=am; } public void AddNewXpense() { try {

st=[Link](); String SQL; SQL=INSERT INTO [Link] VALUES(+xd+,+XItem+,+XCat+,+Xtype+,+Xamount+); [Link](SQL); [Link](One record added); } catch (Exception e) { [Link](Error couccured:+[Link]()); }} } Xpense object and invoking memebers  Now you need to create an object of the class and use it to insert a row to database table  Add the following code to the Update button of the child form (Internal Form) your Frame

private void UpdateTButtonMouseClicked([Link] evt) { Xpenses x=new Xpenses(); try { [Link]([Link]()); [Link]( [Link]() ); [Link]([Link]().toString()); [Link]([Link]().toString()); [Link]([Link]().toString());

NETBEANS JAVA TUTORIALS


[Link]([Link]([Link]()).toString()); [Link](); } catch (Exception e) { [Link](Reading error coccured:+[Link]()); } }  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 project properties.  Access the Libraries add derby and derby client Jar using the Add Jar / Folder [Link] you are ready for first run OK ,start your database and run the project. }

NETBEANS JAVA TUTORIALS

How to

Play with Tables & views in Java DB


[Link]

Database programming with Java-DB and Netbeans is so [Link] times we had tables with too many columns which is not essential for the [Link] the data is being used by other [Link] this case logical views of tables are great help to the programmer. What is a view ?  Views are logical [Link] can create a view of a table with few columns needed based on a table or another [Link] can be worked like table, but it didnt 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 MANUFACTURER. 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 manufacturer 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 { [Link]([Link]); c=[Link](jdbc:derby://localhost:1527/sample,app,app); [Link](Connection established); } catch (Exception e) { [Link](JDB Error:+[Link]()); } aathis 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 [Link]; s=[Link](); rs= [Link](SQL); while([Link]()){ [Link]([Link](MANUFACTURER_ ID)+ | +[Link](NAME)+ | +[Link](STATE)+ | +[Link](EMAIL)+ | +[Link](REP)); } } catch (Exception e) { [Link](Table Error:+[Link]()); } Now you can run the project. ## Just like in table you can perform all CURD operations on affected Try to create more views and add few rows on the Swing components rows.

NETBEANS JAVA TUTORIALS

How to

Playing with swing ComboBox in Netbeans: Adding an array to jComboBox


[Link]

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 [Link] 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 [Link](Duma); Adding a single object or a group of object Sometimes we need to add object arrays to [Link] 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 [Link] add it to the [Link] is good practice instead of using Additem in a loop. String [] s=new String[5]; s[0]=Onam; s[1]=Vishu; s[2]=Bakreed; s[3]=Holly; s[4]=Christmas; [Link](new [Link](s));

NETBEANS JAVA TUTORIALS


Now Run the project Explore more Netbeans Tutorial on [Link]

NETBEANS JAVA TUTORIALS

How to

Utility Classes : Return multiple values using Vectors in Java


[Link]

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 [Link] 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 automatically 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 { [Link]([Link]); con=[Link](jdbc:derby://localhost:1527/TechDB,tech,123); st=[Link](); String SQL; SQL=SELECT CATE FROM [Link]; re=[Link](SQL); while([Link]()){ [Link]([Link](cate)); } [Link]([Link]()+Elements fectched);

} catch (Exception e) {

NETBEANS JAVA TUTORIALS


[Link](Error couccured while fetching:+e. getMessage()); } return li; } aaHere the Vector object list will hold the data. aaThe initial size of the vector was 3 and it will increased by [Link] 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 Forms construc tor,after the initCocomponent(). Xpenses x=new Xpenses(); Vector s=new Vector(); s= [Link](); You can also add the vector object to directly to [Link] defaultComboBoxModdel method support the Vector argument. [Link](new DefaultComboBoxMod el(s)); Vectors cant be directly to output to [Link] have to use Iterator or enumeration class to extract the values.

Iterator i=[Link](); while ([Link]()){ [Link]([Link]()); }

Run your project & watch the resultst

NETBEANS JAVA TUTORIALS

How to

Develop applications using Netbeans persistence


[Link]

Netbeans Java IDE speed up the application [Link] with some power up plugins the IDE make development process rapid and [Link] are talking about Netbeans Persistence [Link] module make database application development so simple and easy.  Using the persistence wizard you can instantly creates persistence class for [Link] 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 [Link] the following code in click event of the button on JFrame Form. EntityManagerFactory ef = [Link](PersistancePU); EntityManager em=[Link](); aaThis will create the EntityManager factory and EntityManager [Link] begin the Transaction.

NETBEANS JAVA TUTORIALS


The Transaction begin with calling of begin(). [Link]().begin(); DiscountCode d=new DiscountCode(); [Link](D); [Link]([Link](12.00)); [Link](d); [Link]().commit(); [Link](); [Link](); 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 commit(). Now check out the table for new entry.

NETBEANS JAVA TUTORIALS

How to

How to use ArrayList in Java to store objects?


[Link]

ArrayList class extends the AbstractList interface, which implements List Interface (extends collection). 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 cant 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(); [Link](C Programming); [Link](Java Programming); [Link](C++ Programming); [Link](Size:+[Link]()); [Link](Python Programming); [Link](0,Rubby); [Link](Size:+[Link]()); Fetching elements int i; i=0; while(i<[Link]()){ [Link](\n+[Link](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. [Link](0,Rubby); statement will insert the object as the first element into the ArrayList. Another example will make the operation on Integer Object in an ArrayList vivid.

NETBEANS JAVA TUTORIALS


ArrayList a1=new ArrayList(); [Link](1); [Link](12); [Link](1); Fetching elements i=0; int s=0; while(i<[Link]()){ s+=[Link]([Link](i).toString()); i++; } [Link](\nSum=+s);

NETBEANS JAVA TUTORIALS

How to

How to obtain value from an ArrayList into an Array in Java?


[Link]

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 extract object into an Array. This can be accomplished using an Object array and toArray() method of the ArrayList. Object ob[]=[Link](); int s=0; while(i<[Link]){ s+=((Integer)ob[i]).intValue(); i++; } [Link](\nSum=+s); The intValue() method of Wrapper class Integer utilized to get the Integer value from the Object.

NETBEANS JAVA TUTORIALS

How to

Functions returning ArrayList in JAVA


[Link]

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 collection 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<[Link]){ if(x[i]%2!=0){ [Link](x[i]); }i++; } return out; } Calling the function int x[]={2,4,5,6,7,11}; ArrayList a=new ArrayList(); a=[Link](x); int i; i=0; while(i<[Link]()){ [Link](\n+[Link](i).toString()); i++; } } The GetOdd() function will fetch all odd elements into ArrayList. You can also fetch those elements into an array from List (See how)

NETBEANS JAVA TUTORIALS

How to

TreeSets for fast accessing and retrieval of objects in Java.


[Link]

TreeSets are a collection framework, ideal for storing retrieving objects. It works faster compared 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(); [Link](12);[Link](1);[Link](121);[Link](22);[Link](121);ts. add(-12); [Link](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.

NETBEANS JAVA TUTORIALS

How to

Getting the current date and time


[Link]

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 milliseconds. For accessing the most of the components of date you have to use the new Calendar Object. package [Link]; import [Link]; /** * * @author [Link] */ public class DateExample { /** * @param args the command line arguments */ public static void main(String[] args) { Date dt=new Date(); //Using default toString() [Link](Current Date is:+dt); //Date and Time in Milliseconds long d=[Link](); [Link](Current Date[Milliseconds]:+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 [Link]; import [Link]; /**

NETBEANS JAVA TUTORIALS


* * @author [Link] */ 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 ([Link](d2)==true){ [Link](Using After:The date is new[+d1+- than -+d2+]); } Date d3=new Date(2/1/2010); if ([Link](d3)==true){ [Link](Using Before:This is an earlier date[+d1+- than -+d3+] ); } Date d4=new Date(); d4=d3; if([Link](d4)==true){ [Link](Using Equal:Both dates are equal[+d3+- than -+d4+] ); } //Compare to method illustration Date d5=new Date(1/1/2010);

NETBEANS JAVA TUTORIALS


[Link](____________________________________ ______________\n ); if([Link](d4)==0){ [Link](CompareTo[0]::Both dates are equal[+d5+- than -+d4+] ); } else if([Link](d4)>0){ [Link](CompareTo[>0]:This is an newer date[+d5+- than -+d4+] ); } else if ([Link](d4)<0){ [Link](CompareTo[<0]::This is an earlier 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.

NETBEANS JAVA TUTORIALS

How to

Accessing date components with Calendar Object


[Link]

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 didnt 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 [Link]; import [Link]; /** * * @author [Link] */ 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=[Link](); [Link]([Link]([Link])+ +mName[[Link]([Link])]+ +[Link]([Link])+ +Days[[Link](Calendar.DAY_OF_WEEK)-1]);

NETBEANS JAVA TUTORIALS


[Link]([Link]([Link])+ :+[Link]([Link])+:+[Link]([Link])); Calendar CDate =[Link](); [Link]([Link],1); [Link]([Link]([Link])); Calendar Edate = [Link](); [Link](__________________________________ ______\n); [Link](); [Link](2013,7,18); [Link]([Link]([Link])+ +mName[[Link]([Link])-1]+ +[Link]([Link])); } } aaSince Month and Day of the week are represented in integer values, we have taken necessary 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.

NETBEANS JAVA TUTORIALS

How to

Gregorian calendar and leap year in Java


[Link]

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 object. 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 [Link]; import [Link]; import [Link]; /** *

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 [Link](2016, 1, 1); Locale loc=new Locale(Malayalam,CANADA); GregorianCalendar lg=new [Link](loc); [Link]([Link](Calendar. YEAR)+/+months[[Link]([Link])]+/+[Link]([Link] ));

if([Link]([Link]([Link]))){ [Link](This is a leap year !); } else { [Link](Not a leap year !); }

[Link]([Link]([Link])+/+months[lg. get([Link])]+/+[Link]([Link] )+ +loc. getCountry()+ +[Link]());}}

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.

NETBEANS JAVA TUTORIALS

How to

Random numbers and Random class in Java


[Link]

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 concept of Random class. package [Link]; import [Link]; /** * * @author NEIT */ public class RandomExample { /** * @param args the command line arguments */ public static void main(String[] args) { Random r=new Random(); [Link]([Link](100)); [Link]([Link]()); [Link]([Link]()); [Link]([Link]()); } } The overloaded nextInt(arg) method can accept a value as argument , and it will generate random values take the argument as starting value. If you dont specified any starting value it will use current time starting string.

NETBEANS JAVA TUTORIALS

How to

How to use Obervable and Observe Objects


[Link]  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 added to the list, it should be notified 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 [Link]. 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 [Link]; /** *

NETBEANS JAVA TUTORIALS


* @author [Link] */ 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 [Link]; import [Link]; /** * * @[Link] */ public class ScoreCard implements

Observer{

@Override public void update(Observable o, Object o1) { [Link]([Link](o1).player_ name +[+[Link](o1).team +] +(+Players. [Link](o1).goals +)); if ([Link](o1).descr!=null){ [Link]( -> lol +[Link]. 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. */ package scoreboard;

NETBEANS JAVA TUTORIALS


/** * * @[Link] */ public class ScoreBoard { /** * @param args the command line arguments */ public static void main(String[] args) throws InterruptedException { Players p=new Players(); ScoreCard sc=new ScoreCard(); [Link](sc); [Link](-----------------------\n SCORE BOARD\n-----------------------\n); [Link](Messie,MU,1); [Link](3500); [Link](Roonie,Arsenel, 5); [Link](4500); [Link](Ronaldo,TotelDam, 1); [Link](4500); [Link](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 [Link] , you can too contribute to us.

NETBEANS JAVA TUTORIALS

How to

How to Schedule a task in Java


[Link]  Scheduling task is an application of threading in Java. Timer and TimerTask classes provide functionality for scheduling the execution 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 [Link]; /** * * @author [Link] */ public class Tasks extends TimerTask{ @Override public void run() { [Link](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 [Link]; /** * * @author [Link] */ public class TaskSheduler { /** * @param args the command line arguments */ public static void main(String[] args) { Tasks tsk=new Tasks(); Timer tm=new Timer(); [Link](tsk,500); } } 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 format [Link](task,Date as date);

//half second

NETBEANS JAVA TUTORIALS

How to

How to Bind a Swing Table compenent with DB connection Netbeans


[Link]

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 aaThe table component will hold all the rows from the connection. aaYou can see the connection navigator just below the service window which is help full for managing Query and list.

NETBEANS JAVA TUTORIALS

How to

Binding selected columns of a table into Swing table in NB


[Link]

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

NETBEANS JAVA TUTORIALS

How to

Observing more than one class and types of changes in those classes.
[Link]  An observer class can observe any no of classes as an observable 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. Lets explore Here is two observable classes which can notify different type of changes occurred. Nos Class package ob1; import [Link]; /** * * @author [Link] */ 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 [Link]; 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 [Link]; import [Link]; 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(); [Link](o); [Link](o); [Link](10); [Link](new Float(12.34)); [Link](Welcome); [Link](new Float(1.34)); [Link](1, 1); [Link](1, 1); } @Override public void update(Observable o, Object o1) { [Link](Integer:+[Link]. cast(o1).toString() + changed!); [Link](Flaot:+[Link](o1). toString() + changed!); [Link](String:+[Link]. cast(o1).toString() + changed!); [Link](\nInstance of Class +[Link]().getName()+\n); [Link](Integer:+[Link]. cast(o1).toString() + changed!); [Link](Flaot:+[Link](o1). toString() + changed!); [Link](String:+[Link]. 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 changes made according to the changing object as well as observing objects. Lets modify the Update method as follows if([Link](o)){ [Link](Instance of Class +[Link]().getName()+\n); if([Link](o1)==true){ [Link](Integer:+[Link]. cast(o1).toString() + changed!); } else if([Link](o1)) { [Link](Flaot:+[Link](o1). toString() + changed!); } else if([Link](o1)){ [Link](String:+[Link]. cast(o1).toString() + changed!); } }

NETBEANS JAVA TUTORIALS


if([Link](o)){ [Link](\nInstance of Class +[Link]().getName()+\n); if([Link](o1)==true){ [Link](Integer:+[Link]. cast(o1).toString() + changed!); } else if([Link](o1)) { [Link](Flaot:+[Link](o1). toString() + changed!); } else if([Link](o1)){ [Link](String:+[Link]. 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.

NETBEANS JAVA TUTORIALS

How to

Files and FileNameFilter Interface


[Link]

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 specified 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){ [Link]=. + ext; } @Override public boolean accept(File file, String string) { return [Link](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;

File f1=new File(Dir);

NETBEANS JAVA TUTORIALS


FilefilterEx fil=new FilefilterEx(exe); String s[]=[Link](fil); for(int i=0;i<[Link];i++){ [Link](s[i]); }
and the out put will be look like

[Link] [Link] [Link] [Link] Advanced [Link] Encyclopedia Britannica 2009 - Book of the [Link] [Link] [Link] 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[]= [Link](fil); for(int i=0;i<[Link];i++){ [Link](s[i]); } The following method of applying Filter class is also leagal File s[]= [Link](new FilefilterEx(docx));

NETBEANS JAVA TUTORIALS

More tutorials will coming soon

Common questions

Powered by AI

The GregorianCalendar class in Java is used for date manipulation. It inherits from the Calendar class and provides methods to handle date and time fields such as year, month, and day. It supports operations like adding dates, checking leap years, and adjusting for different locales and time zones. It offers constructors with various parameters, including year, month, day, and time, which allow precise date specifications .

The Date class in Java is limited compared to the Calendar class because it only provides basic functionalities such as returning date as a string or milliseconds and lacks advanced component manipulation. On the other hand, the Calendar class offers extensive capabilities for date and time operations, including accessing individual date components (year, month, day) and performing operations like adding days or comparing dates. Calendar also supports different locales and time zones, making it more versatile .

The Calendar class is recommended for complex date operations over the Date class due to its extensive support for date manipulation, including adding and subtracting dates, accessing specific fields like DAY_OF_YEAR, and handling different time zones and locales. Unlike the Date class, Calendar allows modification and retrieval of individual components, making it more suitable for intricate date-time operations .

NetBeans IDE facilitates Java database application development by providing built-in tools and libraries for managing JDBC connections, executing SQL queries, and handling database operations. It simplifies the process with GUI-based management, making it easier to configure and interact with databases. Additionally, it supports the integration of Java classes for database functionality, streamlining the creation of database-driven applications .

The Random class in Java enhances functionalities by generating pseudorandom numbers for various data types like int, double, float, and more. This capability is crucial in applications requiring randomization, such as games, simulations, and statistical sampling. Methods like nextInt(), nextDouble(), and nextGaussian() provide random values, aiding in diverse functional requirements .

At runtime in Java, data can be added to a JComboBox using the addItem() method for single items, or setModel() for adding an array or collection. These methods provide flexibility in managing JComboBox content dynamically during execution, enhancing user interaction in applications .

Views improve data management in Java DB applications by allowing developers to present data from one or more tables in a customized format without affecting the actual data stored in the database. They provide a logical representation of a subset of data, which can simplify queries and enhance security by limiting user access to specific columns or rows .

The Observable class in Java plays a significant role in implementing the observer pattern, which is used to create objects that can be observed by other classes. This class notifies observers about changes made to the observable object, allowing for real-time updates. It is typically used in applications such as shopping carts where changes in product lists need to be reflected in real-time for associated objects. The class methods setChanged() and notifyObservers() are crucial for managing these updates .

JDBC (Java Database Connectivity) is used in Java applications to establish a connection with a database, execute SQL queries, and retrieve results. It provides a standard API that allows Java applications to interact with various databases using SQL .

TreeSet in Java offers advantages such as automatic sorting and unique element storage, making it ideal for maintaining a large, ordered dataset with fast retrieval. Unlike other collections like ArrayList, TreeSet ensures that duplicate values are not stored, preventing redundancy. It is particularly efficient for applications requiring frequent access and storage of sorted data .

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
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
Code is poetry
How to
http://techietalkcat.blogspot.in
NETBEANS JAVA TUTORIALS
How to add nodes to a swing tree control in java 
Netbeans?
A
NETBEANS JAVA TUTORIALS
 
DefaultMutableTreeNode m=new DefaultMutableTreeNode(“man­
go”);
       DefaultMutableTreeNode p=new
NETBEANS JAVA TUTORIALS
      
 top.add(Juices);
       DefaultMutableTreeNode m=new DefaultMutableTreeNode(“man­
go”);
NETBEANS JAVA TUTORIALS
GETTING THE PATH OF THE SELECTION
So how would you get the selection path, it is easy .Drag an additi
How to
http://techietalkcat.blogspot.in
NETBEANS JAVA TUTORIALS
create database and tables in Java DB/JDB ?
 
Most of the pro

You might also like