0% found this document useful (0 votes)
69 views51 pages

CENG325 - 2 - GUI

This document provides instructions for developing a GUI time calculator application using Netbeans. It discusses how to: 1. Use a combo box to select the output unit (hours, minutes, seconds). 2. Display the input values and output in a table. 3. Add a "Clear" button to reset the input fields. 4. Save calculation results to an ArrayList to allow viewing multiple calculations. The document provides code snippets and explanations for implementing these features in the time calculator application.

Uploaded by

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

CENG325 - 2 - GUI

This document provides instructions for developing a GUI time calculator application using Netbeans. It discusses how to: 1. Use a combo box to select the output unit (hours, minutes, seconds). 2. Display the input values and output in a table. 3. Add a "Clear" button to reset the input fields. 4. Save calculation results to an ArrayList to allow viewing multiple calculations. The document provides code snippets and explanations for implementing these features in the time calculator application.

Uploaded by

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

Lecture2

GUI Design

GUI using Netbeans


Content
1. Time calculator
1. How to use a Combo box
2. How to show output in a table
3. Add Clear Button
2. Assignment1: Temperature Converter

3. Assignment2: Student Registraion Form


1. How to use radio Button and radio Button group
2. How to use a check box
3. Add Close Button
4. How to save data in a file
5. How to read data from a file
6. How to use ArrayList
Time calculator
 You are asked to design an application that calculates time in
hours, minutes or seconds.
 The user enters a time in days or hours or mins and presses the
corresponding button to display the time in hours , mins or sec.
 The GUI of you application

is similar to the following:


Remember:
1Day=24 h
1h=60min
1min=60secs
N.B set 0 as default input to avoid
exceptions
Time calculator
 For each button ActionPerformed handler make the
folllowing:
1. Read the days textfield and parse to double.
2. Read the hous textfield and parse to double.
3. Read the minutes textfield and parse to double.

4. For the In hours Button: result=Days*24+hours+minutes/60


5. For the In minutes Button:
result=Days*24*60+hours*60+minutes
6. For the In seconds Button:
result=Days*24*3600+hours*3600+minutes*60
Time Calculator: Add a ComboBox

 A JComboBox lets the user choose one of


several choices.
 By default it is non-editable
 Used for limited space/ few # of options(items)
 With Java Swing ComboBox , only one choice
can be selected.
How to use a Combo Box
In your code, you
Add a Combo to your Calculator Frame can add the items
by calling the
1. Name the variable (combo) addItem( )
2. Set the label text to: “Calculate in:” method for each
item, it takes a
3. To set the item list: String argument.
a) Click on the comboBox
b) In the Properties, edit the row model (Hours Minutes Seconds)
How to use a Combo Box
Read the user choice in the ComboBox:
Comb.getSelectedItem( )
Note that getSelectedItem( ) return an Item object, to read the
String of the choice you have to use toString()
So, you will have use the following:
Combo.getSelectedItem( ).toString( )
Note that you can read the index of the choice by using
getSelectedIndex( )
How to use a Combo Box
Remove items from the ComboBox:
You can remove all comboBox items by using the following
method:
Combo.removeAllItems( )
It removes all the items from the item list, so you can set a
new list.
You can also remove a specific Item by using :
Combo.removeItemAt( int index)
You have to specify the index in the list at which to remove
the item.
How to use a Combo Box
 In your Time Calculator
1. Add a new Button Convert
2. Add a new Label Result
 The user will enter days, hours and minutes.
 Chooses from the comboBox to which time
to convert.
 Then Presses the button Convert
 The result is displayed in the Result label
with the corresponding unit.
How to use a Combo Box
 When the button Convert is pressed:
1. User inputs are read from the textfields as Double values>>
Double.parseDouble(variableName.getText( ))
2. The selected item is detected from the comboBox >>
Combo.getSelectedItem( ).toString( )
3. The selected item is tested if it is “Hours”, “Minutes” or “Seconds” (as
are written in the comboBox item list)>>
If(Combo.getSelectedItem( ).toString( ).equals( “hours”)){ do hours
operation}
else If(Combo.getSelectedItem( ).toString( ). equals( “Minutes”)) {….

If …else if…else is used since only one item can be selected.

N.B You can use the old button action performed to copy the code.
How to use a Combo Box
 Where to write the code?
1. Case1: In our application the user must press the button to show
the result>>> you have to set the button action perform handler>>
double click your button and write the necessary code.
2. Case2: If you want the result to be shown when the choice is
selected from the comboBox >> you have to set the comboBox
action performed handler>>double click your comboBox and
write the code. In this case, you can delete the Convert button
Clear Button
 Now add a new button>>Clear button
 This button is used to clear the textfields.
 When the user presses Clear button, an empty string is written
in the textfields>> TextFieldVariableName.setText(“”);
 But, in our time calculator a value “0” is needed to avoid exception.
 So, make the Clear button writes “0” in the textfields>>
TextFieldVariableName.setText(“0”);
Class constructor
 A constructor in Java is a special method that is used
to initialize objects.
 It has always the same name as the class name without
a return value.
 The constructor is called when an object of a class is
created.
 It can be used to set initial values for object attribute.
Example
// Create a MyClass class

public class MyClass {


int x;
}// Create a class attribute
public MyClass() { // Create a class constructor for the MyClass class
x = 5; // Set the initial value for the class attribute x

}
public static void main(String[] args){
MyClass myObj = new MyClass(); // Create an object of class MyClass

//(This will call the constructor)

System.out.println(myObj.x); // Print the value of x

}
}
// Outputs 5
Default Form Constructor
public Myform() {
initComponents();
}

- All the actions that we want them to be applied at the form


creation could be added under the initComponents();
- E.g. if we want to fill in a combo items or to add table
headers.
Show output in a Table
 Now, we would like to organize • Add a Scroll pane to your GUI.
the inputs and results a table. • Add a Table to the Scroll pane.
• To change your table settings>>click
 We can use a Jtable component. on the table>> model row in the
Properties>> Table Settings>>Insert,
Delete, edit Titles.

Row 0
Row 1

Col 0 Col 1
Show output in a Table
 You can set the column header within your code using
the following:
table.getColumnModel().getColumn(0).setHeaderValue
(“Hours");

 This should be done as soon as opening your form for


the first time, which means in the constructor.
Show output in a Table
 Set the Column headers as shown.
 Add the code in the Convert button to show the inputs and
results in the table.
 To set a value in the table, you use
 setValueAt(value, row, column) method>>

TableVariableName.setValueAt( ).
 Note that the first row and column index is 0.
Show output in a Table
 Modify the Convert Button action performed:
1. Define a string variable>>String resultVal
2. Change the if else statements:
1. For hours: resultVal=d*24+h+m/60+ “hours”;
2. For minutes: resultVal=d*24*60+h*60+m+ “mins”;
3. For seconds: resultVal=d*24*60*60+h*60*60+m*60+ “sec”;
3. You can now delete the result label from your design.
4. Set the table values.
Not
Show output in a Table here

int row=0;// start from the first row index


//Test which time is selected
if(item.equals("Hours")){ resultVal=d*24+h+m/60+"hours"; }
else if(item.equals("Minutes"))
{ resultVal=d*24*60+h*60+m+"mins"; }
else{ resultVal=d*24*60*60+h*60*60+m*60+"sec"; }
//set the values
table.setValueAt(d, row, 0);
table.setValueAt(h, row, 1);
table.setValueAt(m, row, 2);
table.setValueAt(resultVal, row, 3);
row++;// Go to next row
Show output in a Table
 Test your Application.
 Is their any problem?
 Why every operation is written in the same row (first row)?
 How can we solve this problem?
Show output in a Table
 Define int row as an integer property for the TimeConverter
Frame.
 Set the initial value >>row=0; in the constructor

public class timeform extends javax.swing.JFrame {


int row;
public timeform() {
initComponents();
table.getColumnModel().getColumn(0).setHeaderValue("Days");
row=0;
}
Open a new form from a button
 Create a new form for showing the results called
showresults for example.
 In the actionPerformed of a new button on your initial
form, you can add the code:
showresults anyname= new showresults();
anyname.setVisible(true);

 This will create an instant from the class object with the
name anyname and will make it visible on button click.
Write results in an array list
public class timeform extends javax.swing.JFrame {

private int row; Class


constructor
protected static ArrayList<String> results;

public timeform() {

initComponents();

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

row=0;

results = new ArrayList<>(); }

if(combo.getSelectedItem()=="in hours") {

result= D*24+H+M/60;

results.add(Double.toString(result)+" Hours"); } Set results in


the array list
else if(combo.getSelectedItem()=="in minutes"){

result= D*24*60+H*60+M;

results.add(Double.toString(result)+" minutes"); }

else if(combo.getSelectedItem()=="in seconds"){

result= D*24*3600+H*3600+M*60;

results.add(Double.toString(result)+" seconds"); }
Open a new form from a button
 Now you can show the results in the new form using the
array list from your initial form (timeform)
 This should be done as soon as opening the new
showresults form  in the constructor of the new form.
public showresults() {

initComponents();

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

table.setValueAt(timeform.results.get(i), i, 0); }
Assignment1:
Temperature Converter
Assignment1: Temperature Converter
 The main idea of this assignment is to create a temperature converter
from Celsius to Fahrenheit or to Kelvin.
 The entered values will be saved into a file.
 They will be then read from the file, and shown in a dynamically
created table inside a dynamically created form
 We need to create the following form:
The action for Convert button
 To convert from Celsius to Fahrenheit, we need to apply the
following conversion equation:
Temperature in Fahrenheit = (Temperature in Celsius)*1.8 + 32
 To convert from Celsius to Kelvin, we need a different equation:
Temperature in Kelvin = (Temperature in Celsius) + 273.15

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


int tempFahr = (int)((Double.parseDouble(tempTextField.getText())) * 1.8 + 32);
fahrenheitLabel.setText(tempFahr + " Fahrenheit");
//Parse degrees Celsius as a double and convert to Kelvin
int tempkel = (int)(Double.parseDouble(tempTextField.getText())+ 273.15);
kelvinLabel.setText(tempkel + " Kelvin");
The action for Save button
 To convert from Celsius to Fahrenheit, we need to apply the
following conversion equation:
Temperature in Fahrenheit = (Temperature in Celsius)*1.8 + 32
 To convert from Celsius to Kelvin, we need a different equation:
Temperature in Kelvin = (Temperature in Celsius) + 273.15

FileWriter out;
try {
out = new FileWriter("Temp.txt", true);
out.write(output.getText()+"\n");
out.close();
} catch(IOException e) {
System.out.println("Error appending to file " + "Temp.txt");
}
The action of Show results button
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");
}
The action of Show results button (part2)
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< rows; i++) {


table.setValueAt(myArr.get(i),i,0);
}
Assignment2:
Student Registration
Form
Assignment 2: Student Registration Form
 You are asked to design a Student Registration
application.
 The GUI of your application is the following:

 Radio Button is used for the Campus


 Check Box is used for the Course
Assignment 2: Student Registration Form
 First change the variable names:
1. TextFields: fname, lname, id.
2. Radio buttons: tripoli, saida, beirut.
3. Check boxes: c300,c310l, c415.
4. Button: submit.
Assignment 2: Student Registration Form
 When the student presses Submit all the entered info must
be save in a file in the following order:
First name last name id Campus name Courses names
 So, set the action performed handler of the Submit button
to do so.
Assignment 2: Button Group
 Double click the Submit button.
1. First, read the user input in the textfields.(use getText()).
2. Next, check if the radio button is selected, if yes store the
campus>>use isSelected( ) method.
 Note that a student can be registered only in one campus. So, you
have add some restriction so only one radio button is selected at
once.>>>add a Radio Button Group.
1. From the palette add a Button Group.
2. It is invisible, but you can detected in the navigator.
3. For each radio button set the Button Group property to buttonGroup1.
Assignment 2: Radio Button Selection
 When you set the buttonGroup for all radio buttons you will see, in
your design the connection between these radio buttons.
 For the test you will use if …else if …else , since a single radio button
can be selected(check the next radio button if the first is not checked)
3. Check each check box if it is selected, if yes store the courses>> use
isSelected( ) method.
 For the test use if…if….You should always check the next check box
not only if the first one is not selected. (more than one choice can be
selected)
Assignment 2: Show data in a TextArea
 In order to check the Submit button action, add aTextArea to show
the String to be stored.
 Change its variable name to out.

 Set the action performed of the Submit button.


Assignment 2: Student Registration Form
 Double click the Submit button and write the following
code:
Assignment2: Close Button
 Now add a Close button to your GUI. When the student
presses this button the application will close, 2 cases are
possible:
1. If you want to stop running your application>>the close button
action performed handler must call System.exit(0);
2. If you want to close the Frame without stop running the
application>> the close button action performed handler must call
this.setVisible(false)
Save data in a File(Continue Assignment 2 )
 Now, we want to save the input data, showed in the out
textArea, in a file.
 In order to write in a File you have to create a file writer
object, specify a file name and call the write method to write
a string.
 Continue the Submit button action performed code by the
following:
1. FileWriter stdinf=new FileWriter(“data.txt”,true) >> it
creates a file writer object stdinf, specifies the file name in the
first argument of the constructor and true in the second, i.e we
can add to the file and the new string is added at its end.
Save data in a File (Continue Assignment 2)
2. stdinf.write(fn+"\n");
stdinf.write(ln+"\n");
stdinf.write(i+"\n");
stdinf.write(campus+"\n");
stdinf.write(courses+"\n");>>writes each data in the file. “\n”
announces the end of the string.
At the end you have to close the file writer by calling the close( )
method>> stdinf.close();
When working with file an ioexception may be thrown, to catch this
exception and avoid system exit we surround the code of file
manipulation by try{ }, and we add a catch statement, to catch
(handle) the ioexception catch(IOException ioe){ }
Save data in a File (Continue Assignment 2)
 The inserted code will be:
try{
FileWriter stdinf = new FileWriter("data.txt", true);
stdinf.write(fn+"\n");
stdinf.write(ln+"\n");
stdinf.write(i+"\n");
stdinf.write(campus+"\n");
stdinf.write(courses+"\n");
stdinf.close();
}catch(IOException ioe){}
 Run your application>>Note that a data.txt file is created in the project
folder and contains the data of the registered students.
 Even when you close your application and rerun it, this file stays.
Show Data in a Table (Continue Assignment
2)
 Now, we want to show all student info in a table.
1. Delete the Text Area
2. Add a new button Show All Registered. When it is pressed, a new
frame is open, and a table is showed containing the registered
student data.
 But, how to read from the data.txt the students data?
Show Data in a Table (Continue Assignment
2)
 To read from the data.txt, you have to use a FileInputStream object that reads the
binary data of a file>>>FileInputStream fs = new FileInputStream("data.txt");
Its constructor takes the file name as argument
 But, the binary stream must be read as String so an InputStreamReader object is
used>> InputStreamReader ir=new InputStreamReader(fs);
Its constructor takes the file input stream object fs as argument.
 Then the String stream is buffred using a BufferedReader object>> BufferedReader
in = new BufferedReader(ir);
 Finally the string stream is read from the buffer by using the readLine( ) method, it
returns a the string ending with \n, this string is written in an
arrayList>>>ArrayList<String> al = new ArrayList<>();
while(in.ready())
al.add(in.readLine());
 When the buffered stream ends the buffered reader must be closed>>> in.close( );
Show Data in a Table (Continue Assignment 2)
 Double click the Show All Registered button and write the
following:
try {
FileInputStream fs = new FileInputStream("data.txt");
InputStreamReader ir=new InputStreamReader(fs);
BufferedReader in = new BufferedReader(ir);
ArrayList<String> al = new ArrayList<>();
while(in.ready())
al.add(in.readLine());
in.close();
}
catch(IOException e) { }
Show Data in a Table (Continue Assignment 2)
 Double click the Show All Registered button and write the
following:
try {
FileInputStream fs = new FileInputStream("data.txt");
InputStreamReader ir=new InputStreamReader(fs);
BufferedReader in = new BufferedReader(ir);
ArrayList<String> al = new ArrayList<>();
while(in.ready())
al.add(in.readLine());
in.close();
}
catch(IOException e) { }
Show Data in a Table (Continue Assignment
2)
 When the Show All Registered button is clicked the registered
student data are put in an array list.
fn1 ln1 id1 camp1 course fn2 ln2 id2 camp2 course
1 2

 How to read from an arrayList>> using get(i) method.


 Note that each 5 elements of an arrayList corresponds to a
student, and are stored in the same row of the table.
Show Data in a Table (Continue Assignment
2)
 Let’s prepare the table.
 Continue the code of Show All Registered:
1. Create the frame f where to show the output table>> JFrame
f = new JFrame();
2. Set the frame size>>f.setSize(1000, 300);
3. Create the table and set the number of rows=al.size()/5 (size
of the arrayList/5) and columns=5>> JTable t = new
JTable(al.size()/5, 5);
4. Add to the frame a ScrollPane containing the table t>>
f.add(new JScrollPane(t));
5. Show the frame>> f.setVisible(true);
Show Data in a Table (Continue Assignment
2)
 Try to run your application and register one student, then press
submit and then Show All registered, you will get the following:
A new frame is open, it contains an empty table of 5 columns. Why?
 Lets set the values of the table:
 First set the columns Headders>>
t.getColumnModel().getColumn(0).setHeaderValue(“First name");
t.getColumnModel().getColumn(1).setHeaderValue(“Last name");
t.getColumnModel().getColumn(2).setHeaderValue(“Id");
t.getColumnModel().getColumn(3).setHeaderValue(“Campus");
t.getColumnModel().getColumn(4).setHeaderValue(“Courses");
Show Data in a Table (Continue Assignment 2)
 Now set the table values:
 The index i is used to read the
int i=0;
elements from the arraylist al.
int j=0;  The index i must be incremented
by the number of data to move to
while(i<rows) the next student.
{  When it is incremented by one, it
t.setValueAt(al.get(i), j, 0); gets the first data of the
t.setValueAt(al.get(i+1), j, 1); student(fname).
t.setValueAt(al.get(i+2), j, 2);  The index j is used for the table
row.
t.setValueAt(al.get(i+3), j, 3);
 It is incremented by 1 to move to
t.setValueAt(al.get(i+4), j, 4);
the next student
i+=5;
j+=1;
}
 Try your registration application!!

You might also like