How to Create a Java File in Netbeans

NetBeans Setup

To install NetBeans, follow the description from the JDK/NetBeans document for Windows, Mac, or Ubuntu Linux. For the purposes of this course, these are the things we want to be able to do in NetBeans:

  1. Create a new Java Application
  2. Create a Java Application Project from Existing Sources (primarily from downloaded sources)
  3. Close a Java Application
  4. Access the files of a Java Application not necessarily through NetBeans.
  5. Delete a Java Application with or without deleting the sources

Personalize NetBeans

Follow the steps listed in the Personalize NetBeans section of the NetBeans/JDK documents on the course website.

The HelloWorld project

The HelloWorld project is intended to be your first NetBeans project. I describe it in the JDK/NetBeans documents for Windows, Mac, or Ubuntu Linux. If you've already created it, either use another name, like

HelloWorld1

, or delete it (deleting sources).

When you start up NetBeans, three windows are available: Projects, Files, and Services. Mostly you work from Projects. Close Services since we'll never use it in this course. You can always control which windows are showing through the Window menu.

Follow these steps to create and run:

  1. Select File ⇾ New Project, or right-click in Projects and select New Project.
  2. In the New Project window, select the Java category, and choose Java Application, then Next.
  3. Choose the project name HelloWorld. The other settings have default values which you probably want to use. The project location cannot be an existing directory. NetBeans also pre-checks the box Create Main Class. Leave it checked. You can always just delete this automatically-generated Main class. Click Finish.
  4. Within the public static void main function, enter the code
                    System.out.println                (                "Hello World"                )                ;              
    DO IT LIKE THIS: Use a NetBeans shortcut: clear the initial "TODO" comment and type "sout" then TAB to have it expand automatically to System.out.println("");
  5. Save the changes and run the project. You can use the green run button or F6. Look for "Hello World" in the Output window at the bottom.
  6. Cleanup. Select Source ⇾ Format.

Keyboard Shortcuts

NetBeans provides many useful keyboard shortcuts that, when learned, help speed up program development due to their frequent usage. You can find a PDF page of them via

Help ⇾ Keyboard Shortcuts Card

The "

sout

TAB" is one of the most useful of these. We illustrate two other shortcuts in the last section.

Running Project Main Classes

When run is invoked, NetBeans will run whatever is the "selected project" by virtue of whatever file is selected in the Projects window. For the most part, you only ever want to run a single Main Class when you run the project, but during development, it is often useful to have more than one Main Class.

NetBeans chooses the main program to run by Run Configuration settings for that project. To see what we mean, select the <default config> ⇾ Customize, and look for

Main Class:                

The Browse button reveals the other Main Classes for choosing.

A more convenient way to deal with multiple Main Classes is by simply right-clicking the file in the Projects window and selecting Run File. You can then easily rerun the same file from the Output window by selecting the green re-run button.

Class and JAR files

When a project is executed, NetBeans compiles the Java source files and puts the class files into the build directory. You can only see this from the Files window. Going there you'll find the compiled classes:

build/classes/helloworld/HelloWorld.class        

Assuming that java is available in you system PATH, you can run this class (in this simple case) using a terminal shell by navigating to the build/classes subdirectory and invoking:

cd build/classes java helloworld.HelloWorld        

NetBeans also provides a "build" mechanism which encapsulates all classes into a JAR file in the

dist

directory. To build a project, run Build ⇾ Clean and Build Project or use the button. Afterward, from the Files window you'll observe the new

dist

folder with

HelloWorld.jar

file. The JAR file offers a more portable way of presenting a Java Application. You can run it by:

cd dist java -jar HelloWorld.jar        

If there were any additional support JAR files, they would be available in the

dist

folder and you could still run the application through the "

java -jar

" mechanism.

Use HelloWorld.java for testing

There are many times in which you want to write a short code sequence using a few variable to test some code behavior. The

HelloWorld

project can provide such a "testing ground." Simply add the imports you need and use the main program, deleting old code as necessary.

Java Application from Existing sources

This will give us the opportunity to show the installation of an existing Java Application along with other NetBeans gimmicks.

Access the default NetBeansProjects directory

This NetBeansProjects directory is the following on the 3 systems of interest:

Documents\NetBeansProjects\          (Windows)          ~/NetBeansProjects/          (Mac OSX & Linux)        

The "

~/

" is notation for your home directory.

Mac OS X Home Folder

Unfortunately, the MAC OSX system wants to hide this from the finder; so do the following:

