This comprehensive guide explains how to use Netbeans Ide to create various Java Applications with code examples:
NetBeans IDE offers a development environment to create applications using Java, HTML, JavaScript, PHP, and C/C++. In this tutorial, we will focus on the use of this universal editor that has inbuilt support for:
- Various versioning tools such as Subversion, Git, Mercurial.
- Build automation tools like Ant, Gradle, and Maven.
- Java Standard, Enterprise, Micro edition, Swing, and JavaFX GUI builder for a graphical interface.
- Debug, builds, exports the application code.
- HTML5, PHP, C/C++, JavaScript, JSP, XML, Groovy and JavaDoc.
- Cross-platform support for Linux, Windows, and Mac.
- MySQL, JavaDB, Oracle, PostgreSQL, ElasticSearch, MongoDB database connection wizards.
Table of Contents:
How To Use NetBeans IDE
Pre-requisites
We have used Apache NetBeans IDE 12.0 and JDK 1.8 or higher installed in this tutorial.
To open NetBeans IDE, click on the shortcut displayed on a desktop or on executable file NetBeans64.exe from the bin directory, Close the default welcome page.
Creating Java Application
Follow the steps below to quickly create a standalone desktop application in Java using NetBeans IDE:
#1) Use Ctrl+Shift+N Short cut key, Or select File–> New Project to open an interface as displayed below.
#2) You can select any one of the categories like Java with Maven, Java with Gradle, or Java with Ant and select Projects as Java Application. Click the Next button. You can alternatively locate a particular Project by entering text in the Filter.
The below image is the interface that allows the type of Java framework to select from:
#3) The next screen displays the default location that gets selected and all the folders will be created at this folder location.
#4) Click the Finish button. This will display the newly created Project with Source Packages, Dependencies, and Project Files.
#5) You can right-click on the Project folder, select New and select any one of the options to say Java Package, with the next screen to enter the package name. (It is recommended by coding standard specifications to create Package)
#6) You can select the Java Class option with next screen to enter the name of Java Class, Name of Java Package created.
#7) This will display code generated on the editor on the right pane as displayed below.
The below image explains creating Package and Class and Code generated for Java Class:
You can start adding variables to be used in Class.
The structure of the variable is as below:
private int adharnumber;
Here, the variable name will be preceded by
- Access modifiers (private, public, protected, or default (without any specifier)
- Data types can be primitives like byte, short, int, long, float, double, boolean, and char OR reference data types such as objects such as String, Arrays, Classes, and Interface.
You will need a main method that is of the structure as NetBeans IDE. Type psvm and press Enter button on your keyboard.
public static void main (String[]args) { }
You may need an output that displays on the console of NetBeans IDE. Type sout and press Enter.
It will display:
System.out.println (“”);
You can enter the message to be displayed inside the commas like Today is Holiday
Selecting Run– Run Projects OR Click on F6. It will run the project and display Today is Holiday on the console. It will build the project as well.
You can import classes by using import statements at the beginning of the Java program. You can inherit Property or State (attribute) and Behavior or Method of another class (parent class) using extends keyword. You can access interface methods by using implements keyword between Class and interface.
Use getter and setter methods in order to access private variables outside of the class. For this, select a Class name and right-click to select Insert Code. Select Getter and Setter from the list.
It will open a window to select variables. In our case, age; on selecting the checkbox and clicking Generate button. Following syntax of Getter and Setter methods will be inserted into the Java Class:
public int getAge() { return age; } public void setAge(int age) { this.age = age; }
Recommended Reading =>> Guide to Java NetBeans IDE
Building Graphical User Interface In Java Application
Follow the steps below to add a graphical user interface for a standalone desktop application.
#1) Repeat the steps from 1 till 7 from Creating Java Application in NetBeans IDE.
#2) Select Categories as Swing GUI Forms and File Type as JFrame Form. Click the Next button. Select Package from the drop-down & click the Finish button.
#3) You will find NewJFrame.java with Frame seen in Design view; Swing Containers and Controls separated in Palette tab on Top Right corner; Swing Menus, Windows, and Fillers panel in hidden mode; AWT pane will be in expanded form.
The below screen shows Palette display Swing Containers Controls and AWT elements:
#4) We will select Panel from Palette under Swing Container & drag it onto the JFrame form. Drag and Drop three JLabel , three JTextField, and three JButton from Swing Controls.
#5) Select JPanel container, right-click & select Properties from menu. Click on ellipsis (…) against properties like the background to change color, border to select the border, etc.
#6) Rename the Swing Controls components,
- Double click on jLabel1, this will let you change the text of Label to Centigrade
- Double click on jLabel2, this will let you change the text of Label to Fahrenheit
- Select jTextField1, right-click to select properties, click on the ellipsis (…) against text property, opens a window, remove the value & click the OK button.
- Repeat the same steps for jTextField2 field.
- Drag the jButton1 between label Centigrade and Fahrenheit,
- Rename the Text of jButton1 to Convert.
- Rename the Text of jButton2 to Clear
- Rename the Text of jButton3 to Exit
#7) Adding functionality
Exit button
- Select Exit button element, right-click and select Event -> Action > actionPerformed. IDE adds an ActionListener to Exit button and creates a handler method for actionPerformed method of listener.
- Enter System.exit(0).
The code will look like below:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); }
Clear button
- Select Clear button, right-click and select Event – Action – actionPerformed. IDE adds an ActionListener to Clear button.
In order to clear the text on clicking Clear button, add the following code:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { jTextField1.setText(""); jTextField2.setText(""); }
Convert button
- Select Convert button, right-click and select Event – Action – actionPerformed.
In order to convert centigrade into fahrenheit add the following code as displayed below:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // Define variables of type Float float degree_cent, degree_fahren; degree_cent = Float.parseFloat(jTextField1.getText()); //degree_fahren = Float.parseFloat(jTextField2.getText()); //formula for Converting centigrade into fahrenheit degree_fahren = (degree_cent*9/5) + 32; jTextField2.setText(String.valueOf(degree_fahren)); }
To run the program code in NetBeans IDE, choose Run – Run Project OR press F6 (shortkey),
The GUI form will be executed as displayed below:
Enter 100 in text field labeled as Centigrade, click on Convert button, Fahrenheit value 212.0 will be displayed in the text field labeled as Fahrenheit as displayed below.
Below is the GUI application to convert Centigrade temperature into Fahrenheit:
Clicking on the Clear button will remove contents from text fields and Clicking on the Exit button will close the GUI form.
Building JavaFX User Interface
You can build 2D, 3D graphics and Media using JavaFX GUI toolkit into Java Application.
#1) Repeat the steps from 1 to 7 from Creating Java Application in NetBeans IDE.
#2) Select Categories Java with Maven, You can select one of the options from Projects.
- Simple JavaFX Maven Archetype (Gluon)
- FXML JavaFX Maven Archetype (Gluon)
Simple JavaFX Maven Archetype (Gluon)
a) It will download Archetype and build the project.
b) Once created, you can verify the following details
- Select Project, right-click, and select Properties
- You will find Categories on the left pane
- Sources will display Source/Binary Format as 1.8
- Compile under Build will display default Java Platform selected as JDK 1.8
- Actions on left pane will display Actions as Run project highlighted
- Execute Goals as clean javafx:run
c) Under Project Files, you will find three xml files namely pom.xml, nbactions.xml, and settings.xml.
d) nbactions.xml will display structure as below:
- You will find on action run, two goals viz. clean and javafx : run
e) Right-click on Project and select Run. It will start Running the application and display the output window as below.
FXML JavaFX Maven Archetype (Gluon)
a) The build will create Other Sources folder in addition to other folders created during Simple JavaFX Maven Archetype.
b) On expanding, it will display -primary and secondary fxml files
c) Select Project, right-click & select Run option. The output of FXML is as below:
Creating Java Web Application Using NetBeans
Follow the below steps to create a web application in Java using NetBeans IDE:
#1) Use Ctrl+Shift+N Short cut key, Or select File–> New Project to open an interface. Select Projects as Web Application.
#2) Click Next for default location which you can change using the browse button and selecting another location. Further clicking Next will open Settings window, allowing user to select Server and Java EE version.
#3) You can click on Add button to choose one of the Servers from the list such as Amazon Beanstalk, Apache Tomcat, GlassFish Server, Payara, and WildFly.
- Amazon Beanstalk- You must first register an Amazon Beanstalk account is the IDE (via Cloud)
- GlassFish Server- You need to download and install GlassFish Server locally or connect Remote Domain.
- Apache Tomcat- You need to download and install Apache Tomcat locally
- Payara OR WildFly Server – You need to download and install Payara or WildFly Servers locally
Interface to Select Server for Web Application in NetBeans:
Note: Glassfish or Wildfly servers are application servers and heavier than Web servers such as Tomcat. Web application projects create WAR file whereas Enterprise application project creates EAR file.
#4) In our case we have selected Apache Tomcat, an interface will open and ask for Server location. Users can select tomcat folder already installed in the system. Enter username and password to login to tomcat server, click Finish button.
#5) Right Click at Source Packages folder created under Web Application Project and select Servlet.
A window will open which allows entering name of class for Servlet and its location.
#6) Selecting Checkbox at Add information to deployment descriptor (web.xml) will add servlet information in web.xml, Servlet Name and URL Pattern(s) details can be entered in respective text fields displayed as displayed in the image below.
package com.mycompany.webapp; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WebServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet WebServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet WebServlet at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; } }
Once Servlet is created, the structure created in NetBeans for Web Application Project is displayed below. It has web.xml folder created under WEB-INF folder. The Servlet created above will be registered (added) in web.xml.
Web Application project structure at NetBeans IDE:
#7) The created Servlet code is as displayed above. Click on Run -> Run Project OR click on F6, short key, to run and execute the Servlet. The Tomcat server opens and displays the output as below:
Creating Java Web Service
Web Services like SOAP, REST, UDDI uses HTTP protocol to communicate and transfer data from client to server require web application as Project.
#1) Use Ctrl+Shift+N Short cut key, Or select File–> New Project to open an interface, Select Projects as Web Application. Right Click on Project and select New–Web Service.
#2) Select Package from the drop-down. Select Create Web Services from Scratch and check Implement Web Service as Stateless Session Bean by selecting the checkbox.
#3) Web service script/program will be displayed as below:
package com.mycompany.mavenproject1; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.ejb.Stateless; @WebService(serviceName = "NewWebService") @Stateless() public class NewWebService { @WebMethod(operationName = "hello") public String hello(@WebParam(name = "name") String txt) { return "Hello " + txt + " !"; } }
#4) Right-click on the web service created i.e. NewWebService in this case, and select Add Operation. An interface will open as displayed below which shows the Web Service Add Operation feature in NetBeans.
#5) Click the Next button. The web service code will get created and seen in the editor as below, where the option to Test Web Service is created.
Building Enterprise Application In NetBeans IDE
You can develop highly scalable, multi-tire, secure network enterprise applications using NetBeans as explained below:
#1) Use Ctrl+Shift+N Short cut key, Or select File–> New Project to open an interface. Select Categories as Java with Maven and Projects as Enterprise Application. Click Next button.
#2) Select Server from the options such as Amazon Beanstalk, Apache Tomcat, GlassFish Server, Payara, or WildFly server. We will select GlassFish Server in this case.
#3) Select Java EE version from the drop-down list. We have selected Java EE 8 that came as default.
#4) Keep checkbox selected for Create EJB Module and Create Web App Module, then click Finish.
#5) NetBeans creates the following projects from Maven Archetype:
- EJB (MyJavaEE-ejb) – It has the application’s source code with business logic in it & is archived as EJB JAR while packaging.
- Webapp (MyJavaEE -web) – JSF and JSP pages contain presentation layer, whereas Servlet (business logic in code) and is archived as WAR while packaging.
- Assembly (MyJavaEE) – Its sole purpose is to combine EJB and WAR archives and create EAR archives.
- Enterprise Application (MyJavaEE -ear) – It contains a POM file (pom.xml) that has details about modules in enterprise applications.
Note – Assembly and Enterprise Application project has no source code.
Select MyJavaEE Project & right-click to create New -> Session Bean. NewSessionBean is created. Keep Stateless as selected Session Type. Enter Package name as com.org.session.stateless.
Here we need to enter radius and height values to find the volume of the cylinder and cone. The formulae to calculate the volume of cylinder and cone is written in NewSessionBean as below:
package com.org.session.stateless; import javax.ejb.LocalBean; import javax.ejb.Stateless; @Stateless @LocalBean public class NewSessionBean { public double volume_cylinder(int radius, int height){ return 3.142*radius*radius*height; } public double volume_cone(int radius, int height){ return 3.142*radius*radius*height/3; } }
Next, Open index.html file under Web Pages folder from MyJavaEE project, wherein the inputs such as Radius and Height will be entered by user, which can be passed to stateless bean to calculate Volume of Cylinder and Cone.
In the below code example, we have created an HTML form for user inputs for Radius and Height values:
<html> <head> <title>Start Page</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <h1>Volume of Cylinder and Cone</h1> <form method="POST" action=" VolumeFormServlet"> <table><tr><td>Enter value of Radius :</td> <td><input type="text" name="radius" id="radius" /></td></tr> <tr><td>Enter value of Height :</td> <td><input type="text" name="height" id="height" /></td></tr> <tr><td><input type="submit" value="Submit"/></td></tr></table> </form></body></html>
Click on code, & select Run File option. Select Server as GlassFish, & click Next. It starts the GlassFish server and launches the Html page as below:
Next is to select Source Packages under MyJavaEE Project. Right Click to select New -> Servlet. Enter the name of Servlet as VolumeFormServlet. Enter package as com.org.volume. Click Next.
Servlet code will be displayed in the editor on the right pane.
Enter variable details in Servlet code under processRequest as shown in code below:
int radius = Integer.parseInt(request.getParameter("radius")); int height = Integer.parseInt(request.getParameter("height"));
Enter
@EJB private NewSessionBean newSessionBean;
Further, enter the following HTML code listed below:
out.println("<h1>Volume of Cylinder is" + newSessionBean.volume_cylinder(radius, height) + "</h1>"); out.println("<h1>Volume of Cone is" + newSessionBean.volume_cone(radius, height) + "</h1>");
The Servlet code VolumeFormServlet is as displayed as:
package com.org.volume; import com.org.session.stateless.NewSessionBean; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "VolumeFormServlet", urlPatterns = {"/VolumeFormServlet"}) public class VolumeFormServlet extends HttpServlet { @EJB private NewSessionBean newSessionBean; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); int radius = Integer.parseInt(request.getParameter("radius")); int height = Integer.parseInt(request.getParameter("height")); try (PrintWriter out = response.getWriter()) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet VolumeFormServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h3>Volume of Cylinder is " + newSessionBean.volume_cylinder(radius, height) + "</h3>"); out.println("<h3>Volume of Cone is " + newSessionBean.volume_cone(radius, height) + "</h3>"); out.println("<a href='index.html'>Return to Form</a>"); out.println("</body>"); out.println("</html>"); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; } }
Select Project, right-click, and select the Clean & Build option. The project gets built. Once build, right-click on the MyJavaEE project and select Run.
In the below image, Index Page accepts user inputs process the output and display using servlet:
Once source codes are written we have to test, debug, compile, build and run the application to verify functionality has been achieved as desired or not. There are various commands in IDE that are required to perform.
Commands Using NetBeans IDE On Java Programs
Enlisted below are the frequently used commands the uses NetBeans IDE on Java Programs:
- Clean and Build: By selecting Run > Clean and Build Project (Shift + F11) – This will delete any previously compiled files & JAR files generated. The source files are re-compiled resulting in new output.
- Compile on Save feature can be activated by selecting Right Click on Project > select Properties option, select Compile under Build, select Checkbox for Compile on Save. On activation of this feature, the files are compiled when they are saved.
- Deploy on Save feature can be activated by selecting Right Click on Project > Select Properties option, select Run, select Checkbox for Deploy on Save. On activation of this feature, the Enterprise Project is deployed when Run option is selected on Right click at Project.
- Run Project: Select Run > Run Project (F6) to run the deployed project.
- Test Project: Select Run > Test Project (Alt + F6) to test the files, alternatively, Window > IDE Tools > Test Results (Alt + Shift + R) will test the files.
- Debug Project feature Debug > Debug Project (Ctrl + F5) allows debugging the code by marking breakpoints and checking the code
Also Read =>> NetBeans Vs Eclipse Java IDEs
Conclusion
NetBeans IDE with build tools like Maven, Gradle, and Ant is used for building various applications such as Desktop standalone Application, Graphical User Interface in Swing and JavaFX, Web applications, Web Services, Enterprise applications, Session Beans, etc. Various commands like test, debug, deploy, run, clean, and build are frequently used using IDE.