0% found this document useful (0 votes)
43 views36 pages

COS221 - 2024-2025 Lecture 2

This document outlines a Java programming course focused on creating GUI applications using IntelliJ IDE. It covers essential components like JTextFields, JLabels, and JButtons, along with examples for building a simple arithmetic application and a temperature converter. Additionally, it explains packaging Java applications into JAR files for distribution.

Uploaded by

patgg16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views36 pages

COS221 - 2024-2025 Lecture 2

This document outlines a Java programming course focused on creating GUI applications using IntelliJ IDE. It covers essential components like JTextFields, JLabels, and JButtons, along with examples for building a simple arithmetic application and a temperature converter. Additionally, it explains packaging Java applications into JAR files for distribution.

Uploaded by

patgg16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Week Two

Basic Java Programming


The COS221 Team
[2024|2025]
Main Text for this Course
Title
Introduction To Java Programming,
Comprehensive Version (2015, 7th Edition)

Author
Liang, Y. Daniel

Download for your progressive learning


Learning Objectives

▪ At the end of this lecture, the student is expected to:


▪ Creating GUI Programs
▪ JTextFields, JLabels, and JButtons
▪ Receiving Inputs and Displaying Outputs via JTextFields and
JLabels
▪ Examples/Exercises on Java GUI Programming
▪ Packaging your Java Programs

3
Creating GUI Programs

▪ The IntelliJ IDE provides these several layouts for the GUI
application development:
■ Border Layout ■ Card Layout ■ Flow Layout
■ Form Layout ■ GridBag Layout
■ Grid Layout*
▪ In this class/course, the Grid Layout (default layout) will
be used as the main layout for our GUI applications.
4
Essential Controls
▪ The essential controls user inputs.
required for developing ▪ They can also be used to
display texts.
GUI applications in Java ▪ Jlabels
include: ▪ They can only be used to
▪ JPanels display texts/images.
▪ All other controls are placed ▪ Jbuttons
on these panels ▪ They are used to initiate
▪ JTextFields commands or trigger events
▪ They are used for collecting in the GUI program.

5
Some Common Properties/Methods of the JTextField 6

Property Function
Editable True or False. Determines if the text within the control can be
edited by the user or not.
Font Used to control the font properties of the control
Text Holds the text within the control
ToolTipText Contains the tooltip string that has been set with setToolTipText
Horizontal The horizontal alignment of the text
Alignment
String getText Returns the text contained in a TextComponent
Void setText Sets the text of the TextComponent to a specified text
Some Common Properties/Methods of the JLabel 7

Property Function
Font Used to control the font properties of the control
Text Holds the text within the control
ToolTipText Contains the tooltip string that has been set with setToolTipText
Icon Controls the graphic image (glyph, icon) that the label displays if
used for that purpose
Icon getIcon Returns the graphic image (glyph, icon) that the label displays
Void setIcon Sets the graphic image that the label displays
String getText Returns the text that the label displays
Void setText Defines the single line of text this component will display.
Example 1
Create a Simple Arithmetic Application
▪ Create a GUI application that will enable users to
Add, Subtract, Multiply and Divide two numbers.
▪ Steps:
▪ Right-click on the folder (src or com.company) that directly
houses your source codes.
▪ Navigate through New → Swing UI Designer → GUI Form
▪ Type the name of the application and click “OK”
8
Naming the GUI application form & the Basic Design (Pre-Run View) 9

Just make sure you have the following:


▪ Three JLabels (“First Input”, “Second Input”, and “Output”)
▪ Three JTextFields for the two inputs and the output
▪ Four JButtons for addition, multiplication, division, and subtraction.
▪ Set the field name of the JPanel to “MainPanel”
Some specific Configurations 10

Control Configuration
textField3 Editable property: Unchecked
MainPanel Field Name property: MainPanel
”Add” Button Field Name property: addButton
Text property: Add
”Subtract” Button Field Name property: subtractButton
Text property: Subtract
”Multiply” Button Field Name property: multiplyButton
Text property: Multiply
”Divide” Button Field Name property: divideButton
Text property: Divide
The field name property is the programmable name of a control, i.e. the variable name of the
control by which the control is referenced in the code view.
Activating your Form & Writing your Code
Running the Application
▪ At this stage, the application cannot be run, some steps
still needs to be taken to complete the Form setup.
▪ You should notice two views of your SimpleCalc
application:
▪ SimpleCalc.form
▪ Just a design
▪ SimpleCalc.java
▪ This view is where all the necessary codes are written.
12
Preliminary Steps – SimpleCalc.java