Open the Finder and from there, Finder ⇾ Preferences. Select the Sidebar tab. Within the Favorites section, locate your home folder (with your login name) and check it; it should now be easily accessible. Within your home directory, find the NetBeansProjects folder.

Install the source folder

Start by downloading and extracting the source archive (just click the hyperlink).

Browsers give you the opportunity to either save it as a zip file or extract it somewhere. Either way, you want to obtain the directory

NumberGuess

somewhere. The goal is to move the

NumberGuess

directory into your NetBeansProjects folder, which differs by operating system:

Documents\NetBeansProjects\          (Windows)          ~/NetBeansProjects/          (Mac OSX & Linux)        

Once you have the

NumberGuess

folder available we want to install it. Open NetBeans.

  1. Create a New Project and select Java Project with Existing Sources, click Next.
  2. Now the Name and Location dialog. The most important thing to get correct is:
                  Project Folder: /path/to/NetBeansProjects/NumberGuess            
    Secondarily you need to give the project a name. There are two ways to achieve these outcomes:
    1. Specify the Project Folder first, then Project Name:
      • Use the Browse button to locate the Project Folder.
      • Enter the Project Name, which can be anything, not necessarily the folder basename NumberGuess.
    2. Enter the Project Name first. By doing this first, NetBeans sets the Project Folder automatically. So it is best to make the Project Name be exactly NumberGuess.
    Click Next.
  3. In the Existing Sources window, click the Add Folder... button. Make sure that it is open to the correct folder with the src sub-folder visible. Select src and click Open.
  4. Back in previous window, Finish.
  5. Run it by pressing the green run button. The Run Project dialog gives a selection of possible Main Classes. There is only one in this case, so select it and click OK.
  6. In the Output window you see the run:
    run: I've chosen 5 numbers between 1 and 20 Try to guess one:            
    Type in any number at the prompt and the run will complete.

Here is the Main Class:

