Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

A GUI program is composed AWT Components &

of three types of software: Containers


-Graphical components that
make up the Graphical User
JAVA GUI
Interface
GUI -Listener methods that
• stands for Graphical receive the events and
User Interface respond to them

• program interface that -Application methods that


takes advantage of perform the desired
the computer’s operations on the Swing
graphics capabilities information.
-graphical user interface
to make the program Abstract Window Toolkit toolkit in Java, which is one
easier to use
Java’s platform-independent part of the Java Foundation
• designed in 1970 by Classes (JFC)
windowing, graphics, and
Xerox Corporation’s user-interface widget toolkit -includes graphical user
Palo Alto Research
• part of the Java interface (GUI) widgets such
Center
Foundation Classes as text boxes, buttons, split-
• Basic Components: panes, and tables
(JFC) – the standard
• Pointer API (Application -runs the same on all
Program Interface) for platforms
• Pointing device providing graphical
user interfaces for -supports pluggable look and
• Icons
Java programs feel – not by using the native
• Desktop platform's facilities, but by
• contains the roughly emulating them
• Windows fundamental classes
used for constructing -classes are often described
• Menu
GUIs as lightweight because they
• In Java, GUI-based do not require allocation of
programs are AWT Hierarchy native resources in the
implemented by using operating system’s window
the classes from the toolkit
standard javax.swing -UI elements such as dialog
(Swing classes) and boxes and buttons; you can
java.awt (AWT usually recognize their
classes) packages.
names because they begin
• All GUI classes are with J
based on the -Each Swing component is a
fundamental classes descendant of a
in the Application
JComponent, which in turn
Windowing Toolkit or
inherits from the
AWT. java.awt.Container class
• You insert the import represents both a width and a
statement height

import javax.swing.*; String getTitle()- Returns a


JFrame’s title
at the beginning of your Java
program files so you can void
take advantage of the Swing setResizable(boolean)-Sets
UI components and their the JFrame to be resizable
methods by passing true to the
method, or sets the JFrame
JFrame Class to be not resizable by
-contains the most basic passing false to the method JFrame Class
functionalities that support boolean isResizable()- When a JFrame serves as a
features found in any frame Returns true or false to Swing application’s main
window, such as minimizing indicate whether the JFrame user interface, you usually
the window, moving the is resizable want the program to exit
window, and resizing the when the user clicks Close.
window void setVisible(boolean)- To change this behavior, you
Sets a JFrame to be visible can call a JFrame’s
-To design such a frame using the boolean argument
window, we define a setDefaultCloseOperation()
true and invisible using the method and use one of the
subclass of the JFrame boolean argument false following four values as an
class and add methods and
data members that void setBounds(int, int, int, argument:
implement the needed int)-Overrides the default JFrame.EXIT_ON_CLOSE
functionalities. behavior of the JFrame to be exits the program when the
positioned in the upper- left JFrame is closed.
corner of the computer
screen’s desktop. The first WindowConstants.DISPOS
two arguments are the E_ON_CLOSE closes the
horizontal and vertical frame, disposes of the
positions of the JFrame’s JFrame object, and keeps
upper-left corner on the running the application.
desktop. The final two
WindowConstants.DO_NO
arguments set the width and
THING_ON_CLOSE keeps
height.
the JFrame and continues
running. In other words,
it functionally disables the
Close button.
JFrame Class Methods
WindowConstants.HIDE_O
void setTitle(String) - Sets a
N_CLOSE closes the
JFrame’s title to the String
JFrame and continues
argument
running; this is the default
void setSize(Dimension)- operation that you frequently
Sets a JFrame’s size using a want to override.
Dimension class object; the
Dimension(int, int) constructor
creates an object that
JPanel Class EVENTS AND EVENT Common user actions and
HANDLING the events that are
The simplest Swing
generated from them
container In Java, events represent all
activity that goes on between User Action
Plain, borderless surface that
the user and the application.
can hold lightweight UI Resulting Event Type
components, such as • Like all Java classes,
JButton, JCheckBoxes, or events are Objects Click a button
even other JPanels. that the user initiates. ActionEvent
Inheritance Hierarchy of the The parent class for all event Click a component
JPanel Class. objects is named
EventObject, which MouseEvent
descends from the Object Click an item in a list box
class.
ItemEvent
EventObject is the parent of
AWTEvent, which in turn is Click an item in a check
the parent of specific event box
• To add a component classes such as
ItemEvent
to a JPanel, the ActionEvent and
container’s add() ComponentEvent. Change text in a text field
method is called, TextEvent
using the component
as the argument. Open a window