▪ Firstly, add “extends JFrame” to the class declaration of


SimpleCalc.java, for the header of the class to look like this:
public class SimpleCalc extends JFrame {
▪ This enables the class to inherit from the JFrame class and
allows it to perform like a JFrame – which is the main UI
component of Java.
▪ Next, create a constructor and a main method for
SimpleCalc.java, see next slide for their contents.
13
SimpleCalc.java – Constructor & Main Method 14

public SimpleCalc(){
setTitle("Simple Calculator"); // 1
setContentPane(MainPanel); // 2
setSize(350, 300); // 3
setDefaultCloseOperation(EXIT_ON_CLOSE); // 4
setLocationRelativeTo(null); // 5
setVisible(true); // 6
}

public static void main(String[] args) {


new SimpleCalc();
}

Note: The code blocks displayed here should be placed within the SimpleCalc.java class.
This means the closing curly brace of the class should appear after the code blocks.
Explaining the Constructor

▪ The title of the JFrame is set, this determines what


appears on top of the JFrame when it is running.
▪ This makes sure the JFrame “knows” that the JPanel
named “MainPanel” is responsible for displaying all the
other controls.
▪ Enables the JFrame to appear at the centre of the screen
▪ The JFrame can be seen on the screen when the
application runs.
15
Running the Application 16

▪ Click on the green button created by the IDE beside your


main method
▪ Click the first option that it brings out
▪ You can now interact with your application
▪ However, the JButtons are still dormant.
▪ It is time to add functionality to the JButtons.
Activating the “Add” button
▪ Follow the steps below:
▪ Right-Click on the button
▪ Click “Create Listener”
▪ Click “ActionListener”
▪ Click “Ok”
▪ Thereafter, the programmer can implement the “Add” button
in the space where the comment “type your code here” is
placed.
▪ Repeat this same procedure for all other buttons.
17
Inside the Add (1) and Subtract (2) buttons 118
// Get the inputs
double input1 = Double.parseDouble(textField1.getText()); // 1
double input2 = Double.parseDouble(textField2.getText()); // 2

double sum = input1 + input2; // 3


textField3.setText("" + sum); // 4 - displays the output

2
double input1 = Double.parseDouble(textField1.getText()); // 1
double input2 = Double.parseDouble(textField2.getText()); // 2

double sum = input1 - input2; // 3


textField3.setText("" + sum); // 4 - displays the output
Brief Explanation

▪ You would notice the use of getText and setText


methods of the JTextField class/component
▪ The former was used in the first two lines of the buttons’
implementations.
▪ It is simply used to retrieve text from the JTextField.
▪ In contrast, the setText method allows the programmer
to set the text of the JTextField component, in order to
display data in it.
19
Exercise

▪ Complete the application by implementing the


“Multiply” and “Divide” buttons
▪ Modify the application so that a JLabel control is
used to display the output rather than a JTextField
control.

20
Enhancing your code – Handling Exceptions

▪ To avoid unexpected behavior in your code, wrap it around a


try-block.
▪ Then create a corresponding catch-block in your code to
catch the exception whenever an unexpected input is entered
by the user
▪ Also, it is useful for catching unexpected events.
▪ If this is done properly, users of your application will get
reasonable outputs from your application regardless of
unexpected events.
21
“Add” button implementation with a try-catch block 22

addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try { // Introduce a try-block
// Get the inputs
double input1 = Double.parseDouble(textField1.getText()); // 1
double input2 = Double.parseDouble(textField2.getText()); // 2

double sum = input1 + input2; // 3


textField3.setText("" + sum); // 4 - displays the output
}
catch(Exception ex){ // Introduce a corresponding catch-block
JOptionPane.showMessageDialog(null, "Check your inputs\n" + ex.getMessage());
}
}
});
Creating GUI Programs in IntelliJ:
Summary of Steps
▪ Design the JFrame (YourClass.form)
▪ Add “extends JFrame” to the class declaration of YourClass.java:
public class YourClass extends JFrame {…}
▪ Create a constructor and a main method for YourClass.java
▪ Sample codes within the constructor and the main method can be found in
Example 1.
▪ Create ActionListeners for your JButtons
▪ Implement the buttons with the created ActionListeners.
▪ It is desirable you follow this order to avoid hiccups.
23
Example 2: Temperature Converter 24

Control Field Name/Text


JLabel Field Name: celsiuslabel
Text: Celcius
JTextField Field Name: celsiustextfield
Text: None
JButton Field Name: convertbutton
Text: Convert!
JLabel Field Name: lblResult
Text: Result
Feel free to design your form in a different way from what was
depicted in the slide.

Only make sure the controls are based on the settings in this
table to avoid errors in your own code.
Completion of the Application
setTitle("Temperature Converter"); - Codes 1: Inside the constructor 25
setVisible(true); 1: Inside the constructor
setLocationRelativeTo(null);
setSize(200, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(mainPanel);

public static void main (String[] arg){


new Temp_converter(); 2: The main method
}

String celsiusText = celsiustextfield.getText();


double tempFahr = (Double.parseDouble(celsiusText) * 1.8) + 32;
String result = String.format("%.2f Fahrenheit", tempFahr); // 1
lblResult.setText(result); // 2
3: Inside the “Convert!” button
Example 2 | Explanation

1. The code designated by this comment number uses the


String.format() facility provided by Java to format output in C-
style.
▪ The string expression “%.2f” enables a floating-point number to be
expressed in two decimal places within the created string.
▪ What follows after the quote represent the variable(s) that will replace the
format specifier(s) within the string in the order in which they appear.
2. The eventual string created within the result variable is displayed
in the JLabel control (lblResult).

26
Example 2: What the constructor looks like 27
Packaging your
Java Applications
Working with JARs

▪ A JAR (Java Archive) is a package file format typically used


to aggregate many Java class files and associated
metadata and resources (text, images, etc.) into one file
to distribute application software or libraries on the Java
platform
▪ Once a JAR is created, it can be distributed or given to
your friends to test your Java application without them
running the application from the IntelliJ IDEA IDE.
29
First Step

▪ For an end user to use your application (JAR), the Java


Runtime Environment (JRE) must have been installed on
his/her machine.
▪ To install Java (JRE) on your machine, Google or Bing
search the term: “download and install Java” on your
browser.
▪ Download and install Java on your PC via the first link.
30
Creating JARs with IntelliJ IDEA
Stage Zero
▪ Navigate through “File → Project Structure”
▪ Under Project Settings, Click “Project”.
▪ Under the “Project SDK” settings, select the lowest
SDK version to be sure your JAR will run on any
machine.
▪ SDK Version 1.8?
▪ Click “Apply”, then “Ok”.
31
Creating JARs with IntelliJ IDEA
Stage One
▪ Navigate through “File → Project Structure”
▪ Under Project Settings, Click “Artifacts”, then the plus (+)
sign.
▪ Navigate through “JAR → From modules with
dependencies…”
▪ On the dialog window, select the main class (the main
program that should first run when the JAR is run).
▪ Press “Ok” for the remaining steps.
32
Creating JARs with IntelliJ IDEA
Stage Two
▪ Navigate through “Build → Build Artifacts”
▪ Select/Click the appropriate action: “Build” for the
project you wish to create a JAR for.
▪ Under “Build Artifact → Action” immediately after Step 1.
▪ To locate the JAR, go through project_folder → out →
artifacts → project_folder_jar (preferably start from
C:\...\IdeaProjects\...), sample here:
33
Running the JAR 34
Summary Exercises —1

▪ To be done in the class


▪ Write a program to find the Area of a Circle
▪ Program to convert inches to Centimetres
▪ Program to average two double-precision numbers

35
Summary Exercises — 2

▪ Write a program that reads in two numbers: an


account balance and an annual interest rate
expressed as a percentage.
▪ Your program should then display the new balance after a
year.
▪ There are no deposits or withdrawals—just the interest
payment.
36

You might also like