Sie sind auf Seite 1von 76

Java Programming, Second Edition

Chapter Thirteen
Understanding Swing Components
In this chapter, you will:
• Use the JFrame class
• Extend the JFrame class
• Use the JPanel class
• Understand Swing event listeners
• Use the JCheckBox class
• Use the ButtonGroup class
• Use the JComboBox class
• Create JScrollPanes
Using the JFrame Class
GUI Components
• Insert the import statement import javax.swing.*;
to take advantage of the Swing GUI components
and their methods
• Also called widgets, which stands for windows
gadgets
• Within the awt package, components are defined
in the Component class
• When you use components in a Java program, you
usually place them in containers
Using the JFrame Class
• Container- Type of component that holds
other components so that you can treat a
group of several components as a single
entity
– Usually takes the form of a window
– Defined in the Container class
Using the JFrame
• The JFrame class is a subclass of the awt
Component class
• The JFrame is the best container option for hosting
Java applications
• The setSize() method allows you to set the
physical size of a JFrame
• The setVisible() method makes the JFrame
component visible or invisible
• Create a JFrame so that you can place other
objects within it for display using a JPanel
Using the JFrame
• The JFrame class has four constructors
– JFrame() constructs a new frame that is initially
invisible
– JFrame(GraphicsConfiguration gc) creates a JFrame in
the specified GraphicsConfiguration of a screen device
and a blank title
– JFrame(String title) creates a new, initially invisible
JFrame with the specified title
– JFrame(String title, GraphicsConfiguration gc) creates
a JFrame with the specified title and the specified
GraphicsConfiguration of a screen
Using the JFrame Class

• A JFrame’s action in response to a user


clicking the Close button is set by passing
an argument to the
setDefaultCloseOperation() method placed
inside the JFrame constructor method
– The most common action is to close the
application using the argument
JFrame.EXIT_ON_CLOSE
Using the JFrame Class
• EXIT_ON_CLOSE exists the program when the
JFrame is closed
• DISPOSE_ON_CLOSE closes the frame, disposes
of the JFrame object, and keeps running the
application
• DO_NOTHING_ON_CLOSE keeps the JFrame
and continues running
• HIDE_ON_CLOSE closes the JFrame and
continues running
Using the JPanel Class
• The simplest Swing container is the JPanel
• You add components to a JPanel using the
add() method
• Call the setContentPane() method with the
panel object created to set the application's
content pane
Understanding Swing Event
Listeners
• Classes that respond to user events must
implement an interface that deals with the
events
• These interfaces are called event listeners
– Each listener can handle a specific event type
– A class can implement as many event listeners
as needed
Using Swing Event Listeners
• When a user event takes place, the
appropriate method is automatically called
by the system
Using the JCheckBox Class
• JCheckBox Class- Consists of a JLabel
positioned beside a square
• You can click the square to display or
remove a check mark
Using the ButtonGroup Class
• ButtonGroup Class
– Can group several JCheckBoxes so a user can select
only one at a time
– When you group JCheckBox objects, all other
JCheckBoxes are automatically turned off when the
user selects any one checkbox
– Either create a ButtonGroup and then create the
individual JCheckBoxes, or you can create the
JCheckBoxes and then create the Button group
– Similar to a set of radio buttons but more than one can
be checked
Using the JComboBox Class

• JComboBox class- For picking items from a


list or entering text into a field
Using the JComboBox Class

• You can build a JComboBox by using a


constructor with no arguments and then adding
items to the list with the addItem() method
• The following statements create a JComboBox
with three options
JComboBox majorChoice = new
JComboBox();
majorChoice.addItem(“English”);
majorChoice.addItem(“Math”);
majorChoice.addItem(“Sociology”);
Creating JScrollPanes
• A JScrollPane is a container whose methods
can be used to hold any component that can
be scrolled
• Add a JTextArea component to use both
multiple rows and columns
JScrollPane forms
The JScrollPane constructor takes one of four forms:
• JScrollPane() creates an empty JScrollPane where both
horizontal and vertical scrollbars appear when needed
• JScrollPane(Component) creates a JScrollPane that
displays the contents of the specified component
• JScrollPane(Component, int, int) creates a JScrollPane
that displays the specified component, vertical scrollbar,
and horizontal scrollbar.
• JScrollPane(int, int) creates a scroll pane with specified
vertical and horizontal scrollbars
Horizontal and vertical scrollbar constants

• HORIZONTAL_SCROLLBAR_AS_NEEDED
• HORIZONTAL_SCROLLBAR_ALWAYS
• HORIZONTAL_SCROLLBAR_NEVER
• VERTICAL_SCROLLBAR_AS_NEEDED
• VERTICAL_SCROLLBAR_ALWAYS
• VERTICAL_SCROLLBAR_NEVER
Java Programming, Second Edition