• In using a JPanel to WindowEvent


hold components, the Iconify a window
setContentPane()
method is also used WindowEvent
to allow the JPanel to Press a key
be set as a content
pane so it can hold KeyEvent
components.
When you write programs
with GUI interfaces, you are
always handling events that
originate with the mouse or
keys on specific
Components or Containers.

Event Listener
Object that includes a
method that gets executed in
response to the generated
events
Event listeners and the types
of events for which they are
used.
Listener-Type of Events • The class of the
object that responds
Example
to an event must
ActionListener-Action events contain a method that
accepts the event
Button clicks object created by the
AdjustmentListener- user’s action. Mouse Event
Adjustment events • In other words, when The MouseMotionListener
Scroll bar moves you register a interface provides methods
component (such as named mouseDragged()
ChangeListener-Change JFrame) to be a and mouseMoved() that
Events listener for events detect the mouse being
Slider is repositioned generated by another rolled or dragged across a
component (such as a component surface.
FocusListener-Keyboard JCheckBox), you
focus events need to write a The MouseListener
method that reacts to interface provides methods
Text field gains or loses
any generated event. named mousePressed(),
focus
mouseClicked(), and
ItemListener-Item events Listener mouseReleased() that are
Methods similar to the keyboard event
Check box changes status methods keyPressed(),
KeyListener-Keyboard ActionListener keyTyped(), and
events keyReleased().
actionPerformed(ActionEv
Text is entered ent) The MouseInputListener
interface implements all the
MouseListener-Mouse AdjustmentListener
methods in both the
events MouseListener and
adjustmentValueChanged(
Mouse clicks AdjustmentEvent) MouseMotionListener
interfaces.
MouseMotionListener-Mouse FocusListener
movement events
focusGained(FocusEvent)
Mouse rolls and
focusLost(FocusEvent)
WindowListener-Window
events ItemListener

Window closes itemStateChanged(ItemEve


nt)
• Any object can be
notified of an event as AWTEvent Class Methods
long as it implements
the appropriate
interface and is
registered as an event
listener of the
appropriate event
source.
Support for drag and drop This creates a JLabel
instance with the specified
Double buffering
text and horizontal
Key bindings alignment.

JComponent Class • JComponent class JLabel Methods


and its subclasses
• All Swing
components except
top-level containers
whose names begin
with “J” descend from
the JComponent
class (e.g., JPanel,
JScrollPane, and
JButton). JTextComponent Class
JLabel Class
• Inheritance Hierarchy The JTextComponent class
of the Jcomponent A JLabel object can display provides a base class for
class. either text or an image, or Swing components that
both. It cannot react to input handle editable text.
events but is instead
It provides the functionalities
commonly used to provide a
for entering and editing text
label identifier for a nearby
information—nearly all the
object that does.
features of a text editor.
The Jcomponent class The JLabel class uses three
JTextComponent has three
provides the following constants to align the
direct subclasses—
functionality to its component horizontally.
JTextField, JTextArea, and
descendants:
JLabel.LEFT JEditorPane.
Tool tips
JLabel.RIGHT • JTextField provides a
Painting and borders component for
JLabel.CENTER entering and editing a
Application-wide pluggable
One form of the constructor single line of text.
look and feel
for JLabel is: A constructor for JTextField
Custom properties
JLabel(String text, int where the parameter
Support for layout horizontalAlignment); specifies how many
characters wide the field is.
Support for accessibility
-JTextField(int numChars);
Another constructor for JTextArea Class
JTextField is:
A JTextArea object displays
-JTextField(String text); multiple lines of text in a
single font and style and
This constructs a new
optionally allows the user to
TextField initialized with the
edit the text.
specified text. JTextArea Methods
JTextArea does not handle
JTextField Class
scrolling, but implements the
provides a component for swing Scrollable interface.
entering and editing a single
• JTextArea uses the
line of text.
rows and columns
A constructor for JTextField properties to indicate
where the parameter the preferred size of
specifies how many the viewport when
characters wide the field is. placed inside a
JScrollPane to match
-JTextField(int numChars); JList Class
the functionality
Another constructor for provided by JList class is used to display
JTextField is: java.awt.TextArea. a list of items, such as list of
students, a list of files, and
-JTextField(String text); Constructors used for
so forth.
JTextArea
This constructs a new • A JList object is
TextField initialized with the JTextArea(int rows, int constructed in a
specified text. columns) creates a new manner similar to the
empty TextArea with the
way a JComboBox
specified number of rows
object is constructed,
and columns.
that is, by passing an
JTextArea(String text) array of String.
creates a new TextArea with
String[] names = {″Mark″,
the specified text displayed.
″Antonio″, ″Lea″,
JTextArea(String text, int ″Sheila″};
rows, int columns) creates
JList list = new
a new TextArea with the
JList(names);
specified text and number of
rows and columns. JList three selection modes:
• single-selection
• single-interval
JTextField Methods
• multiple-
interval.
Statements show how to set arguments and then adding ComboBox Method
the three selection modes: items (e.g., Strings) to the list
with the addItem() method.
list.setSelectionMode(List
SelectionModel. ComboBox fruitChoice =
SINGLE_SELECTION); new JComboBox();
list.setSelectionMode(List fruitChoice.addItem(″Apple
SelectionModel. ″);
SINGLE_INTERVAL_SELE
fruitChoice.addItem(″Bana
CTION);
na″);
list.setSelectionMode(List AbstractButton Class
fruitChoice.addItem(″Cherr
SelectionModel.
y″); AbstractButton is an
MULTIPLE_INTERVAL_SE
LECTION); Alternatively, you can abstract base class of button
construct a JComboBox and menu objects (e.g.,
using an array of Objects as JButton, JToggleButton,
the constructor argument. JCheckBox, JRadioButton,
The Objects in the array and JMenuItem).
become the listed items It defines much of the
within the JComboBox. functionality for all button
String[] fruitArray = types.
{″Apple, Banana, Cherry″}; Methods defined here are
JComboBox fruitChoice = applicable to all subclasses.
JList Methods
new JButtons act as push
buttons which invoke some
JComboBox(fruitArray); action when clicked. These
are not buttons that are
toggled on and off.
To construct a JButton
object, use the new
keyword. Then add the
button to the frame’s content
pane. The add() method of a
JComboBox Class content pane puts a JButton
The JComboBox is a in the frame.
component that combines The getContentPane()
two features: method of a frame is used to
• display area showing get the reference to the
an option, and content pane.

• a list box containing


additional options.
You can build a
JComboBox by using a
constructor with no
If you do not initialize a ActionListener listener = new
JCheckBox with a label and ActionListener() {
you want to assign one later,
public void
or if you want to change an
actionPerformed(ActionEv
existing label, you can use
ent event) {
the setText() method as in
int mode = 0;
box1.setText(″Check this
box!″); if (bold.isSelected())
• The state of a mode += Font.BOLD;
JCheckBox can be
changed with the if (italic.isSelected())

JToggleButton Class setSelected() mode += Font.ITALIC;


method.
JToggleButton is an label.setFont(new
extension of AbstractButton box1.setSelected(false); Font("Serif", mode,
and is used to represent • The isSelected() FONTSIZE));
buttons that can be toggled method is used to }
on and off (as opposed to check if a checkbox
buttons like JButton which, button is selected };
when pushed, "pop back (i.e., has a check JRadio Button Class
up"). mark) or deselected.
The JRadioButton class is
JToggleButton has two When the status of a used to represent a type of
direct subclasses— JCheckBox changes from button called a radio button.
• JCheckBox unchecked to checked or
vise versa, an ItemEvent is Like the checkbox button,
and
generated and the you can select or deselect a
JRadioButton.
itemStateChanged() radio button.
JCheckBoxes Class method is executed. But unlike with a checkbox
• The JCheckBox is You can use the getItem() button, you can only select
typically used to allow method to determine which one of the radio buttons that
the user to turn an object generated the event belong to the same group.
option on or off. and the getStateChange() Like JCheckBox,
method to determine JRadioButton generates
whether the event was a both action events and item
selection or a deselection. events.
The getStateChange() Constructors of the
method returns an integer JRadioButton:
Creates four JCheckBox
that is equal to one of two
objects – one with no label JRadioButton(Icon icon,
class variables –
and unselected, two with boolean selected) creates a
ItemEvent.SELECTED or
labels and unselected, and radio button with the
ItemEvent.DESELECTED.
one with a label and specified image and
selected. selection state, but no text.
JRadioButton(String text)
creates an unselected radio
button instance with the horizontal scroll bar JScrollPane Method
specified text. specification.
JRadioButton(String text, -JScrollPane(int, int)
boolean selected) creates a creates a JScrollPane with
radio button with the both vertical and horizontal
specified text and selection scroll bar specifications.
state.
If you want to force the
JRadioButton(String text, display of a scroll bar, you
Icon icon) creates a radio can use class variables Layout Managers
button that has the specified defined in the
text and image, and that is ScrollPaneConstants class. • A layout manager is
initially unselected. an object that controls
ScrollPaneConstants.HORI the placement (size
JRadio Button Methods ZONTAL_ and position or layout)
SCROLLBAR_AS_NEEDED of components inside
ScrollPaneConstants.HORI a Container object.
ZONTAL_ • Layout managers are
SCROLLBAR_ALWAYS interface classes that
ScrollPaneConstants.HORI are part of the Java
ZONTAL_ SDK. These align
SCROLLBAR_NEVER your components so
they neither crowd
JScrollPane Class ScrollPaneConstants.VER each other nor
The JScrollPane container TICAL_ overlap.
can hold components that SCROLLBAR_AS_NEEDED
• Each layout manager
require more display area ScrollPaneConstants.VER defines
than they have been TICAL_ methods
allocated. SCROLLBAR_ALWAYS that arrange
The JScrollPane constructor ScrollPaneConstants.VER components within a
takes one of four forms: TICAL_ Container.

-JScrollPane() creates an SCROLLBAR_NEVER BorderLayout Managers


empty JScrollPane in which Creates a scroll pane • A layout manager is
both horizontal and vertical displaying an image named an object that controls
scroll bars appear when picture, a vertical scroll bar, the placement (size
needed. and no horizontal scroll bar. and position or layout)
-JScrollPane(Component) JScrollPane scroll = new of components inside
creates a JScrollPane that JScrollPane(picture, a Container object.
displays the contents of the ScrollPaneConstants.VER • Layout managers are
specified component. TICAL_SCROLLBAR_ interface classes that
-JScrollPane(Component, ALWAYS, are part of the Java
int, int) creates a ScrollPaneConstants.HORI SDK. These align
JScrollPane that displays the ZONTAL_SCROLLBA your components so
specified component and R_NEVER); they neither crowd
includes both vertical and
each other nor BorderLayout Managers FlowLayout Managers
overlap.
//content pane The FlowLayout manager
• Each layout manager class provides a simple
getContentPane().setLayo
defines layout manager that is used,
ut(new BorderLayout());
methods by default, by the JPanel
that arrange getContentPane().add(gen objects.
components within a derPanel,
It sizes each component
Container. BorderLayout.WEST);
according to its preferred
• BorderLayout divides getContentPane().add(heig size and arranges them in
a rectangular screen htPanel, horizontal wrapping lines so
area into five BorderLayout.EAST); that they are evenly spaced.
regions—a central
getContentPane().add(resu The advantages of the
region surrounded by
ltPanel, FlowLayout manager
four border regions.
BorderLayout.SOUTH); include its ease of use, and
• The following class the guarantee that each
constants are the • When you add a component can be seen.
predefined names that component to a
container that uses The FlowLayout class
identify the
BorderLayout, the contains three constants that
corresponding regions
add() method uses are used to align
(by common
two arguments: Components with a
convention, North is
Container.
assumed to be at the • the component the
top): region to which the FlowLayout.LEFT
• BorderLayout. component is added
FlowLayout.CENTER
NORTH contentPane.setLayout(ne
FlowLayout.RIGHT
• BorderLayout. w BorderLayout());
SOUTH
• BorderLayout. |
EAST |
• BorderLayout. V
WEST
• BorderLayout.
CENTER

You might also like