You are on page 1of 29

Object Oriented

Programming
CPE313,MIS313,ISYE313,CMPE313,IT31,ITEC313,ISE313

by
Dr. Cain Kazimoglu

Info about resources


I claim no rights in the material used for making these
presentation slides. The slides are prepared in a way to avoid
using copyright-protected material. As the lecturer of the
course, I compiled a variety of resources in order to produce
recent and correct information fitting to the content of the
course.
I have no content claim on any and all of the material used
in this course including text, images, programs and other
materials used. The lecture primarily uses a variety of books –
which are all mentioned on the Moodle page of the course.
While the majority of the exercises are prepared by me, the
copyright of all materials used belong to their original
owners.
- Asst. Prof. Dr. Cain KAZIMOGLU

1
What makes up a GUI?
 This lecture shows how to write Java programs that run in any
Computer OS using Graphical User Interface (GUI)
Components such as

 Button,
 TextField,
 Label,
 checkBox,
 radioButton,
 ComboBoxes

 All of these (and many other GUI Components) are defined


under the Swing library class javax.swing.* which must be
imported into your main class when these components are
used in Java application.

Where do we start?
 We need to create the form first which would involve the
GUI components and act as the user interface template
 This form is also called the content pane
 It is part of the Java Swing library and uses a class called
JFrame

2
JFrame Basics (1)
 To Create a JFrame, you need to extend the JFrame class
and implement ActionListener event.

JFrame Basics (2)


 The import statements are crucial in order to successfully use
all Graphical User Interface (GUI) Components on the content
pane.

 If you do not put the import statements, the Java compiler will
not understand which components refer to which library class
files.

3
JFrame Basics (3)

 To create a JFrame form, you need to have certain


statements written inside the constructor of your class.

 An example for this is given below :

JFrame Basics (4)

setLayout defines how components are organized


setSize defines the size of the content pane
setTitle puts a title to the bar at the top of the pane.
setDefaultClose operation allows standard windows
buttons
setLocationRealtiveTo defines a specific location to be
placed
setVisible makes the form visible – unless you set the form to
visible, it will not appear on the screen during the run time even if
you have no errors in your source code.

4
JFrame Basics (5)
The size of the form is defined in setSize function

400 px

300 px

A JFrame example

5
A form is a JFrame extention that usually listens a button
click event (usually represented within the action
performed method). Therefore, almost all forms in Java
implements the ActionListener Interface

these are the Java libraries you will


be using

awt is the abstract windows toolkit


and adding event means it can
interact with the user clicking
buttons etc

6
means we can use the features
of the class JFrame as this is its
subclass

says
that we want our application to
“listen” for events such as the user
pressing a button (writing this means
that the class must have an
actionPerformed method)

main method as this is not just a class


but an application

just creates a new object of the


JFrameBasic class

7
the instructions to make had no
parameters () so we need the
constructor with no parameters

the constructor (with no parameters) just sets


up the appearance and behaviour of the
object using 6 basic methods inherited from
JFrame

the content pane of the frame is


392 by 265 pixels.
(we lose 8 sideways for the border
and 35 for the top title bar)

needed to make the allows the user to close


frame visible. the application by
clicking the close
FlowLayout adds controls from top window button
to bottom and left to right in a
manner similar to writing text in
Word
(centrally justified)

8
A different example using the template
with class renamed FirstFrame

different size different title

different size

different title

Exercise 1 – Create the


following JFrame extension
400 px
Do not consider the
loss of pixels due to
top bar and sideway
for border.

Use the name Form


for your JfFame.
300 px

9
Exercise 1 Answer

JButton
 Buttons are the predominant GUI components that provide
interaction with the user.

 Ideally, when the user clicks on a button, the form needs to


reach it some way to the user.

 Buttons are created via JButton class in Java

10
Buttons in Swing Library
 One of the first ways to communicate with the
user is to get then to click on a button
 We have already seen this set up for us in the
JOptionPane.showConfirmDialog

 Now we want to have more flexibility by creating


our own buttons using
JButton myButton = new JButton("Text");

Adding a JButton
1 JButton myButton = new JButton("Press");

2 add(myButton);
myButton.addActionListener(this);

3 public
{
void actionPerformed(ActionEvent e)

// do what you want to do in here…


}

11
Adding a JButton (1)

JButton myButton = new JButton("Press");

Make a new JButton object called myButton using the


constructor from javax.swing which takes a String parameter
and puts it on the button

Adding a JButton(2)
adds the button to the content
pane

add(myButton);
myButton.addActionListener(this);

It registers the button with the action listener for


the frame (identified by this). When the user clicks
the button, the actionPerformed method is called
automatically

12
Adding a button(3)
this is the method which is automatically
called when the ActionListener ‘hears’
that the button has been clicked
( pressed by the mouse)

public void actionPerformed(ActionEvent e)


{
setTitle("pressed");
}

this is what will happen

Exercise 2 – Using JButton


 Create a Java Form Application which will have a button that has a
”Click Me!” text on it. When this button is clicked by the user, the form
will prompt showMessageDialog window with a “you clicked on me
!” text.

13
Resizing buttons

 You can resize a button in a form by entering new


dimensions through a new object.

 Use the setPreferredSize method to set the size of a button.

Image Icon
 You can set an image to an icon through using
the image icon object.

14
Having problems with
image buttons?
 If you are having trouble with image icons, this is most probably
because Java API cannot find the image in the specified
location. Luckily, you can check whether or not the image file
exists in the location you predefined in your ImageIcon object.

ForeColour and
BackGroundColour

 Remember that button is not the only


object that accepts these methods. Many
other form components, even the JFrame
itself is adjustable.

