Java Netbeans Tutorials for beginners

Share Embed Donate


Short Description

Descripción: Java Oracle Netbeans IDE Tutorials for beginners. These tutorials will take you into the world advanced jav...

Description

NETBEANS JAVA TUTORIALS FOR BEGINNERS JAVA Coding simplified

NETBEANS JAVA TUTORIAL FOR BIGINNERS Manoj A.P

Author's Note

I

used this material for training program of the young and provided as an additional material for students.These 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 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? create database and tables in Java DB/JDB ? 9 Make a Tabbed dialog in Java Netbeans 11 Database programming with Netbeans and Java 12

5

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

How to

NETBEANS JAVA TUTORIALS

How to add nodes to a swing tree control in java Netbeans? http://techietalkcat.blogspot.in

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

DefaultMutableTreeNode Juices=new DefaultMutableTreeNode(“Juices”); DefaultMutableTreeNode ic=new DefaultMutableTreeNode(“IceCream”); top.add(ic); // add the “IceCreame” node to the “top” node as child top.add(Juices);

NETBEANS JAVA TUTORIALS DefaultMutableTreeNode m=new DefaultMutableTreeNode(“mango”); DefaultMutableTreeNode p=new DefaultMutableTreeNode(“Pinwapple”); DefaultMutableTreeNode g=new DefaultMutableTreeNode(“Grapes”); DefaultMutableTreeNode o=new DefaultMutableTreeNode(“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(“Falooda”); DefaultMutableTreeNode ch=new DefaultMutableTreeNode(“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(“Juices”); DefaultMutableTreeNode ic=new DefaultMutableTreeNode(“IceCream”); top.add(ic); node as child

// add the “IceCreame” node to the “top”

NETBEANS JAVA TUTORIALS top.add(Juices); DefaultMutableTreeNode m=new DefaultMutableTreeNode(“mango”); DefaultMutableTreeNode p=new DefaultMutableTreeNode(“Pinwapple”); DefaultMutableTreeNode g=new DefaultMutableTreeNode(“Grapes”); DefaultMutableTreeNode o=new DefaultMutableTreeNode(“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(“Falooda”); DefaultMutableTreeNode ch=new DefaultMutableTreeNode(“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)); 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=jTree2.getSelectionPath(); DefaultMutableTreeNode t=new DefaultMutableTreeNode(tp); if (t!=null){ jLabel1.setText(t.toString());}

How to

NETBEANS JAVA TUTORIALS

create database and tables in Java DB/JDB ? http://techietalkcat.blogspot.in

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 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 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 Oracle.com

How to

NETBEANS JAVA TUTORIALS

Make a Tabbed dialog in Java Netbeans http://techietalkcat.blogspot.in

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 controls .Containers just hold the controls.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.  We can also re position the tabs.

How to

NETBEANS JAVA TUTORIALS

Database programming with Netbeans and Java http://techietalkcat.blogspot.in

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 functionality 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 (Exception e) {System.out.print(“DataBase error”+e.getMessage());}} aaThe Class.Forname specifies the Database Driver.You 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 database.Lets Just do some CURD operations.  Add a method called AddNewXpense and add the following codes. public void AddNewXpense() {try {st=con.createStatement();String SQL;SQL=”INSERT INTO TECH.XPENSE VALUES(‘”+xd+”’,’”+XItem+”’,’”+X Cat+”’,’”+Xtype+”’,”+Xamount+”)”;st.executeUpdate(SQL);System.out.print(“One record added”);}

}

catch (Exception e) {System.out.print(“Error couccured:”+e.getMessage());} 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. st.executeUpdate(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://localhost: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+”’,’”+XItem+”’,’”+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 database table  Add the following code to the Update button of the child form (Internal Form)

your Frame

private void UpdateTButtonMouseClicked(java.awt.event.MouseEvent 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()).toString()); x.AddNewXpense(); } catch (Exception e) { System.out.println(“Reading error coccured:”+e.getMessage()); } }  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 button.Now you are ready for first run OK ,start your database and run the project. }

How to

NETBEANS JAVA TUTORIALS

Play with Tables & views in Java DB http://techietalkcat.blogspot.in

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 “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 { Class.forName(“org.apache.derby.jdbc.ClientDriver”); c=DriverManager.getConnection(“jdbc:derby://localhost:1527/sample”,”app”,”app”); System.out.println(“Connection established”); } catch (Exception e) { System.out.println(“JDB Error:”+e.getMessage()); } 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 APP.SANTACLARA”; s=c.createStatement(); rs= s.executeQuery(SQL); while(rs.next()){ System.out.println(rs.getString(“MANUFACTURER_ ID”)+” | “+rs.getString(“NAME”)+” | “+rs.getString(“STATE”)+” | “+rs.getString(“EMAIL”)+” | “+rs.getString(“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 Try to create more views and add few rows on the Swing components

rows.

How to

NETBEANS JAVA TUTORIALS

Playing with swing ComboBox in Netbeans: Adding an array to jComboBox http://techietalkcat.blogspot.in

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 Additem 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.DefaultComboBoxModel(s));

NETBEANS JAVA TUTORIALS Now Run the project Explore more Netbeans Tutorial on wwww.techietalkcat.blogspot.in

How to

NETBEANS JAVA TUTORIALS

Utility Classes : Return multiple values using Vectors in Java http://techietalkcat.blogspot.in

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 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 { Class.forName(“org.apache.derby.jdbc.ClientDriver”); con=DriverManager.getConnection(“jdbc:derby://localhost: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; } aaHere the Vector object list will hold the data. aaThe 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 ComboBox.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()); }

Run your project & watch the resultst

How to

NETBEANS JAVA TUTORIALS

Develop applications using Netbeans persistence http://techietalkcat.blogspot.in

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 persistence 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.createEntityManagerFactory(“PersistancePU”); EntityManager em=ef.createEntityManager(); aaThis will create the EntityManager factory and EntityManager objects.Lets begin the Transaction.

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 commit(). Now check out the table for new entry.

How to

NETBEANS JAVA TUTORIALS

How to use ArrayList in Java to store objects? http://techietalkcat.blogspot.in

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 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
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF