0% found this document useful (0 votes)
46 views22 pages

CENG325_3_GUI-Temperature converter

This document outlines a step-by-step guide for creating a GUI-based Temperature Converter application using Swing and NetBeans IDE. It covers the initial setup, GUI component arrangement, and the addition of application logic for converting temperatures from Celsius to Fahrenheit and Kelvin, as well as saving and displaying temperature values in a table. The document is structured into multiple parts, detailing the process from project creation to implementing advanced features like file handling and user interaction.

Uploaded by

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

CENG325_3_GUI-Temperature converter

This document outlines a step-by-step guide for creating a GUI-based Temperature Converter application using Swing and NetBeans IDE. It covers the initial setup, GUI component arrangement, and the addition of application logic for converting temperatures from Celsius to Fahrenheit and Kelvin, as well as saving and displaying temperature values in a table. The document is structured into multiple parts, detailing the process from project creation to implementing advanced features like file handling and user interaction.

Uploaded by

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

CENG325- GUI- Temperature Converter Step by step

This document provides an introduction to Graphical User Interface (GUI) programming with Swing and
the NetBeans IDE.

Lab 1: Simple Celsius Converter


The goal of this lab is to introduce the Swing API by designing a simple application that converts
temperature from Celsius to Fahrenheit. Its GUI will be basic, focusing on only a subset of the available
Swing components. We will use the NetBeans IDE GUI builder, which makes user interface creation a
simple matter of drag and drop. Its automatic code generation feature simplifies the GUI development
process, letting you focus on the application logic instead of the underlying infrastructure.

The finished GUI for this application will look as follows:

The CelsiusConverter Application.

From an end-user's perspective, usage is simple: enter a temperature (in Celsius) into the text box, click
the "Convert" button, and watch the converted temperature (in Fahrenheit) appear on screen. The
“minimize”, “maximize”, and “close” buttons will behave as expected, and the application will also have
a title that appears along the top of the window.
From a programmer's perspective, we will write the application in two main stages. First, we will
populate the GUI with the various Swing components and arrange them as shown above. Then, we will
add the application logic, so that the program actually performs a conversion when the user presses the
"Convert" button.

Part 1: Setting up the CelsiusConverter Project


This part is common for most projects in NetBeans IDE. Here, we have the initial steps that describe the
settings that are specific to this GUI application.

Step 1: Create a New Project


To create a new project, launch the NetBeans IDE and choose New Project from the File menu:
Creating a New Project

Step 2: Choose General -> Java Application


Next, select General from the Categories column, and Java Application from the Projects column:

Press the button labeled "Next" to proceed.


Step 3: Set a Project Name
Now enter "CelsiusConverterProject" as the project name. You can leave the Project Location and
Project Folder fields set to their default values, or click the Browse button to choose an alternate
location on your system.

Make sure to deselect the "Create Main Class" checkbox; leaving this option selected generates a new
class as the main entry point for the application, but our main GUI window (created in the next step) will
serve that purpose, so checking this box is not necessary. Click the "Finish" button when you are done.

When the IDE finishes loading, you will see a screen similar to the above. All panes will be empty except
for the Projects pane in the upper left hand corner, which shows the newly created project.
Step 4: Add a JFrame Form
Now right-click the CelsiusConverterProject name and choose New -> JFrame Form (JFrame is the Swing
class responsible for the main frame for your application.) You will learn how to designate this class as
the application's entry point later in this lab.

Step 5: Name the GUI Class


Next, type CelsiusConverterGUI as the class name, and learn as the package name. You can actually
name this package anything you want, but here we are following the tutorial convention of naming the
package after the lesson in which is resides.

The remainder of the fields should automatically be filled in, as shown above. Click the Finish button
when you are done.
When the IDE finishes loading, the right pane will display a design-time, graphical view of the
CelsiusConverterGUI. It is on this screen that you will visually drag, drop, and manipulate the various
Swing components.

Part 2: Some tools for GUI applications


Before proceeding with GUI application creation, some Netbeans IDE features need to be explained. We
will discuss the following features below: the Palette, the Design Area, the Property Editor, and the
Navigator.

The Palette

The Palette contains all of the components offered by the Swing API; example: JLabel is a text label, JList
is a drop-down list, etc.

From this list, our application will use JLabel (a basic text label), JTextField (for the user to enter the
temperature), and JButton (to convert the temperature from Celsius to Fahrenheit).

The Design Area


The Design Area is where you will visually construct your GUI. It has two views: source view, and design
view. Design view is the default, as shown below. You can toggle between views at any time by clicking
their respective tabs.
The figure above shows a single JFrame object, as represented by the large shaded rectangle with blue
border. Commonly expected behaviors (such as quitting when the user clicks the "close" button) are
auto-generated by the IDE and appears in the source view between uneditable blue sections of code
known as guarded blocks.

A quick look at the source view reveals that the IDE has created a private method named
initComponents, which initializes the various components of the GUI. It also tells the application to "exit
on close", performs some layout-specific tasks, then packs the (soon to be added) components together
on screen. No need to understand this code in any detail.
The Property Editor
The Property Editor does what its name implies: it allows you to edit the properties of each component.
The Property Editor is intuitive to use; in it you will see a series of rows — one row per property — that
you can click and edit without entering the source code directly. The following figure shows the Property
Editor for the newly added JFrame object:

The screenshot above shows the various properties of this object, such as background color, foreground
color, font, and cursor.

The Navigator
The last component of the NetBeans IDE that we will use here is the Navigator. To open it, click on
“Window” in the menu bar then click on Navigator. It will appear in the down left side of the screen,
click on Design to see the following:
The Navigator

The Navigator provides a graphical representation of your application's components. We will use the
Navigator to change a few variable names to something other than their defaults.

Part 3: Creating the CelsiusConverter GUI

This section explains how to use the NetBeans IDE to create the application's GUI. As you drag each
component from the Palette to the Design Area, the IDE auto-generates the appropriate source code.

Step 1: Set the Tiltle


First, set the title of the application's JFrame to "Celsius Converter", by single-clicking the JFrame in the
Navigator:
Selecting the JFrame

Then, set its title with the Property Editor:

Setting the Title

You can set the title by either double-clicking the title property and entering the new text directly, or by
clicking the button and entering the title in the provided field. Or, as a shortcut, you could single-click
the JFrame of the Navigator and enter its new text directly without using the property editor.
Step 2: Add a JTextField
Next, drag a JTextField from the Palette to the upper left corner of the Design Area. As you approach the
upper left corner, the GUI builder provides visual cues (dashed lines) that suggest the appropriate
spacing. Using these cues as a guide, drop a JTextField into the upper left hand corner of the window as
shown below:

Adding a JTextField

Step 3: Add a JLabel


Next, drag a JLabel onto the Design Area. Place it to the right of the JTextField, again watching for visual
cues that suggest an appropriate amount of spacing. Make sure that text base for this component is
aligned with that of the JTextField. The visual cues provided by the IDE should make this easy to
determine.
Adding a JLabel

Step 4: Add a JButton


Next, drag a JButton from the Palette and position it to the left and underneath the JTextField. Again,
the visual cues help guide it into place.
Adding a JButton

Step 5: Add a Second JLabel


Finally, add a second JLabel, repeating the process in step 2. Place this second label to the right of the
JButton, as shown above.

Adding a Second JLabel


Part 4: Adjusting the CelsiusConverter GUI

With the GUI components now in place, it is time to make the final adjustments. There are a few
different ways to do this; the order suggested here is just one possible approach.

Step 1: Set the Component Text


First, double-click the JTextField and JButton to change the default text that was inserted by the IDE.
When you erase the text from the JTextField, it will shrink in size as shown below. Change the text of the
JButton from "JButton1" to "Convert." Also change the top JLabel text to "Celsius" and the bottom to
"Fahrenheit."

Setting the Component Text

Step 2: Set the Component Size


Next, shift-click the JTextField and JButton components. This will highlight each showing that they are
selected. Right-click Same Size -> Same Width. The components will now be the same width, as shown
below. When you perform this step, make sure that JFrame itself is not also selected. If it is, the Same
Size menu will not be active.
Setting the JTextField and JButton Sizes

Step 3: Remove Extra Space


Finally, grab the lower right-hand corner of the JFrame and adjust its size to eliminate any extra
whitespace. Note that if you eliminate all of the extra space (as shown below) the title (which only
appears at runtime) may not show completely. The end-user is free to resize the application as desired,
but you may want to leave some extra space on the right side to make sure that everything fits correctly.

The Completed GUI


The GUI portion of this application is now complete! If the NetBeans IDE has done its job, you should
feel that creating this GUI was a simple, if not trivial, task. But take a minute to click on the source tab;
you might be surprised at the amount of code that has been generated.

To see the code in its entirety, scroll up and down within the IDE as necessary. You can expand or
collapse certain blocks of code (such as method bodies) by clicking the + or - symbol on the left-hand
side of the source editor.

Part 5: Adding the Application Logic


It is now time to add in the application logic.

Step 1: Change the Default Variable Names


The figure below shows the default variable names as they currently appear within the Navigator.
For each component, the variable name appears first, followed by the object's type in square brackets.
For example, jTextField1 [JTextField] means that "jTextField1" is the variable name and "JTextField" is its
type.
Default Variable Names

The default names are not very relevant in the context of this application, so it makes sense to change
them from their defaults to something that is more meaningful. Right-click each variable name and
choose "Change variable name." When you are finished, the variable names should appear as follows:

New Variable Names

The new variable names are "tempTextField", "celsiusLabel", "convertButton", and "fahrenheitLabel".
Each change that you make in the Navigator will automatically propagate its way back into the source
code. You can rest assured that compilation will not fail due to typos or mistakes of that nature.