15
JTextField
 The JTextField is the default input field in the Java
Swing GUI Components.

 Similar to JOptionPane.showInputDialog Box, the


JTextField primarily used to receive data from the
user.

JTextField
 A textbox is displayed through the JTextField class.
 JTextField myText = new JTextField(10);

This code creates a new JTextField object called myText using the
constructor from javax.swing which takes an int parameter and makes
a text input box with that width (here, the textField accepts 10 characters)

16
JTextField

…..
Package javax.swing
+setText(s:String) has many different
+getText(): String methods including
those to read the
……
String from the box
and display a String in
the box. These
operations are
completed through
setText and getText
methods.

Adding a JTextField

1 JTextField myText = new JTextField(10);

2 add(myText);

17
Exercise 3 - Interactions
 Create two JTextField which would take the name and
surname from the user; and display it on the screen when
these values are entered properly.

 Prompt the user with a showMessageDialog Box when


values are not entered (i.e. “Please fill your name and
surname”). On the other hand, when the values are
entered sucessfully, show these values on the screen as the
output in a showMessageDialog Box (“Hello” + fullName).

18
Exercise 3 Sample Run

JLabel
 The JLabel is GUI components used to inform the
user about certain outputs or explanations.

 These make the user interface more readable


and provide instructions to the user.

19
JLabel
The labels are added via using the following statement:

add(new Label("String"));
If you are not going to use the JLabel only for
an instruction purpose,
it might be a more efficient to add the JLabel directly
to the form without assigning it to an object.

add(new Label ("first label :"));


add(new Label ("second label :"));
add(new Label ("third label :"));
add(new Label ("fourth label :"));
add(new Label ("fifth label :"));

Defining Labels

20
41

label added here

only listening for the button using


keyboard return in the text field has
no effect

pressing submit
clears the text field

Layout Managers
 FlowLayout is not the only layout developers use on GUI
JfFrame and other components.

 There are many other popular layouts available in Java


Swing Library such as the Border Layout and Grid Layout.

 A full list can be achived from here :

https://www.tutorialspoint.com/awt/awt_layouts.htm

21
Main Layouts we are going to use

 FlowLayout > use it when you want to add


components one after the other to the
contentPane;

 BorderLayout > use it when you want to divide


the entire contentPane into 5 regions;

 GridLayout > use it when you want to put


components inside a table-like structure that
consists of rows and columns.

A Layout Example : Border Layout

 Border layout splits the content pane (or other


container such as a panel) into up to five regions
North, South, East, West and Center (note the
American spelling).
North

W E
e Center a
s s
t t

South

22
GridLayout
 The GridLayout class is a layout manager that lays out
a container's components in a rectangular grid. The
container is divided into equal-sized rectangles, and
one component is placed in each rectangle.

 For example, the following is an applet that lays out six


buttons into three rows and two columns:

GridLayout object

The constructor of the GridLayout class creates an instance that


has two columns and as many rows as necessary.

Button 1 Button 2
Button 3 Long-Named Button 4
5

23
JPanel Component
 Layouts can be difficult to manage and each layout is
created for a specific purpose.

 For example, BorderLayout divides the Frame into 5


components whereas GridLayout allows developers to
treat Frame as if it’s a big table. A specific layout might
not be enough for you to create a complicated and
efficient user interface.

 Under such circumstances, you might need to use a


container rather than relying on a specific layout for the
entire JFrame.

JPanel (1)
 The JPanel is a container that is used to hold the 'widgets' of
Swing. They are used to let the developer have more control
over positioning and style of widgets on the screen, and to
give a better structure to the code. JPanels are fundamental
in the creation of a professional GUI.

24
JPanel (2)
 You can set borders for JPanel to see where it starts and where
it ends.

 It is also possible to attach a panel to a specific part of the


JFrame. However, doing so would limit the position of your
widgets as well as the dimension of the panel.

JPanel (3)
 You can adjust the dimensions of a JPanel similar
to a button, however, if you attach it to a JFrame
(such as to North or South) then this ability cannot
be used as the panel would occupy the whole
area.

25
Parsing to/from numbers
 Remember if any calculation is to be done you will have to be
making sure the Strings you read in are changed to number
using some method of the number class like
 Double.parseDouble(String)
 Integer.parseInt(String)
 If you are to display numbers in text they must be converted to
Strings using an implicit conversion
 "" + value
 Or one of the methods of the String class
 String.valueOf(int)
 Or you can use a method of the number class such as
 Integer.toString(int)

Exercise 4 – Using JPanel


Create the following JPanel with the labels inside them.
Notice that there are three Jpanels, each with a JLabel
attached in it.

26
Exercise 5 – Cars & Vans

 Create an application named CarsAndVans.java which


would have 3 buttons and 2 non-editable textFields in a java
form (i.e. JFrame).

 When user presses the first button which is the «cars» button,
the number of cars will increase and correspondingly, when
user presses the second button, the «vans» button, the number
of vans will increase.

 When the third button, which is the «Reset» button is pressed,


the number of Cars and Vans will be initialised to 0.

Exercise 5 – Sample Run

27
Exercise 5 – GUI Layout

setEditable(false) prevents modifying


the content of a textField

Even More Hints on


Exercise 5
 To detect which button is pressed you can use
e.getSource() statement.

28
Revision
 This section has been a very brief introduction to
GUI programming using Swing. We investigated the
following Swing controls:

 JFrames – with a useful EditPlus template file


 JButtons and the ActionListener technique for event
handling
 Jlabels, JTextFields for text handling
 JPanel and finally Layouts such as FlowLayout,
BorderLayout and GridLayout.

29

You might also like