Chapter Fourteen
Using Layout Managers and the
Event Model
In this chapter, you will:
• Learn about layout managers
• Use JPanels
• Learn about advanced layout managers
• Understand events and event handling
• Use the AWTEvent class methods
• Use event methods from higher in the
inheritance hierarchy
• Handle mouse events
Learning about Layout Managers
• Layout manager- An interface class that is
part of the JDK
– Aligns your components so they neither crowd
each other nor overlap
– Can assign layout managers within layout
managers
– For example:
• One layout manager arranges components in equally
spaced columns and rows
Learning about Layout Managers
Learning about Layout Managers
• BorderLayout manager- The default manager for
all content panes
– Can use the BorderLayout class with any container that
has five or fewer components
– Components fill the screen with five regions named
North, South, East, West, and Center
– The compiler determines the exact size of each
component based on the components contents
– When BorderLayout is used with less than five
components, any empty regions disappear
Positions using the BorderLayout
Learning about Layout Managers
• FlowLayout- To arrange Components in
rows across the width of a container
– Each component retains its default size
– Each component that you add is placed to the
right of previously added components
Learning about Layout Managers
• GridLayout- To arrange Components into
equal rows and columns
– You indicate the numbers of rows and columns
you want, and then the container surface is
divided into a grid
– Specify rows first, columns second
– As you add components they are positioned
left-to-right across each row in sequence
JDemoGrid Swing applet
Learning about Layout Managers
• CardLayout- Generates a stack of containers or
components, one on top of another
• Each container in the group is referred to as a card
• Only one component is visible at a time
• A card layout is created from the CardLayout class
using one of two constructors
– CardLayout() creates a new card layout without a
horizontal or vertical gap
– CardLayout(int hgap, int vgap) creates a new card
layout with the specified horizontal and vertical gaps
Using JPanels
• JPanels- Increase the number of possible
component arrangements by using the JPanel class
• A JPanel is similar to a JWindow in that a JPanel
is a surface on which you can place components
• JPanel is a Container so it can contain other
components
• By using JPanels within JPanels, you can create an
infinite variety of screen layouts
Using JPanels
• JPanel object constructors
– JPanel() creates a new JPanel with a double
buffer and a flow layout
– JPanel(LayoutManager layout) creates a new
buffered JPanel with the specified layout
manager
Learning about Advanced Layout
Managers
• GridBagLayout- Allows you to add
components to precise locations within the
grid, as well as to indicate that specific
Components should span multiple rows or
columns within the grid
• This class is difficult to use because you
must set the position and size for each
component
Learning about Advanced Layout
Managers
• BoxLayout- Components are arranged in
either a single row or a single column
• The box layout manager tries to make all
the components the same height(row) or
width(column) so components do not spill
over
BoxLayout
• Requires two arguments
– The first refers to the container to which the
layout manager applies
– The second is a constant
• BoxLayout.X_Axis for a row arrangement
• BoxLayout.Y_Axis for a column arrangement
Understanding Events and Event
Handling
• Events are Objects that the user initiates
– For example a mouse click or a key press
• The parent class for all event objects is
EventObject
– Event object descends from the Object class
– EventObject is the parent class to AWTEvent
which is the parent to specific classes such as
ActionEvent
Understanding Events and Event
Handling
Understanding Events and Event
Handling
• When you want to listen for an event, you can
implement an appropriate interface for the class
such as ActionListener or Window Listener
– The class becomes an event listener
– For every event class there is a similarly named listener
– Every <name> listener interface method has a return
type of void, and each takes one argument
Understanding Events and Event
Handling
• Event handlers- Interface methods, such as
actionPerformed(), that are called
automatically when an appropriate event
occurs
Understanding Events and Event
Handling
Understanding Events and Event
Handling
Understanding Events and Event
Handling
• The KeyListener interface- Used when you
are interested in events that users initiate
from the keyboard
– keyPressed()- provides information about keys
that don’t generate characters
– keyTyped()- provides information about what
key was typed
– keyReleased()- provides information about
keys that don’t generate characters
Using AWTEvent Class Methods
• AWTEvent Class methods- Use many of
these methods to determine the nature of
and the facts about an event in question
• The AWTEvent classes themselves contain
methods
Using Event Methods from Higher
in the Inheritance Hierarchy
• When you use an event such as KeyEvent,
you can use any of the event’s methods
• Because of inheritance, you can also use
methods that belong to any class that is a
superclass of the event with which you are
working
Handling Mouse Events
• When you write GUI programs, you
probably expect users to spend most of their
time operating a mouse
– You are interested in more than key presses
• The MouseListener interface provides you
with methods
Mouse Events
• mouseDragged()
• mouseMoved()
• mousePressed()
• mouseClicked()
• mouseReleased()
• mouseEntered()
• mouseExited()
Java Programming, Second Edition

