OOP2 Chapter12
OOP2 Chapter12
12
A First
Look at
GUI
Applicatio
ns
Updated by: Najlaa Alshatri
• We use these constants later in the program to set the size of the
window.
• The window’s size is measured in pixels.
• A pixel (picture element) is one of the small dots that make up a
screen display.
• This statement:
– creates a JFrame object in memory and
– assigns its address to the window variable.
• To specify the action to take place when the user clicks on the
close button.
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Instantiate a swing
Frame object
Label
Button
add(panel);
• Examples: KiloConverter.java
FlowLayout
GridLayout
Object BorderLayout
CardLayout
GridBagLayout
FlowLayout(int alignment,
int horizontalGap,
int verticalGap)
• Example:
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 7));
add(button, BorderLayout.NORTH);
• Example:
setLayout(new BorderLayout(5,10));
columns
rows
Adding components
Adding
components to
the panel
NOTE: panel p1 is
embedded inside panel p2!
Registering the
frame to be a
listener for action
events generated
by the two buttons
Inner class
has direct
access to all
members
(even private)
of the outer
class
Example:
KiloConverter.java
©2016 Pearson Education, Ltd. 12-78
Registering A Listener
• The process of connecting an event listener object to
a component is called registering the event listener.
• JButton components have a method named
addActionListener.
calcButton.addActionListener(
new CalcButtonListener());
panel.add(radio1);
panel.add(radio2);
panel.add(radio3);
if (radio.isSelected())
{
// Code here executes if the radio
// button is selected.
}
radio.doClick();
checkBox.doClick();