Tải bản đầy đủ (.pdf) (101 trang)

Java graphical user interfaces an introduction to java programming

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.14 MB, 101 trang )

Java: Graphical User Interfaces

An Introduction to Java Programming
David Etheridge

Download free books at


David Et heridge

Java: Graphical User I nt erfaces
– An I nt roduct ion t o Java Program m ing

Download free eBooks at bookboon.com
2


Java: Graphical User I nt erfaces – An I nt roduct ion t o Java Program m ing
© 2009 David Et heridge & Vent us Publishing ApS
I SBN 978- 87- 7681- 496- 0

Download free eBooks at bookboon.com
3


Contents

Java: Graphical User Interfaces

Cont ent s
1.


1.1
1.2
1.3
1.4
1.5
1.6
1.7

The Input/Output Package
An Introduction to Streams
Categories of Streams and their Classes
Using Streams
Object Streams
Files and File I/O
Data Streams
Summary of Streams

6
7
7
11
19
21
25
27

2.
2.1
2.2
2.3

2.4
2.5
2.6
2.7

Collecting Data II
The Java Collections Framework
The Core Collection Interfaces
Implementation Types
Operations, Methods, Iterators and Algorithms
Generics and the Collections Framework
Collections in the Themed Application
Summary of the Java Collections Framework

28
28
28
31
34
36
42
46

Download free eBooks at bookboon.com
4

Click on the ad to read more


Contents


Java: Graphical User Interfaces

3.
3.1
3.2
3.3
3.4
3.5
3.6
3.7

User Interfaces
What is a User Interface?
Client/Server Applications
The Construction of User Interfaces
A Visual Approach to GUI Design
Activating User Interface Components
The GUI for the Themed Application
Summary of Event Handling

47
47
49
50
64
68
83
87


4.
4.1
4.2
4.3
4.4

Concurrency with Threads
An Introduction to Threads
Creating Threads
Using Threads in Java Applications
Summary of Threads

90
90
91
93
100

360°
thinking

.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Download free eBooks at bookboon.com
5


Click on the ad to read more


The Input/ Output Package

Java: Graphical User Interfaces

1. The I nput / Out put Package
Chapter One considers some of the classes of the j a va .io package. Java defines input and output (I/O) in
terms of classes known as streams. Streams provide system input and output in a way that isolates the
developer from the details about how an operating system provides access to system resources for the
purposes of I/O. Streams are not required for input and output when a graphical user interface (GUI) is
used to capture and display information in an application. Graphical user interface design is examined in
Chapter Three.
There are approximately 60 classes in the j a va .io package. Consequently, this guide does not aim to cover
every stream class. Instead, some of the main categories of streams are explained in general terms and
examples are provided of the use of specific types of streams in a practical situation.
The reader is referred to the j a va .io package of the API for the documentation associated with the many
stream classes provided by the Java language.

GOT-THE-ENERGY-TO-LEAD.COM
We believe that energy suppliers should be renewable, too. We are therefore looking for enthusiastic
new colleagues with plenty of ideas who want to join RWE in changing the world. Visit us online to find
out what we are offering and how we are working together to ensure the energy of the future.

Download free eBooks at bookboon.com
6

Click on the ad to read more



The Input/ Output Package

Java: Graphical User Interfaces

1.1 An I nt roduct ion t o St eam s
A stream is an abstraction of the underlying mechanism that is used by an operating system to transfer
information into and out of a Java programme. The level of abstraction means that the developer uses
classes of the j a va .io package for I/O. As a consequence, I/O can be regarded as a high-level programming
activity that transparently maps onto the low-level mechanisms associated with system I/O.
A stream is a sequence of bits of information that is passed along a virtual path between a source and a
destination. An input stream provides a path from a source to a programme and, similarly, an output
stream is a path from a programme to a destination. Figure 1.1 visualises the general representation of
streams as paths between code and a source or a destination.

Figure 1.1 The source and destination associated with a stream

Sources and destinations of information include files, disks and networked resources; the information
passed along streams can take any form, such as objects, text, images and sound.

1.2 Cat egories of St ream s and t heir Classes
Streams in the j a va .io package usually occur as input/output pairs and fall into one of three categories byte streams, character streams or object streams. This section looks at classes in the first of these two
categories in relatively general terms to give a flavour of their functionality and to encourage the reader to
refer to the API for the j a v a .io package. A later section examines object streams.
1.1.1 Byt e St ream s
A byte streams carries a sequence of binary data and is one of two types, either an input stream or an
output stream. To read a byte stream in an application, one of the subclasses of the I npu t St r e a m class is
used. An extract from the API displayed on the next page shows some of the input stream classes that are
subclasses of the abstract class I n pu t St r e a m .


Download free eBooks at bookboon.com
7


The Input/ Output Package

Java: Graphical User Interfaces

java.io

Class InputStream
java.lang.Object
java.io.InputStream

All Implemented Interfaces:
Closeable
Direct Known Subclasses:
AudioInputStream, ByteArrayInputStream, FileInputStream, FilterInputStream,
ObjectInputStream
Table 1.1 below summarises the main functions of these I npu t St r e a m types, as indicated by the
documentation for each class in the API.
Type

Function

AudioInputStream

Reads a specified audio format and length of audio file

ByteArrayInputStream


Contains in internal buffer that contains bytes read from the stream

FileInputStream

Inputs bytes from a file in a file system

FilterInputSteam: has a number of
subclasses

Contains some other input stream, which it uses as its basic source
of data, possibly transforming the data along the way or providing
additional functionality

ObjectInputStream

Reads primitive data and objects previously written using an
ObjectOutputStream

Table 1.1 Some of the input streams

Some of the corresponding output stream classes that are subclasses of the abstract class Ou t pu t St r e a m
are shown in the next extract from the API.
java.io

Class OutputStream
java.lang.Object
java.io.OutputStream

All Implemented Interfaces:

Closeable, Flushable
Direct Known Subclasses:
ByteArrayOutputStream, FileOutputStream, FilterOutputStream, ObjectOutputStream

Download free eBooks at bookboon.com
8


The Input/ Output Package

Java: Graphical User Interfaces

Table 1.2 below summarises the main function of these Ou t pu t St r e a m types, as indicated by the
documentation for each class in the API.
Type

Function

ByteArrayOutputStream

Data is written into a byte array

FileOutputStream

Writes data to a file

FilterOutputStream: has a number of
subclasses

Contains some other output stream, which it uses as its basic source

of data, possibly transforming the data along the way or providing
additional functionality

ObjectOutputStream

Writes objects to a file for persistent storage

Table 1.2 Some of the output streams

The next sub-section presents a similar overview of some of the character streams.
1.2.2 Charact er St ream s
The Java language uses the UTF–16 (Unified Transformation Format) 16 bit encoding to represent text
characters. The streams that carry text-based information are called readers and writers. To read a
character stream in an application, one of the subclasses of the Re a de r class is used. The following extract
from the API shows some of the readers that are subclasses of the abstract class Re a de r .

Brain power

By 2020, wind could provide one-tenth of our planet’s
electricity needs. Already today, SKF’s innovative knowhow is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to maintenance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!


The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.
Visit us at www.skf.com/knowledge

Download free eBooks at bookboon.com
9

Click on the ad to read more


The Input/ Output Package

Java: Graphical User Interfaces

java.io

Class Reader
java.lang.Object
java.io.Reader

All Implemented Interfaces:
Closeable, Readable
Direct Known Subclasses:
BufferedReader, CharArrayReader, InputStreamReader, StringReader
Table 1.3 summarises the main function of these readers, as indicated by the API.
Type

Function


BufferedReader

Reads text from a character-input stream, buffering characters so as
to provide for the efficient reading of characters, arrays, and lines

CharArrayReader

This class implements a character buffer that can be used as a
character input stream

InputStreamReader

An InputStreamReader is a bridge from byte streams to character
streams. It reads bytes and decodes them into characters using a
specified charset. The charset that it uses may be specified by name
or may be given explicitly, or the platform's default charset may be
accepted

StringReader

A character stream whose source is a string

Table 1.3 Some of the readers

Some of the corresponding subclasses of the abstract class W r it e r are shown in the next extract from
the API.
java.io

Class Writer
java.lang.Object

java.io.Writer

All Implemented Interfaces:
Closeable, Flushable, Appendable
Direct Known Subclasses:
BufferedWriter, CharArrayWriter, OutputStreamWriter, PrintWriter, StringWriter
Table 1.4 on the next page summarises the main function of these writers, as indicated by the API.

Download free eBooks at bookboon.com
10


The Input/ Output Package

Java: Graphical User Interfaces

Type

Function

BufferedWriter

Writes text to a character-output stream, buffering characters so as
to provide for the efficient writing of single characters, arrays, and
strings

CharArrayWriter

This class implements a character buffer that can be used as a
character output stream


OutputStreamWriter

An OutputStreamWriter is a bridge from character streams to byte
streams: Characters written to it are encoded into bytes using a
specified charset. The charset that it uses may be specified by
name or may be given explicitly, or the platform's default charset
may be accepted

PrintWriter

Prints formatted representations of objects to a text output stream

StringWriter

A character stream that collects its output in a string buffer, which
can then be used to construct a string

Table 1.4 Some of the writers

The next section gives some examples of using streams.

1.3 Using St ream s
Although most applications use a GUI to input relatively small amounts of information to an application,
streams are very useful for testing the methods of classes in an application before such an interface is
constructed. On the output side of an application, object streams can be used to write objects out to a file
so that the data associated with an application takes on a persistent state. Streams are also extremely useful
when an application needs to output information to data storage devices or input data from them.
A general algorithm for using streams for I/O in an application can be expressed as follows:
1.

2.
3.

Instantiate a stream object: this automatically opens the stream.
Read from or write to the stream in a try block.
Catch IOException objects (and any other exceptions that may
occur).

4. Close the stream.
An application typically uses more than one stream chained together, depending on whether a buffer or a
bridge or some other functionality is required: see tables 13.1 to 13.4 for a summary of the functionality of
streams. Chaining streams can be visualised as connecting pipes together, as you would do when
undertaking plumbing jobs at home, as shown in Figure 1.2. (The author strongly recommends that the
reader never attempt this kind of thing in your own home; instead, bring in a professional plumber to do
the work.)

Download free eBooks at bookboon.com
11


The Input/ Output Package

Java: Graphical User Interfaces

Figure 1.2 Chaining streams together

Chaining is achieved by passing a stream object into the constructor of another stream object, as will be
shown by the examples that are presented in sub-section 1.3.2 below. Before embarking on the examples
of chaining streams, sub-section 1.3.1 looks at how streams are used for screen output.
1.3.1 Screen Out put

A number of examples in previous chapters use the statement
System.out.println( );
to output the results of test classes to a computer’s screen.

With us you can
shape the future.
Every single day.
For more information go to:
www.eon-career.com

Your energy shapes the future.

Download free eBooks at bookboon.com
12

Click on the ad to read more


The Input/ Output Package

Java: Graphical User Interfaces

The Syst e m class includes a number of fields that are used for input and output. The static field with the
identifier ou t provides an output stream of the Pr in t St r e a m type. The stream is automatically open and is
ready to accept output data.
The class Pr int St r e a m inherits from a subclass of Ou t pu t St r e a m , as shown in the extract from the API.
java.io

Class PrintStream
java.lang.Object

java.io.OutputStream
java.io.FilterOutputStream
java.io.PrintStream

A Pr in t St r e a m object adds functionality to its parent output stream, so that it can print primitive data to
the console. All characters printed by a Pr in t St e a m object are converted into bytes using the platform's
default character encoding. One interesting and convenient feature of Pr in t St r e a m objects is that they
never throw an I OEx ce pt ion .
Standalone Java applications, such as those that use a dedicated m a in method for testing purposes, write a
line of output as follows:
System.out.println( data );
The pr int and pr int ln methods of the Pr int St r e a m class are overloaded for primitive data types.
If an object reference is passed to any of the variants of pr int or pr in t ln , as in
System.out.println( objectReference );
the pr in t ln method calls St r in g.v a lu e Of( obj e ct Re fe r e n ce ) to return the object’s St r ing value before it
behaves as though it invokes pr in t ln with a St r in g passed to it. In effect, the statement behaves as if it
invokes the t oSt r ing method on obj e ct Re fe r e n ce .
In general, invoking t oSt r ing on an object reference returns what is known as the St r ing representation of
the object. It is good practice to override this method for all developer-written classes so that the result is a
representation of the object that is informative when invoked.
1.3.2 Keyboard I nput
The static field with the identifier in of the Syst e m class is an I npu t St r e a m object that can be used for
keyboard input. Given that I n put St r e a m is an abstract class, an appropriate subclass is automatically
instantiated when accessing the in field of Syst e m . This stream is already open and ready to supply input
data. The I npu t St r e a m class has a r e a d method that reads a byte of data and returns an int in the range 0
to 255. The int is cast to convert it to a ch a r .
The example that follows shows how a byte is entered via the computer’s keyboard and output to the
computer’s screen.
Download free eBooks at bookboon.com
13



The Input/ Output Package

Java: Graphical User Interfaces

import java.io.*;
public class Keyboard {
public static void main( String[ ] args ) {
try
{
System.out.print( "Please press any key: " );
char key = ( char )System.in.read( );
System.out.print( "The key pressed was: " + key );
System.out.println( "The class is: " + System.in.toString( ) );
}
catch( IOException ioe )
{
// do something about the exception
}
} // end of main
} // end of class definition
Executing main results in the following output:
C:\ > java Keyboard
Please press any key: a
The key pressed was: a
The class is: java.io.BufferedInputStream@3e25a5
The output shows that selecting Syst e m .in .t oSt r in g( ) returns the object reference of the object that is
automatically instantiated when referring to Syst e m .in and shows that the object is of the type
Buffe r e dI n pu t St r e a m . The class Bu ffe r e dI n pu t St r e a m is shown in the next extract from the API.

java.io

Class BufferedInputStream
java.lang.Object
java.io.InputStream
java.io.FilterInputStream
java.io.BufferedInputStream

We can conclude, therefore, that selecting Syst e m .in instantiates an object of the Buffe r e d I n pu t St r e a m
type and closes the stream when it has been finished with.
The code for the Ke yboa r d class (on the previous page) implies that invoking r e a d should be included in a
loop to add each ch a r to a St r in g to, in effect, input a string of characters via the keyboard. However, the
code would have to detect when the last character has been entered in order to determine the end of
the loop.
Download free eBooks at bookboon.com
14


The Input/ Output Package

Java: Graphical User Interfaces

In short, using Syst e m .in .read is not a particularly useful way to input data from the computer’s keyboard.
As an alternative, a number of streams can be chained together in order to read characters and strings and
numbers from the keyboard.
String Input via the Keyboard
The following class chains three streams in order to read characters from the keyboard. Firstly, Syst e m .in
is the byte stream that is used for keyboard input, as shown in the previous sub-section. Secondly,
Syst e m .in is connected to a stream of the I n pu t St r e a m Re a de r type to act a bridge between the byte stream
and a character stream. Thirdly, a buffer is required because keyboard input tends to be irregular.

Therefore, the I npu t St r e a m Re a de r is connected to a buffer of the Bu ffe r e dRe a de r type. The re a dLin e
method of Bu ffe r e dRe a d e r reads, in the example below, a set of characters from the keyboard. When the
enter key is pressed, the method returns a St r in g .
Chaining the three streams together is achieved by passing one stream object to the constructor of the next
stream in the chain, as shown in the class definition that follows and continues on the next page.

All rights reserved.

© 2013 Accenture.

Bring your talent and passion to a
global organization at the forefront of
business, technology and innovation.
Discover how great you can be.
Visit accenture.com/bookboon

Download free eBooks at bookboon.com
15

Click on the ad to read more


The Input/ Output Package

Java: Graphical User Interfaces

import java.io.*;
public class KeyboardInput {
public static void main( String[ ] args ) {
// Instantiate a bridge stream and pass the object instantiated by Syst e m .in to

// its constructor.
InputStreamReader isr = new InputStreamReader( System.in );
// Instantiate a buffered stream and pass the I n pu t St r e a m Re a de r to its
// constructor.
BufferedReader kbd = new BufferedReader( isr );
try
{
System.out.print( "Enter some characters and press “ +
“return when finished: " );
String s = kbd.readLine( );
System.out.println( "The String was: " + s );
// Close the initial stream; this will close all streams connected to it.
kbd.close( );
}
catch( IOException e )
{
e.printStackTrace( );
}
} // end of main
} // end of class definition
The result of executing main is:
Enter some characters and press return when finished: Hello World
The String was: Hello World
Numerical Input via the Keyboard
Syst e m .in cannot be expected to distinguish numerical input from pressing any other of the keys on the
keyboard. The object instantiated by Syst e m .in reads the next byte of data entered via the keyboard when
its r e a d method is invoked. When this object is chained, as in the code for KeyboardInput in the previous
sub-section, the r e a dLin e method of a Bu ffe r e dRe a de r returns a St r in g .

Numerical input via the keyboard is relatively straightforward in that a St r in g is returned in a similar way

to that used in the code for the KeyboardInput class. The St r in g is then converted into the corresponding
primitive type.
The class definition shown on the next page illustrates this technique for integer input.

Download free eBooks at bookboon.com
16


The Input/ Output Package

Java: Graphical User Interfaces

import java.io.*;
public class ReadInt {
public static void main( String[ ] args ) {
try
{
BufferedReader kbd = new BufferedReader( new
InputStreamReader( System.in ) );
System.out.print( "Enter an integer: " );
String intStr = kbd.readLine( );
// Convert the String into its corresponding integer by calling one of
// the methods of the I nt e ge r wrapper class.
int number = Integer.parseInt( intStr );
System.out.println( "The number is " + number );
}
catch( IOException ioe )
{
// do something about it
}

} //End of main.
} // End of class definition.
The result of executing main is as follows:
Enter an integer: 123
The number is 123
The class definition shown on the next page shows a similar way to enter a double into a programme from
the keyboard.

Download free eBooks at bookboon.com
17



×