Chapter Fifteen
Exception Handling
In this chapter, you will:

• Learn about exceptions


• Try code and catch Exceptions
• Use the Exception getMessage() method
• Throw and catch multiple Exceptions
• Use the finally block
• Understand the limitations of traditional
error handling
• Specify the Exceptions a method can throw
• Handle Exceptions uniquely with each catch
• Trace Exceptions through the call stack
• Create your own Exceptions
Learning about Exceptions
• Exception- An unexpected or error
condition
– For example:
• You issue a command to read a file from a disk, but
the file does not exist
• You write data to a disk but the disk is full or
unformatted
• The program attempts to divide by zero
Learning about Exceptions
• Exception Handling- The object-oriented
techniques to manage such errors comprise
the group of methods know as exception
handling
– There are two basic classes of errors
• Error and Exception
– Both classes descend from the Throwable class
– You must expect the unexpected
Learning about Exceptions
• Error class- Represents more serious errors
from which your program usually cannot
recover
– For example, spelling a class name incorrectly
or storing a required class in the wrong folder
Learning about Exceptions
• Exception class- Comprise less serious
errors that represent unusual conditions that
arise while a program is running, and from
which the program can recover
– Examples of Exception class errors include
using an invalid array subscript or performing
certain illegal arithmetic operations
Trying Code and Catching
Exceptions
• try block- A block of code you attempt to
execute, while acknowledging that an
Exception might occur
• Consists of the following elements:
– The keyword try
– An opening curly brace
– Statements that might cause exceptions
– A closing curly brace
Trying Code and Catching
Exceptions
• catch block- Must code at least one catch
block immediately following a try block
– A segment of code that can handle an
Exception that might be thrown by the try block
that precedes it
Creating a catch block
• Create a catch blocky by typing the following
elements:
– The keyword catch
– An opening parenthesis
– An Exception type
– A name for an instance of the Exception type
– A closing parenthesis
– An opening curly brace
– Statements that take the action you want to use to
handle the error condition
– A closing curly brace
General format of a try…catch pair
Using the Exception GetMessage()
Method
• getMessage() method- To retrieve Java's
message about any Throwable Exception
named someException
– Code someException.getMessage()
Throwing and Catching Multiple
Exceptions
– Can place as many statements as you need
within a try block
– Can catch as many Exceptions as you want
– If you try more than one statement, only the
first error-generating statement throws an
Exception
• As soon as the Exception occurs, the logic transfers
to the catch block
Throwing and Catching Multiple
Exceptions
– Multiple catch blocks are examined in sequence
until a match is found for the type of Exception
that occurred
• The match catch block executes and each remaining
catch block is bypassed
Using the finally Block
• The finally block contains actions you must
perform at the end of a try…catch sequence
• Code within a finally block executes
whether or not the preceding try block
identifies exceptions
• The finally block performs clean-up tasks
that must happen
Understanding the Limitations of
Traditional Error Handling
• Before object-oriented programming,
potential errors were handled using error-
prone methods
• Object-oriented exception handling allows
you to isolate error-handling code
Specifying the Exceptions a Method
can Throw
• When you write a method that might throw an
Exception, you can type the clause throws
<name> Exception after the method header to
indicate the type of exception that might be
thrown
• When you use any method you must know
– The method’s name
– The method’s return type
– The type and number of arguments it requires
– The type and number of Exceptions the method throws
Specifying the Exceptions a Method
can Throw
• Method's signature- A method's header,
including its name, any arguments, and any
throws clause
Handling Exceptions Uniquely with
Each catch
• When you use a class and one of its
methods throws an Exception, the class that
throws the Exception does not have to catch
it
• Your calling program can catch the
Exception, and then you can decide what to
do with it
Tracing Exceptions Through the Call
Stack
• Call stack- Where the computer stores the list of
locations to which the system must return
• When a method throws an Exception, and if the
method does not catch the Exception, the
Exception is thrown to the next method up the call
stack
• You can display this list using the
printStackTrace() method
Creating Your Own Exceptions
• Java provides over 40 categories of Exceptions
that you can throw in your programs
• Java also allows you to create your own
Exceptions
• You should extend your Exceptions from the
Exception class
• When you create an Exception, it's conventional to
end its name with Exception

Das könnte Ihnen auch gefallen