NumberGuess

              package              numberguess              ;              import              java.util.Scanner              ;              import              java.util.Random              ;              /**  * @author Robert Kline  */              public              class              NumberGuess              {              private              static              boolean              findNum(              int              [              ]              nums,              int              upto,              int              key)              {              for              (              int              i              =              0              ;              i              <              upto;              ++i)              {              if              (key              ==              nums[i]              )              {              return              true              ;              }              }              return              false              ;              }              private              static              void              printNums(              int              [              ]              nums,              int              how_many)              {              System.out.print              (              "["              )              ;              boolean              first              =              true              ;              for              (              int              i              =              0              ;              i              <              how_many;              ++i)              {              if              (              !first)              System.out.print              (              ", "              )              ;              first              =              false              ;              System.out.print              (nums[i]              )              ;              }              System.out.print              (              "]"              )              ;              }              /**    * @param args the command line arguments    */              public              static              void              main(              String              [              ]              args)              {              final              int              HOWMANY              =              5              ;              final              int              LIMIT              =              20              ;              int              nums[              ]              =              new              int              [HOWMANY]              ;              // generate and store HOWMANY random integers into nums without duplicates              int              size              =              0              ;              Random              randgen              =              new              Random              (              )              ;              while              (size              <              HOWMANY)              {              int              num              =              1              +              randgen.nextInt              (LIMIT)              ;              // random int between 1 and LIMIT              if              (              !findNum(nums, size, num)              )              {              // num is not in current nums, add it, increase size by 1              nums[size++              ]              =              num;              }              }              Scanner keyboard              =              new              Scanner(              System.in              )              ;              System.out.format              (              "I've chosen %s numbers between 1 and %s\n",              HOWMANY, LIMIT)              ;              System.out.print              (              "Try to guess one: "              )              ;              int              guess              =              keyboard.nextInt              (              )              ;              // see if guess is in nums              if              (findNum(nums, HOWMANY, guess)              )              {              System.out.println              (              "you got it"              )              ;              }              else              {              System.out.println              (              "wrong guess"              )              ;              }              // print them              System.out.print              (              "nums:"              )              ;              printNums(nums, HOWMANY)              ;              System.out.println              (              )              ;              }              }            

Now it will behave as if you had created the project from scratch. The Run Project dialog initially doesn't work because the desired Main Class is not initially set in the Run Configuration.

The format function

The

format

function (see the tutorial) offers a way to embed arguments into a string. Used in the way we have it above,

System.out.format

is synoymous with

System.out.printf

, but the

format

function can has a more general usage as

String.format        

which allows you to create a string with embedded arguments, whether printed or not. Using the

format

function has advantages over the cumbersome usage of "

+

" to glue together fixed string segments and variables.

The first argument to the

format

function is the format string. The

%s

occurrences are the insertion points for the remaining arguments. For simplicity, the

%s

insertion point will always work, but for numerical arguments the

%d

and

%f

usages are common.

Commenting code sections and adding imports

After some research you discover a much way to print the

nums

array without the

printNums

function. First comment out the current output line:

// System.out.print("nums:"); printNums(nums, HOWMANY); System.out.println();        

and below it write the replacement:

            System.out.println            (            "nums: "            +            Arrays.toString            (nums)            )            ;          

This statement needs the additional import:

but you can have NetBeans insert it by:

Right-click on the document and choose Fix Imports from the menu.

Then test it to see that it has the same effect.

Printing incomplete arrays

The above usages of both

printnums

as well as

Arrays.toString

only work correctly because the number of things in the array is exactly the array size. In general, you will have unused array entries at the end and so it is necessary to restrict the range printed with this code:

            System.out.println            (            "nums: "            +            Arrays.toString            (            Arrays.copyOfRange            (nums,            0, HOWMANY)            )            )            ;          

Commenting Multiple Lines

Since you no longer need the

printNums

function, comment out the entire body (DON'T DELETE IT!). The slick, NetBeans way to do so is:

  • Select the body of the printNums function.
  • Type: "Control-/" (Windows/Linux) or "Command-/" (MAC). The comment string "//" is prepended to every line in the region.
  • If you wanted to "go back" the same operation undoes the comments.

Adding JavaDoc

Every member function should be documented via JavaDoc standards. NetBeans provides support for doing so. Start with the

findNum

function.

  1. Position the cursor on an empty line above the findNum function, just above the "p" in "private".
  2. Type "/**" then RETURN. The outline of the JavaDoc is generated for you:
                  /**    *     * @param nums    * @param upto    * @param key    * @return     */            
  3. Fill in the missing information like this:
                  /**    * findNum returns true if the key is one of the elements in the nums    * array prior to position upto    *     * @param nums: the array to search    * @param upto: one above the last search index    * @param key: the element to search for    * @return whether key is present or not    */            

Class-wide name change

You decide that the constant

HOWMANY

should really be

HOW_MANY

:

Select an occurrence of

HOWMANY

in any of the statements. Right-click and select Refactor ⇾ Rename to invoke a dialog in which you want this:

New Name:  
Apply Rename on Comments

Click Refactor.

Use an ArrayList

In most circumstances, an ArrayList offers an improvement over a standard array. Start by replacing the definition of

nums

with this:

ArrayList<Integer>            nums            =            new            ArrayList<>            (            )            ;          

Then there are three other sections which must be rewritten, and the

findNum

function can be commented out. Here is the solution:

Multi-system Project usage

A NetBeans project, once created, can easily be loaded onto different systems, so long as it does not reference external JAR files (which will be the case for all the projects in this course.)

A NetBeans project need not be within the "official" NetBeansProject directory. For example you can simply load it onto a USB flash drive, transport it to another system with NetBeans installed, and load it there. To load a project, simple navigate to the flash drive and Open it there!

Assume we're doing this on a Windows system for definiteness. Assume you have created a sample NetBeans project in the "usual" place, which would be in the Documents folder, more precisely:

C:\Users\LOGIN\Documents\NetBeansProjects        

Let's use project

NumberGuess

. It is represented by the folder:

C:\Users\LOGIN\Documents\NumberGuess\Hello        

Open the project on the flash drive

Insert your flash drive and open a folder which accesses the flash drive. Drag the

NumberGuess

folder into the flash drive folder.

From NetBeans, select, right-click on the Projects Window and choose Open Project. Navigate to the flash drive and select

Hello

which was copied onto the flash drive folder.

You now have 2 NumberGuess projects open! How do I know which one is which?

A very useful thing to know about is a Project's properties. To get this, again right-click on the project and select Properties from the menu (the last choice). Immediately you can tell which is which by the information in the Project Folder found at the top of the information dialog. So it is best to close the first one. Right click on the first one and select Close from the Menu.

How to Create a Java File in Netbeans

Source: https://www.cs.wcupa.edu/rkline/ds/netbeans.html

0 Response to "How to Create a Java File in Netbeans"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel