0% found this document useful (0 votes)
7 views40 pages

GUI Compact-Practical

Uploaded by

Chai Shao Feng
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)
7 views40 pages

GUI Compact-Practical

Uploaded by

Chai Shao Feng
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/ 40

JAVA GUI STIA1014 Session A232

STIA1014 : Introduction To
Programming

GUI
Graphical User interface

Designing a Swing GUI in NetBeans


IDE
• In real world, you will create your GUI using tool
such as the NetBeans IDE GUI Builder
• Here we will design the GUI for an application
that can calculate the area and perimeter of a
rectangle given its length & width as the input
• The GUI is shown below:

[email protected] 1
JAVA GUI STIA1014 Session A232

Steps for designing the GUI


1. Create a new project & named it as RectangleApp
2. Creating a JFrame Container
To add a JFrame container:
•In the Projects window, right-click the
rectangleapp (small case) node
and choose New > JFrame Form.
• Enter RectangleAppGUI as the Class Name.
• Click Finish.

Steps for designing the GUI


3. Getting Familiar with the GUI Builder

Palette
Design
Area

Navigator
Properties

[email protected] 2
JAVA GUI STIA1014 Session A232

Getting Started
1) Drag Label
& Button to the
design area

2) Right click at
Label & choose
Edit Text, change
to “Display Label”

3) Perform similarly
for Button, change
to “Click Me to
Display Label”

Run the Project with Run File

[email protected] 3
JAVA GUI STIA1014 Session A232

GUI Coding
1) Right click at Label
& choose Change
Variable Name,
change to “lblOut”.

2) Double
click Button.

GUI Coding
1) Make sure you’re
in the right
jButtonAction area,
create some spaces
for your coding

2) Type:

lblOut.setText(“Hello GUI”);

3) Run it again.
Click your button
after it is executed

[email protected] 4
JAVA GUI STIA1014 Session A232

Steps for designing the GUI


4. Adding Components
To add a JLabel to the form:
-In the Palette window, select (click your mouse) the Label component
from the Swing Controls category.

Steps for designing the GUI


4. Adding Components
-Move your mouse into the Design Area.
. When the guidelines appear indicating that the JLabel is
positioned in the top left corner with a small
margin at the top and left edges, click again your mouse to place the Label.

-The JLabel is added to the form and a corresponding


node representing the component is added to the Navigator window.

10

[email protected] 5
JAVA GUI STIA1014 Session A232

Edit Appearance & Variable Name

11

Steps for designing the GUI


4. Adding Components
Before going further, we need to edit the JLabel text.
To edit the display text of a JLabel:

-Double-click the JLabel to select its display text.


-Type ‘Length:’ and press Enter.

The JLabel's new name is displayed and the component's width


adjusts as a result of the edit.

12

[email protected] 6
JAVA GUI STIA1014 Session A232

Steps for designing the GUI


4. Adding Components
To add a JTextField to the form:
- In the Palette window, select the Text Field component.
- Move the cursor immediately to the right of the ‘Length:’ JLabel
-When the horizontal guideline appears indicating that the JTextField's baseline
is aligned with the JLabel and the spacing between them is suggested with a
vertical guideline, click to position the JTextField.
- The JTextField snaps into position in the form aligned with the JLabel's
baseline, as shown below:

13

Steps for designing the GUI


4. Adding Components
To remove the text inside the JTextField & resize it:

-Double-click the JTextField to select its display text & press Delete.
- The width of the JTextField will be reduced. You need to resize (make it
wider) the JTextField by dragging the JTextField's right edge resize handle
toward the right edge of the enclosing JFrame

14

[email protected] 7
JAVA GUI STIA1014 Session A232

Steps for designing the GUI


4. Adding Components
To add the remaining three JLabels & JTextFields
- Repeat all the previous steps to add Jlabels & JTextFields
- Ensure that all the texts for the labels & textfields have been changed
correctly (e.g. second JLabel’s text is ‘Width :’ etc.)
- Once finished, you should have your GUI as shown below:

15

Steps for designing the GUI


4. Adding Components
To add JButton to the form:
- In the Palette window, select the Button component from the Swing Controls
category.
- Move the JButton below of the Perimeter: JTextField

-Set the display text for the JButton.


-You can edit the button's text by right-clicking the button and choosing Edit Text.
-Enter ‘Compute’ for the button

16

[email protected] 8
JAVA GUI STIA1014 Session A232

Steps for designing the GUI


4. Adding Components
To add another JButton
- Repeat all the previous steps to add the second JButton
- The second JButton text must be set to ‘Reset’
- Once finished, you should have your GUI as shown below:

17

Steps for designing the GUI


5. Set the JFrame Container size & title
To resize your JFrame (main container):
- Bring your mouse to the bottom right corner of the frame
- Click & drag your mouse diagonally up or down to resize the frame according
your preference

18

[email protected] 9
JAVA GUI STIA1014 Session A232

Steps for designing the GUI


5. Set the JFrame Container size & title
To set the JFrame title:
- Click the JFrame and ensure that it is highlighted (with orange-colored border)

- In the JFrame Properties Window, click the ‘title' property field.

19

Steps for designing the GUI


5. Set the JFrame Container size & title
To set the JFrame title:
- Type the desired title (e.g. ‘My Rectangle App’) in the title property field

20

[email protected] 10
JAVA GUI STIA1014 Session A232

Steps for designing the GUI


6. Running your App
To run your RectangleAppGUI program:
- Click the Source view tab to view the source codes that have been generated by
Netbeans

Generated
codes

21

Steps for designing the GUI


6. Running your App
To run your RectangleAppGUI program:
-Right Click your mouse in the generated codes area & select “Run File”

22

[email protected] 11
JAVA GUI STIA1014 Session A232

Steps for designing the GUI


6. Running your App
You can see your GUI when the program runs:

23

GUI EVENT HANDLING USING


NETBEANS GUI BUILDER TOOL
 Here we will add the event handling for the GUI that we have
built previously
 The GUI is shown again below
 Specifically, we’ll add the functionality for the two buttons,
Compute & Reset

24

[email protected] 12
JAVA GUI STIA1014 Session A232

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
1. Renaming the GUI components variables
The reference variables for GUI objects (such as buttons & textfields)
should be renamed so that we can easily identify them in the
codes generated by Netbeans GUI Builder
• Right-click the Compute button and select Change Variable Name…

25

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
1. Renaming the GUI components variables
• In the Rename dialog box, type ‘computeBtn’. (The variable name for
the Compute button has been changed from jButton1 to computeBtn)

• Repeat the previous steps to rename the variable for Reset button from
jButton2 to resetBtn

resetBtn

26

[email protected] 13
JAVA GUI STIA1014 Session A232

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
1. Renaming the GUI components variables
• Next we are going to rename all the variables for the four textfields
• Right-click the textfield beside label ‘Length:’ and select Change
Variable Name…

27

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
1. Renaming the GUI components variables
• In the Rename dialog box, type ‘lengthTF’. (The variable name for the
Length textfield has been changed from jTextField1 to lengthTF)

28

[email protected] 14
JAVA GUI STIA1014 Session A232

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
1. Renaming the GUI components variables
• Repeat the previous steps to rename the remaining three textfields:
- the variable for Width textfield from jTextField2 to widthTF
- the variable for Area textfield from jTextField3 to areaTF
- the variable for Perimeter textfield from jTextField4 to perimeterTF

widthTF

areaTF

perimeterTF

29

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
2. Adding the event handlers
Making the Compute Button Work
First, we will make the Compute button works by assigning the
handler to the button:
Specifically, we will use ActionListener responding to ActionEvent
• Right Click on the Compute button. From the pop-up menu choose Events --
> Action --> actionPerformed.

30

[email protected] 15
JAVA GUI STIA1014 Session A232

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
2. Adding the event handlers
• Netbeans will automatically add an ActionListener to the Compute button
and generate a handler method for handling the listener's actionPerformed
method
• You will be brought into the Source Code window where you implement the
action you want the Compute button to do when the button is pressed. Your
Source Code window should contain the following lines which is the
actionPerformed method that you need to override:

31

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
2. Adding the event handlers
• Next, we add the codes to implement what we want the Compute Button to
do (replacing the // TODO add your handling code here: line)

• The action performed by the Compute button can be divided into 3 steps:

1. It is going to accept user inputs, length & width, from the textfields
lengthTF and widthTF and convert the inputs from type String to
double,
2. It will then perform calculation of rectangle area & perimeter based on
the inputs length & width,
3. It will convert the area & perimeter to type String and place them in the
areaTF & perimeterTF respectively.

32

[email protected] 16
JAVA GUI STIA1014 Session A232

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
2. Adding the event handlers
• The finished source code shall look like this:

Step 1

Step 2

Step 3

33

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
2. Adding the event handlers
Making the Reset Button Work

Next, we will make the Reset button works by assigning the


handler to the button:
Again, we will use ActionListener responding to ActionEvent
• Right Click on the Reset button. From the pop-up menu choose Events -->
Action --> actionPerformed.

34

[email protected] 17
JAVA GUI STIA1014 Session A232

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
2. Adding the event handlers
• Your Source Code window should contain the following lines which is the
actionPerformed method for the Reset button that you need to override:

•Next, we add the codes to implement what we want the Reset Button to do
(replacing the // TODO add your handling code here: line)

35

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
2. Adding the event handlers
• The action performed by the Reset button is to simply erase all texts in the
textfields. To do this, you will set the texts to all of the four textfields to
empty String.

• Your finished source code should look like this:

36

[email protected] 18
JAVA GUI STIA1014 Session A232

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
2. Running the Program
1.
• The final step is to run the program. Right click in the Source Code window
and select Run File.
• Test the Compute button by entering values in the Length & Width textfields
and click the Compute button.
• A sample of the output is as follows:

37

STEPS FOR ADDING EVENT HANDLER


FOR THE GUI
2. Running the Program
1.
• Test the Reset button by clicking it and all the textfields will be cleared.
• A sample of the output is as follows:

38

[email protected] 19
JAVA GUI STIA1014 Session A232

Exercise 1

• Insert a button and a label


• Change the message in each object
• Give a new variable name for each object
• Create a coding in the button, so that when user
click the button, “Hello World” will appear in the
label.

39

Exercise 2

• Add a label and an input text to the previous


exercise.
• This time, take the input and display in the
previous label.
• Add a title for the form, such as “GUI Lesson”.

40

[email protected] 20
JAVA GUI STIA1014 Session A232

Exercise 3

• Input a length of one of the cube edge then display


the volume of the cube

41

Exercise 4

• Create one input (text field) and one output (label)


and two buttons.
• The first button will convert from Celsius to
Fahrenheit and the second button will convert from
Fahrenheit to Celsius.

42

[email protected] 21
JAVA GUI STIA1014 Session A232

Exercise 5

• Develop application for monthly payment of a loan.

43

Exercise 6

• Convert your water tariff assignment by using Java


GUI

44

[email protected] 22
JAVA GUI STIA1014 Session A232

Exercise 7

• Develop a GUI Java application to generate a


multiplication table from 1 to 12. Get the input
from user on the multiplier fro the table.

45

RESET & EXIT BUTTONS

• Reset – clear all inputs.


• Exit – terminate the running application
[System.exit(0) ]

Reset &Exit
Button

46

[email protected] 23
JAVA GUI STIA1014 Session A232

Running with jFrame as the main class

RUNNING WITH RUN BUTTON

47

Multiple jFrames

48

[email protected] 24
JAVA GUI STIA1014 Session A232

EXAMPLE

49

Pop-Up window with JOptionPane

50

[email protected] 25
JAVA GUI STIA1014 Session A232

Pop-Up window with JOptionPane

51

Pop-Up window with JOptionPane


JOptionPane.showMessageDialog(null,
8.9, "This is not an integer.",
JOptionPane.PLAIN_MESSAGE);

JOptionPane.showMessageDialog(null,
"Uh-oh!", "Error",
JOptionPane.ERROR_MESSAGE);

ImageIcon icon = new


ImageIcon("src/images/turtle64.png");

JOptionPane.showMessageDialog(null,
"I like turtles.", "Customized Dialog",
JOptionPane.INFORMATION_MESSAGE,
icon);

52

[email protected] 26
JAVA GUI STIA1014 Session A232

JOptionPane.showInputDialog
String m =
JOptionPane.showInputDialog("Any
one there?");

String m =
JOptionPane.showInputDia
log("Anyone there?");

taOut.setText("Hello:
\n"+m);

53

JOptionPane.showInputDialog
String m =
JOptionPane.showInputDialog("Any
one there?", 42);
String m =
JOptionPane.showInputDialog(null,
"Broccoli is tasty!", "Green dinner",
JOptionPane.INFORMATION_MESSAGE);
Integer[] options = {2, 3, 5, 7, 9, 11};

int n =
(Integer)JOptionPane.showInputDialog
(null, "Pick a number that is not prime:",
"Prime numbers",
JOptionPane.QUESTION_MESSAGE, null,
options, options[2]);
54

[email protected] 27
JAVA GUI STIA1014 Session A232

Display output/message in more


than one lines
• It can be done with TextArea element (Swing
Component) or table like element.

55

Display output/message in more


than one lines - Example

56

[email protected] 28
JAVA GUI STIA1014 Session A232

Display output/message in more


than one lines - Exercise

57

Sample Solution

58

[email protected] 29
JAVA GUI STIA1014 Session A232

Implementing Options
with radio Button

59

Exercise 2

• Develop the following task (Celsius to Fahrenheit


converter) by using radio buttons:

60

[email protected] 30
JAVA GUI STIA1014 Session A232

Sample solution for Exercise II

61

Implementing
Counter with Button

62

[email protected] 31
JAVA GUI STIA1014 Session A232

Exercise 3

• Put another button that add 100 to the counter


label (where it adds 100 each time the button is
pressed).
• Thus, it will add 1 and 100 to the label each time
the button is clicked

63

How to Store Repeated Inputs


to an Array

64

[email protected] 32
JAVA GUI STIA1014 Session A232

65

Reset/Again Button

66

[email protected] 33
JAVA GUI STIA1014 Session A232

Finish
Button

67

Exercise 4

• Display the total accumulation of the number and


the average as well, in addition to the list of inputs.

68

[email protected] 34
JAVA GUI STIA1014 Session A232

Display the Result


in a jTable

69

JTABLE

• You can change number


of columns and number
of rows.
• You can set title of the
columns
• You can
70 set type of data

for each column

70

[email protected] 35
JAVA GUI STIA1014 Session A232

Statements to insert data to the JTable

Variable name:
tblResult

1. DefaultTableModel model = (DefaultTableModel)tblResult.getModel();


2. model.setValueAt(value, indRow, indColumn);
7
1

71

Display the Result


in a jTable

1. DefaultTableModel model =
(DefaultTableModel)tblResult.getModel();
2. model.setValueAt(value, indColumn, indRow);

72

[email protected] 36
JAVA GUI STIA1014 Session A232

Exercise 5

• Display the total accumulation of the number and


the average as well, in addition to the list of inputs,
at the end of the jTable.

73

Sample Solution for Ex 4 & 5

74

[email protected] 37
JAVA GUI STIA1014 Session A232

Exercise 6

• Display the total accumulation of the number and


the average as well, in addition to the list of inputs,
at the end of the jTable in a two columns table as
below.

75

Exercise 6: Sample Solution

76

[email protected] 38
JAVA GUI STIA1014 Session A232

Deal with more than


one different Data
Types: Inputs &
Array

77

Add the Cake Button

78

[email protected] 39
JAVA GUI STIA1014 Session A232

Finish
Button

79

[email protected] 40

You might also like