Step 2: Add the Temperature Conversion Code


Double click on the Convert button. This will take you to the ActionPerformed of the button.
To convert the temperature from Celsius to Fahrenheit, you should use the following formula:
Temperature in Fahrenheit = (Temperature in Celsius)*1.8 + 32.
The final step is to simply paste the temperature conversion code into the empty method body. The
following code is all that is necessary to convert a temperature from Celsius to Fahrenheit:

//Parse degrees Celsius as a double and convert to Fahrenheit.


int tempFahr = (int)((Double.parseDouble(tempTextField.getText()))
* 1.8 + 32);
fahrenheitLabel.setText(tempFahr + " Fahrenheit");
Simply copy this code and paste it into the convertButtonActionPerformed method as shown below:

With the conversion code in place, the application is now complete.

Step 3: Run the Application


Running the application is simply a matter of choosing Run -> Run Main Project within the NetBeans IDE.
The first time you run this application, you will be prompted with a dialog asking to set
CelsiusConverterGUI as the main class for this project. Click the OK button, and when the program
finishes compiling, you should see the application running in its own window.
Lab 2: Celsius Converter and Tracker
In this lab, we are going to expand the developed application in Lab 1 “Celsius Conversion” by adding
more functionalities to it such as conversion to Kelvin, saving the temperatures to a file and showing
them in a table.

The final application that we will call “Celsius Converter and Tracker” will look as follows:

Part 1: Adding the Conversion to Kelvin

First, we will expand the CelsiusConverter project to include also conversion from Celsius to Kelvin.
To do this, add a new Button “Convert” and another “Label” for Kelvin conversion to have the following:

Change the name of the added components to the following variable names: "convertButtonKel" and
"kelvinLabel".

Double click on the new Convert button and copy the following code in the ActionPerformed of the
button:
private void convertButtonKelActionPerformed(java.awt.event.ActionEvent
evt) {
//Parse degrees Celsius as a double and convert to Kelvin
int tempFahr = (int)(Double.parseDouble(tempTextField.getText())
+ 273.15);
kelvinLabel.setText(tempFahr + " Kelvin");
}

Note: Temperature in Kelvin = Temperature in Celsius + 273.15.

Part 2: CelsiusConverter with ComboBox

In this part, we are going to merge the conversion from Celsius to Fahrenheit and Kelvin in one button
using the ComboBox, to have the following form:

First, organize you JFrame to have the components in the figure above. The first JtextField where you
enter the temperature in Celsius will be named “jTextField1” and the second JtextField where you enter
the temperature in Celsius will be named “jTextField2”. The ComboBox name is “jComboBox1”.

To fill in the ComboBox, write the following code in the default constructor of the main class of your
project:
jComboBox1.addItem("Fahrenheit");
jComboBox1.addItem("Kelvin");

Also, put the following code in the ActionPerformed of the “Convert”button:

if (jComboBox1.getSelectedItem()=="Fahrenheit")
{
Int tempFahr = (int)((Double.parseDouble(jTextField1.getText()))
*1.8 + 32);
jTextField2.setText(tempFahr + " Fahrenheit");
}
if (jComboBox1.getSelectedItem()=="Kelvin")
{
int tempKelv = (int)(Double.parseDouble(jTextField1.getText())
+273.15);
jTextField2.setText(tempKelv + " Kelvin");
}

Now, you can run your application and test that it does convert from Celsius to Fahrenheit or Kelvin
depending on the selected choice in the ComboBox.
Part 3: Saving temperature values to a file

Here, we will save each entered temperature in a text file that we will name "Temp.txt".

To do this we will add a new button “Save” and enter the following code in its ActionPerformed:

FileWriter out;
try {
out = new FileWriter("Temp.txt", true);
out.write(jTextField1.getText()+"\n");
out.close();
} catch(IOException e) {
System.out.println("Error appending to file " + "Temp.txt");
}

Part 4: Showing the saved temperatures in a table

The idea here is to show the saved results in a table when the button “Show Results” is clicked.
This should create a new JFrame with a Table inside. Then, the temperature values are read from the file
"Temp.txt" and shown in the table as follows:

To do so, add a new button “Show Results” and enter the following code in its ActionPerformed:

ArrayList<String> myArr = new ArrayList<>();


int rows;
try {
FileInputStream fStream = new FileInputStream("Temp.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(fStream));
while (in.ready()) {
myArr.add(in.readLine());
}
in.close();
}
catch (IOException e) {
System.out.println("File input error");
}

rows = myArr.size();

JTable table = new JTable(rows, 1);


JFrame f = new JFrame();
f.setSize(100, 300);
f.add(new JScrollPane(table));
f.setVisible(true);

table.getColumnModel().getColumn(0).setHeaderValue("Temperature");

for (int i=0; i< myArr.size(); i++) {


table.setValueAt(myArr.get(i),i,0);
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy