Java for Beginners 1 - Writing an Application Class in Java and Introduction to Dialog Boxes

Following is the first article in a series Java for Beginners that shows how to write an application class in Java and introduces the reader to dialog boxes, string to...

Following is the first article in a series Java for Beginners that shows how to write an application class in Java and introduces the reader to dialog boxes, string to integer conversion and other basics of Java.

Introduction

Prerequisites

JDK Version

Integrated Development Environment (IDE)

New Project Setup in IntelliJ IDEA

First Method: greeting()

Second Method: getFirstNumber()

Third Method: getSecondNumber()

Fourth Method: swapNumber()

Adding all methods to Main method

Exception Handling

Complete Code

Proof of working program

References

Introduction

We'll demonstrate the process of creation of a Java application classes that contains several methods. The class gives an object its attributes and methods and it is the essential building block of object-oriented software development. In our Java application, we will pay particular importance to properly document the code, so that each of the blocks or lines of the code well describes the functionality performed. In the naming, we will follow camelcase Java naming convention.

First Java Program

Let's create a class that that contains four different methods. The first method should be named greeting() and should display a JOptionPane that is customised like this:

- There should be no icon in this message box.

- The title bar on this message box should read ‘Welcome!’

- The message box should display ‘Welcome to my program!’

The second method should be named getFirstNumber() and should display a JOptionPane that is customised in the following ways:

- There should be a question mark icon on this message box.

- The title bar on this message box should read ‘First number?’

- The message box should allow the user to input the first number.

The third method should be named getSecondNumber() and should display a JOptionPane that is customised in the following ways:

- There should be a question mark icon on this message box.

- The title bar on this message box should read ‘Second number?’

- The message box should allow the user to input the second number.

The fourth method should be named swapNumber() and should display JOptionPanes as follows:

- In this method, you need to swap the value of the first number with the value of the second number. You can think of some temporary variable to do the swapping. Here is an example of how swapping works:

Before swapping: First = 10 Second = 5

After swapping: First = 5 Second = 10

- The new value of the first variable shall be incremented by 100, whereas the new value of the second variable shall be incremented by 50.

- The method should first display a `JOptionPane` with an information icon that has ‘Summary’ as the title bar text.

- This message box should display the first number (X) in the format ‘The new value of first number is: X’.

- The method should display another with`JOptionPane` an information icon that has ‘Summary’ as the title bar text.

- This message box should display the second number (Y) in a similar format to the first message: ‘The new value of the second number is: Y’.

- In order to accomplish this task, you will need to discover how to convert a string to an integer to perform the calculation.

Prerequisites

JDK Version

- Downloaded Java SE Development Kit 8 for Windows from Oracle’s website at: [ttp://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)

- Install to: C:\Program Files\Java\jdk-8.0.131

- Note you can also use JDK 9, but this article is written with vs 8 in mind.

Integrated Development Environment (IDE)

As my IDE of choice, I’ve decided to opt for IntelliJ IDEA for Windows. Download the community edition ideal for Java development from https://www.jetbrains.com/idea/download/#section=windows

New Project Setup in IntelliJ IDEA

In IntelliJ IDEA, first start the process by creating a new project by going to File / New / Project.

The following window opened, where you can selected the project JDK. Select 1.8 (java version 1.8.0_131):

The next step is to specify the Project Name and Project Location. I have decided to name the project as **Assignment_1 **and saved it in: C:\code\Assignment_1, as shown here:

When I pressed finish button, the project structure was created, with the Main.java class placed in the source code src folder created in underneath the C:\code\Assignment_1. For this project, due to its small size, I have opted out from using domain reversed package structure typically used in larger projects and in enterprise environments. Following screenshots illustrates the project code.

The code with the Main class which I’ll build my entire project on, looks like this:

public class Main { 
public static void main(String[] args) { 
} 
}

Okay, that said, let me show you how I'll go about designing each of the methods:

First Method: greeting()

The first method is called greeting() and displays a JOptionPane that is customised using following parameters:

- No icon on the message box.

- The title bar reads: ‘Welcome!’

- The message box displays ‘Welcome to my program!’

I have followed these steps:

- First I imported javax.swing.JOptionPane, using on-demand static import, which allows me to pop up a standard dialog box and also because I don’t later need to do import static javax.swing.JOptionPane.PLAIN_MESSAGE; to set PLAIN_MESSAGE explicitly through JOptionPane. Normally I wouldn’t use it, but for this project, it makes a nicely readable code.
import javax.swing.JOptionPane.*;
- I found the class JOptionPane documentation at [https://docs.oracle.com/javase/8/docs/api/javax/swing/JOptionPane.html](https://docs.oracle.com/javase/8/docs/api/javax/swing/JOptionPane.html)

- The JOptionPane.showMessageDialog allows me to display the dialog box and has couple of options available to it, the one’s that I will use are **parentComponent**, **message**, **title** and **messageType**.

**parentComponent**: “This parameter may be null, in which case a default Frame is used as the parent, and the dialog will be centered on the screen (depending on the L&F)” (Docs.oracle.com, 2018).

- **Message** is set to display ‘Welcome to my program!’

- **Title** is set to display: ‘Welcome!’

- As a **messageType** I’ve used PLAIN_MESSAGE, because that defines the style of the message, its look and feel and allows to display the dialog box without default icon. For example, if I had used INFORMATION_MESSAGE, I’d see information icon before the wording ‘Welcome to my program!’, that looks like this: ![](/wp-content/uploads/2018/01/word-image-3.png) , but wouldn’t be the desirable result.

The Main class, main() method are setup with main() method referencing the greeting method(), which ensures execution immediately upon the start of the program:

import static javax.swing.JOptionPane.*; 

public class Main { 

public static void main(String[] args) { 
// run first method, pop up the greeting dialog 
greeting();

} 

public static void greeting() { 
// parentComponent: This parameter is null. Default Frame is a parent. 
// message: The message box displays: ‘Welcome to my program!’ 
// title: The title bar on this message box is set to read ‘Welcome!’ 
showMessageDialog(null, "Welcome to my program!", "Welcome!", PLAIN_MESSAGE); 
} 
}

Once I ran the program, output of the first class called greeting() is showing the expected result:

Second Method: getFirstNumber()

The second method is called getFirstNumber() and displays a JOptionPane in a following manner:

- A question mark icon on the message box.

- The title bar reads ‘First number?’

- The message box allows the user to input the first number.

I’ve created a JOptionPane with showInputDialog to enable entry of the text. The message I left empty, and title is set accordingly. The text entered into input box, is passed straight into integer called getNumber1, which is then returned as a result of the getFirstNumber() method which is setup as an integer method. Input string gets converted to integer using Integer.parseInt(String) that parses the string argument as a signed decimal integer. Integer gets assigned to int variable getNumber1 and returned:

public static int getFirstNumber() { 
// A question mark icon on the message box. 
// The title bar reads ‘First number?’ 
// The message box allows the user to input the first number. 
// Input string gets converted to integer using Integer.parseInt 
// Integer gets assigned to int variable getNumber1 and returned 
int getNumber1 = Integer.parseInt(showInputDialog(null, "", "First number?", QUESTION_MESSAGE)); 
return getNumber1; 
}

Now, I adjusted main() method to pop up the input dialog and assign the value to integer called firstNumber, which I’ll use during calculations in the fourth method during swapping of the numbers.

// run second method, open input dialog box, assign result to integer firstNumber int firstNumber = getFirstNumber();

The input box looks like this:

Third Method: getSecondNumber()

The third method is called getSecondNumber() and displays a JOptionPane in a following manner:

- A question mark icon on the message box.

- The title bar reads ‘Second number?’

- The message box allows the user to input the second number.

This is exactly the same approach as created above in the second method. I’ve again used a JOptionPane with showInputDialog to enable entry of the text. The message is left empty and title is set accordingly. The text entered into input box, is passed straight into integer called getNumber2, which is then returned as a result of the getSecondNumber() method which is also setup as an integer method. Input string gets converted to integer using Integer.parseInt(String) that parses the string argument as a signed decimal integer. Integer gets assigned to int variable getNumber2 and returned:

public static int getSecondNumber() { 
// A question mark icon on the message box. 
// The title bar reads ‘Second number?’ 
// The message box allows the user to input the first number. 
// Input string gets converted to integer using Integer.parseInt 
// Integer gets assigned to int variable getNumber2 and returned 
int getNumber2 = Integer.parseInt(showInputDialog(null, "", "Second number?", QUESTION_MESSAGE)); 
return getNumber2; 
}

Now, I adjusted main() method to pop up the input dialog and assign the value to integer called secondNumber, which I’ll use during calculations in the fourth method during swapping of the numbers.

// run third method, open input dialog box, assign result to integer secondNumber int secondNumber = getSecondNumber();

The input box looks like this:

Fourth Method: swapNumber()

The fourth method is named swapNumber() and swaps the value of the first number with the value of the second number. So, if first number is 10 and second number is 5, after the swapping, it will be reversed so that first number is 5 and second number is 10. Additionally, the new value of first variable will be incremented by 100 and the new value of second variable shall be incremented by 50.

- The method displays a JOptionPane with an information icon that has ‘Summary’ as the title bar text.

- This message box should display the first number (X) in the format ‘The new value of the first number is: X’.

- The method should display another JOptionPane with an information icon that has ‘Summary’ as the title bar text.

- This message box should display the second number (Y) in a similar format to the first message: ‘The new value of the second number is: Y’.
public static void swapNumber(int firstNumber, int secondNumber) { 
// swap the value of the first number with second number and increment by 100 
int newFirstNumber = secondNumber + 100; 

// swap the value of the second number with first number and increment by 50 
int newSecondNumber = firstNumber + 50; 

// show the dialog with the swapped first number 
showMessageDialog(null, "The new value of first number is " + newFirstNumber, "Summary", INFORMATION_MESSAGE); 

// show the dialog with the swapped second number 
showMessageDialog(null, "The new value of second number is " + newSecondNumber, "Summary", INFORMATION_MESSAGE); 
}

Adding all methods to the main method

To tie it all together, I added all methods in order to the main method.

public static void main(String[] args) { 
// run first method, pop up the greeting dialog 
greeting(); 

// run second method, open input dialog box, assign result to firstNumber 
int firstNumber = getFirstNumber(); 

// run third method, open input dialog box, assign result to secondNumber 
int secondNumber = getSecondNumber(); 

// run swap method, with two variables extracted from second and third method 
swapNumber(firstNumber, secondNumber); 
}

Exception Handling

I want to note here, that under normal circumstances, I would prevent the exception in thread "main" in java.lang.Integer.parseInt in case I run across the situation where user inserts non-integer characters into input boxes, which could produce errors like these:

To fix this, I would do the check for such event and wouldn’t allow the user to enter, or ask them to change to an integer value. However, this wasn’t the part of the assignment, even though the implementation of error checking would be somewhat trivial.

To check if the entered string is numeric, I’d simply run it through a regular expression such as str.matches("-?\d+") or use Apache Commons: isNumeric from StringUtils class (Commons.apache.org, 2018).

Complete Code

import static javax.swing.JOptionPane.*;

public class Main {

    public static void main(String[] args) {
        // run first method, pop up the greeting dialog
        greeting();

        // run second method, open input dialog box, assign result to firstNumber
        int firstNumber = getFirstNumber();

        // run third method, open input dialog box, assign result to secondNumber
        int secondNumber = getSecondNumber();

        // run swap method, with two variables extracted from second and third method
        swapNumber(firstNumber, secondNumber);
    }

    public static void greeting() {
        // parentComponent: This parameter is null. Default Frame is a parent.
        // message: The message box displays: ‘Welcome to my program!’
        // title: The title bar on this message box is set to read ‘Welcome!’
        showMessageDialog(null, "Welcome to my program!", "Welcome!", PLAIN_MESSAGE);
    }

    public static int getFirstNumber() {
        // A question mark icon on the message box.
        // The title bar reads ‘First number?’
        // The message box allows the user to input the first number.
        // Input string gets converted to integer using Integer.parseInt
        int getNumber1 = Integer.parseInt(showInputDialog(null, "", "First number?", QUESTION_MESSAGE));

        // Integer gets assigned to int variable getNumber1 and returned
        return getNumber1;
    }

    public static int getSecondNumber() {
        // A question mark icon on the message box.
        // The title bar reads ‘Second number?’
        // The message box allows the user to input the first number.
        // Input string gets converted to integer using Integer.parseInt
        int getNumber2 = Integer.parseInt(showInputDialog(null, "", "Second number?", QUESTION_MESSAGE));

        // Integer gets assigned to int variable getNumber2 and returned
        return getNumber2;
    }

    public static void swapNumber(int firstNumber, int secondNumber) {
        // swap the value of the first number with second number and increment by 100
        int newFirstNumber = secondNumber + 100;

        // swap the value of the second number with first number and increment by 50
        int newSecondNumber = firstNumber + 50;

        // show the dialog with the swapped first number
        showMessageDialog(null, "The new value of first number is " + newFirstNumber, "Summary", INFORMATION_MESSAGE);

        // show the dialog with the swapped second number
        showMessageDialog(null, "The new value of second number is " + newSecondNumber, "Summary", INFORMATION_MESSAGE);
    }
}

Proof of working program

- Start the program

- Show greeting

- Enter First Number (10):

- Enter Second Number (5)

- Swap numbers

- Display result for first number (5+100 = 105)

- Display result for second number (10+50 = 60)

References

Docs.oracle.com. (2018). JOptionPane (Java Platform SE 8 ). [online] Available at: https://docs.oracle.com/javase/8/docs/api/javax/swing/JOptionPane.html [Accessed 15 Jan. 2018].

Commons.apache.org. (2018). StringUtils (Apache Commons Lang 3.7 API). [online] Available at: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isNumeric(java.lang.CharSequence) [Accessed 16 Jan. 2018].