Sei sulla pagina 1di 137

]<gj]<]<j<^]<]

W
K

????
K


]<gj]<]<j<^]<]

K
K

K
K

--


Inheritance and Polymorphism


Object Oriented programming

K
Classes

Objects
Methods

J F
Instance variables

E
K

Class
Objects

Behavior Member variablesDataAttributes

WMember Methods
Access specifier
Ex:
public
class

class

class_name
BankAccount

public

class

public classmain

Constructors
Constructors

K
Parameters

--

BankAccount.java
1 public class BankAccount
2 {
3 // The first constructor is the default constructor sets balance to zero
4
public BankAccount()
5
{
6
balance = 0;
7
}
8 // The second constructor sets balance to initial to initial balance
9
public BankAccount(double initialBalance)
10
{
11
balance = initialBalance;
12
}
13 // The deposit method adds an amount to instance variable balance
14
public void deposit(double amount)
15
{
16
balance = balance + amount;
17
}
18 // The withdraw method subtracts an amount from instance variable balance
19
public void withdraw(double amount)
20
{
21
balance = balance - amount;
22
}
23 // The transfer method withdraw an amount from this object and deposit to
other object balance
24
public void transfer(BankAccount other , double amount)
25
{
26
withdraw(amount);
27
other.deposit(amount);
28
}
29
30
// The getBalance method returns the current balance
31
public double getBalance()
32
{
33
return balance;
34
}
35
// The instance variable balance
36
private double balance;
37 }

EJ F

--

K
double

Constructors K

K
Access Specifier
Ex:
Public

Class name (parameter type parameter name, .)


BankAccount (double

initialBalance)

Methods

Methods BankAccount

deposite Method

withdraw method

transfer method

getBalance method

Wmethod

Access specifier
return type
method name(parameter type parameter name,..)
Ex 1:
public
void
deposite (double amount)
Ex 2:
public
double
getBalance
public

double

Kvoid

--

small letter

getBalance

E,F

implicit parametersEF

explicit parameter

InstanceObjects

new
Ex1:
BankAccount myAccount = new BankAccount();

myAccount
balanceBankAccountBankAccount()
myAccount
Ex2:
BankAccount m1 = new BankAccount(5000);

m1
BankAccount BankAccount(double

initialBalance)

m1balance

--

instance variables

W

Access specifier
type
Ex:
private
double

variable name;
balance;

private

Encapsulationdata hiding

OOP

Ex1:
myAccount.balance
Ex2:
m1.balance

Ex:
m1.deposit(500);

deposit
depositm1

balance = balance + amount


this.balnce = this.balance + amount
m1.balance = m1.balance +amount

--

Inheritance

OOP inheritance

K W

BankAccount

KEJ F
SavingAccount.java
/* The SavingAccount class extends the BankAccount class implements
a new method addInterest to model an account that pays a fixed
interest rate on deposits
*/
public class SavingAccount extends BankAccount
// The SavingAccount constructor
{
public SavingAccount(double rate)
{
interestRate = rate;
}
// addInterest method
public void addInterest()
{
double interest = getBalance()*interestRate/100;
deposit(interest);
}
// The SavingAccount instance variable
private double interestRate;
}

EJ F

--


code

reuse

superclass EF

Base parent class

class

subclass

drived child class


class
J


extends




W
class subclass Name
ex:
class SavingAccount

extends

superclass Name

extends

BankAccount

superclassEF
BankAccount

subclassSavingAcount

Object

ObjectBankAccount Object

KtoString

SavingAccountBankAccountObjectEJ F

Inheritance Diagram

--

Object

BankAccount

SavingAccount

EJ F

Ex:
SavingAccount

m2 = new SavingAccount(10)

SavingAccountm2
balanceBankAccount

intrestRateSaving Account
W
m2.balance = 0
m2.intrestRate = 10

balance

SavingAccountm2EJ

FintrestRate

SavingAccount
Bankaccount portion

Balance 1000
interestRate 10

EJ F

K
--

Ex:

m2.addIntrest();

SavingAccountaddIntrest

BankAccountdepositgetBalance

WaddIntrest addIntrest
double interest =this.getBalance() * this.intrestRate/100
this.deposit(intrest)

WaddIntrest()m2.addIntrest();
double interest = m2.getBalance() * m2.intrestRate/100
m2.deposit(intrest)

C++single inheritance

Multiple inheritance

K
Inheritance Hierarchies

branches root
K
WW

CheckingAccount

SavingAccount

TimeDepositAccount

balance

getBalance withdrawdeposit
- -

BankAccount

EJ F

BankAccount
getBalance
deposit
withdraw

CheckingAccount

SavingAccount

deductFees
deposit
withdraw

addInterest

TimeDeposit
Account
addInterest
withdraw

EJ F

- -

instance variablesmethods
W Methods

EF
override

method
K

Instance variables

BankAccountEJ FCheckingAccount
transactionCount deductFees()
withdrawdeposit

transactionCount

CheckingAccount

BankAccountbalance

CheckingAccounttransactionCount

WCheckingAccount

BankAccountgetBalance()
- -

E Fdeposit(double

amount)

BankAccount)

EFwithdraw(double

amount)

BankAccount
CheckingAccountdeductFees()

CheckingAccount deposit(double amount)

- -

CheckingAccount.java
/* The CheckingAccount class extends the BankAccount class implements
a new method deductFees and overide the deposit and withdraw methods
*/
public class CheckingAccount extends BankAccount
// The CheckingAccount constructor
{
public CheckingAccount(double initialBalance)
{
// construct superclass
super(initialBalance);
// initialize transaction count
transactionCount = 0;
}
// overide the BankAccount deposit method
public void deposit(double amount)
{
transactionCount ++;
// now add amount to balance
super.deposit(amount);
}
// overide the BankAccount withdraw method
public void withdraw(double amount)
{
transactionCount ++;
// now subtract amount from balance
super.withdraw(amount);
}
// New method deductFees
public void deductFees()
{
if(transactionCount>FREE_TRANSACTIONS)
{
double fees =
TRANSACTION_FEE*(transactionCount- FREE_TRANSACTIONS);
super.withdraw(fees);
}
transactionCount = 0;
}
// The CheckingAccount instance variables
private int transactionCount;
private static final int FREE_TRANSACTIONS = 3;
private static final double TRANSACTION_FEE = 2.0;
}

EJ F
- -

override


// override the BankAccount deposit method
public void deposit(double amount)
{
transactionCount ++;
// now add amount to balance
balance = balance + amount;
}

//ERROR

balance

private

balance deposit(amount)

// override the BankAccount deposit method


public void deposit(double amount)
transactionCount ++;
// now add amount to balance
deposit(amount);

this
deposit(amount)
deposit(double

amount)CheckingAccount

super

// override the BankAccount deposit method


public void deposit(double amount)
transactionCount ++;
// now add amount to balance
super.deposit(amount);

// override the BankAccount withdraw method


public void withdraw(double amount)
- -

transactionCount ++;
// now subtract amount from balance
super.withdraw(amount);

deductFees

fees

withdraw(fees)



// New method deductFees
public void deductFees()
if(transactionCount>FREE_TRANSACTIONS)
double fees = TRANSACTION_FEE*(transactionCount- FREE_TRANSACTIONS);
super.withdraw(fees);
transactionCount = 0;

TimeDepositAccount
SavingAccount

EJ F

periodsToMaturity TimeDepositAccount

addIntrest

TimeDepositAccountEJ F

BankAccount BankAccount

depositgetBalanceTimeDepositAccount

K
- -

override

TimeDepositAccount

methodaddInterest()

SavingAccount
// override the SavingAccount addInterest method
public void addInterest()
periodsToMaturity--;
super.addInterest();

withdraw(double amount)

W
// override the BankAccount withdraw method
public void withdraw(double amount)
if (periodsToMaturity >0)
super.withdraw(EARLY_WITHDRAW_PENALITY);
// now subtract amount from balance
super.withdraw(amount);

- -

TimeDepositAccount.java
/* The TimeDepositAccount extends SavingAccount class overrides
the SavingAccount addInterest method and the BankAccount withdraw
method to model an account like SavingAccount but you promize to leave
the mony in the account for a particular number of months, and
there is a penalty for early withdrawal.
*/
public class TimeDepositAccount extends SavingAccount
// The TimeDepositAccount constructor
{
public TimeDepositAccount(double rate , int maturity)
{
super (rate);
periodsToMaturity = maturity;
}
// override the SavingAccount addInterest method
public void addInterest()
{
periodsToMaturity--;
super.addInterest();
}
// override the BankAccount withdraw method
public void withdraw(double amount)
{
if (periodsToMaturity >0)
super.withdraw(EARLY_WITHDRAW_PENALITY);
// now subtract amount from balance
super.withdraw(amount);
}
// The TimeDepositAccount instance variables
private int periodsToMaturity;
private static final double EARLY_WITHDRAW_PENALITY = 20.0;
}

EJ F
super.addIntrest(); TimeDepositAccount
addIntresetK super.withdraw(amount);

withdrawSavingAccount
withdraw

KBankAccount
- -

Subclass constructors

balanceCheckingAccount

balanceBankAccount

super
W
// The CheckingAccount constructor
public CheckingAccount(double initialBalance)
// construct superclass
super(initialBalance);
// initialize transaction count
transactionCount = 0;

BankAccountCheckingAccount

balanceBankAccount

balance CheckingAccount

// The CheckingAccount constructor


public CheckingAccount(double initialBalance)
// superclass has been constructed with its default //constructor
// now set initial balance
super.deposit(initialBalance);
// initialize transaction count
transactionCount = 0;

SavingAccount TimeDepositAccount

// The TimeDepositAccount constructor
public TimeDepositAccount(double rate , int maturity)
super (rate);
periodsToMaturity = maturity;
- -

Polymorphism

"is a"

ChechingAccount
BankAccount

BankAccounttransfer


// The transfer method withdraw an amount from this object and //deposit to other object balance
public void transfer(BankAccount other , double amount)
withdraw(amount);
other.deposit(amount);

BankAccount

transfer

Ex:
BankAccount c1 = new BankAccount(1000);
CheckingAcount c2 = new CheckingAccount(2000);
C1.transfer(c2,500);

BankAccount K

EJ F CheckingAccountBankAccount

Bankaccountother deposit

deposit

BankAccount.deposit
transactionCount
deposit CheckingAccount

CheckingAccounttransferother

BankAccount.depositCheckingAccount.depoit

actual object

other.depositreference

object

KOOP

many shapespolymorphism

polymorphicinstance methods
- -


overloaded methods explicit parameters

compiler
explicit parameters

overload polymorphism
overload
early

binding

compiler deposit
virtual machine
other

late bindingcompiler

EJ FpolymorphismTestEJ FBankAccountTest

- -

BankAcountTest.java
public class BankAcountTest
{
/* This program is used to test the diferent bankAcounts
classes
*/
// The main method
public static void main(String [] args)
{
BankAccount mohamed = new BankAccount();
BankAccount ahmed = new BankAccount(1000);
BankAccount mahmoud = new BankAccount(2000);
mohamed.deposit(3000);
ahmed.deposit(3000);
mahmoud.deposit(3000);
// transfer 1000Sr from mahmoud to ahmed
mahmoud.transfer(ahmed,1000);
System.out.println(mohamed.getBalance());
System.out.println(ahmed.getBalance());
System.out.println(mahmoud.getBalance());
// construct new SavingAccount object called moustafa
SavingAccount moustafa = new SavingAccount(5);
moustafa.deposit(1000);
moustafa.addInterest();
System.out.println(moustafa.getBalance());
// construct new CheckingAccount object called baker
CheckingAccount baker = new CheckingAccount(5000);
baker.deposit(1000);
baker.deposit(1000);
baker.deposit(1000);
baker.deposit(1000);
baker.deposit(1000);
baker.withdraw(2000);
baker.deductFees();
System.out.println(baker.getBalance());
// construct new TimeDepositAccount object called flah
TimeDepositAccount flah = new TimeDepositAccount(5,5);
flah.deposit(10000);
System.out.println(flah.getBalance());
flah.addInterest();
System.out.println(flah.getBalance());
flah.addInterest();
System.out.println(flah.getBalance());
flah.deposit(1000);
System.out.println(flah.getBalance());
flah.addInterest();
System.out.println(flah.getBalance());
flah.withdraw(5000);
System.out.println(flah.getBalance());
- -

flah.addInterest();
System.out.println(flah.getBalance());
flah.addInterest();
System.out.println(flah.getBalance());
flah.withdraw(5000);
System.out.println(flah.getBalance());
}
}

EJ F
PolymorphismTest.java
public class PolymorphismTest
{
/* This program is used to test the principles of polymorphism
*/

// The main method


public static void main(String [] args)
{
// construct new SavingAccount object called abdalah
SavingAccount abdalah = new SavingAccount(0.5);
// construct new TimeDepositAccount object called flah
TimeDepositAccount flah = new TimeDepositAccount(1,3);
// construct new CheckingAccount object called baker
CheckingAccount baker = new CheckingAccount(0);
abdalah.deposit(10000);
flah.deposit(10000);
printBalance("abdalah ",abdalah);
printBalance("flah ",flah);
printBalance("baker ",baker);
// transfer 1000Sr from abdalah to baker
abdalah.transfer(baker,2000);
// transfer 1000Sr from flah to baker
flah.transfer(baker,980);
- -

printBalance("abdalah ",abdalah);
printBalance("flah ",flah);
printBalance("baker ",baker);

baker.withdraw(500);
printBalance("baker ",baker);
baker.withdraw(80);
printBalance("baker ",baker);
baker.withdraw(400);
printBalance("baker ",baker);
endOfMonth(abdalah);
endOfMonth(flah);
endOfMonth(baker);
printBalance("abdalah ",abdalah);
printBalance("flah ",flah);
printBalance("baker ",baker);
}
public static void endOfMonth(SavingAccount savings)
{savings.addInterest();
}
public static void endOfMonth(CheckingAccount checking)
{checking.deductFees();
}
public static void printBalance(String name , BankAccount account)
{System.out.println("The balance of " + name +
"account is " + account.getBalance()+" SR");
}
}

EJ F

PolymorphismTest

The balance of abdalah account is 10000.0 SR


The balance of flah account is 10000.0 SR
The balance of baker account is 0.0 SR
The balance of abdalah account is 8000.0 SR
The balance of flah account is 9000.0 SR
The balance of baker account is 2980.0 SR
The balance of baker account is 2480.0 SR
The balance of baker account is 2400.0 SR
The balance of baker account is 2000.0 SR
The balance of abdalah account is 8040.0 SR
The balance of flah account is 9090.0 SR
The balance of baker account is 1996.0 SR

- -


]<gj]<]<j<^]<]

K
K

try K

catch K
finally K

K
W

- -


Exception Handling

syntax error

Error codes

W
J


The basics of java Exception Handling

Error codes

program
JVM

K
- -

JVM

exception

handler

K
KK

EJ F

EdF

(-)

EJ F
Process completed
(compiler)

EF

Exception in thread "main" java.lang.ArithmeticException: /by zero at Excp1.main <Excp1.java:6>


- -

ArithmaticException
EJ F /by

zero

(-)


EJ F

a[2] = 6;EJ F

W
Exception in thread "main" java.lang.ArrayIndexOutOfBoundException at Excp1.main <Excp3.java:9>

ArrayIndexOutOfBoundException
- -

EJ F

EJ F
- -

Exception types

class classes

Throwable
java.langError

subclassException subclass

program related

JVM

root classException

ExceptionEJ F

ExceptionEJ

ArithmaticException

ArrayIndexOutOfBoundsException

ClassNotFoundException

FileNotFoundException

IOException

NullPointerException

null reference

root classError

OutOfMemoryError class JVM


K
- -

Exception Handling In java

W
abcde-

try block
catch blocks
finally block
throw statement
throws clause
trycatch finally blocks :

try
catch

finally catch

try
W
try
// Tested statements
catch ( ExceptionType 1 exob1)
// exception handler for ExceptionType1
catch ( ExceptionType 2 exob2)
// exception handler for ExceptionType2
finally
// Statements that must be executed

EJ F

d ArithmaticException

Wtry

try
int d=0;
int a=60/d;
- -

Wcatch
catch (ArithmeticException e)
System.out.println("divide by zero");
System.out.println(e.getMessage());

EJ F

ArithmeticException

divide by zero

/by

zeroe

After Exception Handling

EJ F

a[2]ArrayIndexOutOfBoundsException


try
W
try
a[0]=2;
a[1]=4;
a[2]=6;

- -

(-)

(-)
- -

WcatchArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e)
System.out.println("Array Index out of bounds.."+ e);

finally
Ktry

EJ F

(e)
Array

Index

out

of

bounds

java.lang.ArrauIndexOutofBoundsException
Wfinally

The code here must be executed

(-)

- -

EJ F
finally

catch

try

catch
K

EJ F
try

ArithmeticExceptioncatch
KArrayIndexOutOfBoundsException

Handling the first Exception divide by zero


/by zero

finally

The code here must be executed

W
Ktry

( -)

Handling the second Exception Array Index out of bounds


Array Index out of bounds java.lang.ArrauIndexOutofBoundsException

finally
The code here must be executed

Ktry
- -

(-)

(-)
- -

- -

- -

- -

DivideByZeroException.java
Created with JBuilder
// DivideByZeroException.java
// Definition of class DivideByZeroException.
// Used to throw an exception when a
// divide-by-zero is attempted.
public class DivideByZeroException
extends ArithmeticException {
public DivideByZeroException()
{
super( "Attempted to divide by zero" );
}
public DivideByZeroException( String message )
{
super( message );
}

NegativeNumberException.java
Created with JBuilder
// NegativeNumberException.java
// Definition of class NegativeNumberException.
// Used to throw an exception when a
// negative number is intered
public class NegativeNumberException
extends ArithmeticException {
public NegativeNumberException()
{
super( "Attempted to Enter negative numbers" );
}
}

- -

DivideByZeroTest.java
Created with JBuilder
// DivideByZeroTest.java
// A simple exception handling example.
// Checking for a divide-by-zero exception
// and negative number exception
import java.text.DecimalFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DivideByZeroTest extends JFrame
implements ActionListener {
private JTextField input1, input2, output;
private int number1, number2;
private double result;
// Initialization
public DivideByZeroTest()
{
super( "Demonstrating Exceptions" );
Container c = getContentPane();
c.setLayout( new GridLayout( 3, 2 ) );
c.add( new JLabel( "Enter numerator ",
SwingConstants.RIGHT ) );
input1 = new JTextField( 10 );
c.add( input1 );
c.add(
new JLabel( "Enter denominator and press Enter ",
SwingConstants.RIGHT ) );
input2 = new JTextField( 10 );
c.add( input2 );
input2.addActionListener( this );
c.add( new JLabel( "RESULT ", SwingConstants.RIGHT ) );
output = new JTextField();
c.add( output );
setSize( 425, 100 );
show();
}
- -

// Process GUI events


public void actionPerformed( ActionEvent e )
{
DecimalFormat precision3 = new DecimalFormat( "0.000" );
output.setText( "" ); // empty the output JTextField
try {
number1 = Integer.parseInt( input1.getText() );
number2 = Integer.parseInt( input2.getText() );
if(number1 < 0 || number2 <0)
throw new NegativeNumberException();
result = quotient( number1, number2 );
output.setText( precision3.format( result ) );
}
catch ( NumberFormatException nfe ) {
JOptionPane.showMessageDialog( this,
"You must enter two integers",
"Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
}
catch ( DivideByZeroException dbze ) {
JOptionPane.showMessageDialog( this, dbze.toString(),
"Attempted to Divide by Zero",
JOptionPane.ERROR_MESSAGE );
}
catch ( NegativeNumberException nne ) {
JOptionPane.showMessageDialog( this, nne.toString(),
"Attempted to Enter negative numbers",
JOptionPane.ERROR_MESSAGE );
}
}
// Definition of method quotient. Used to demonstrate
// throwing an exception when a divide-by-zero error
// is encountered.
public double quotient( int numerator, int denominator )
throws DivideByZeroException
{
if ( denominator == 0 )
throw new DivideByZeroException();
return ( double ) numerator / denominator;
}
public static void main( String args[] )
{
DivideByZeroTest app = new DivideByZeroTest();
- -

app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
e.getWindow().dispose();
System.exit( 0 );
}
}
);
}
}

UsingException.java
Created with JBuilder
// UsingExceptions.java
// Demonstration of the try-catch-finally
// exception handling mechanism.
public class UsingException {
public static void main( String args[] )
{
try {
throwException();
}
catch ( Exception e )
{
System.err.println( "Exception handled in main" );
}
doesNotThrowException();
}
public static void throwException() throws Exception
{
// Throw an exception and immediately catch it.
try {
System.out.println( "Method throwException" );
throw new Exception(); // generate exception
}
catch( Exception e )
{
System.err.println(
"Exception handled in method throwException" );
throw e; // rethrow e for further processing
// any code here would not be reached
}
- -

finally {
System.err.println(
"Finally executed in throwException" );
}
// any code here would not be reached
}
public static void doesNotThrowException()
{
try {
System.out.println( "Method doesNotThrowException" );
}
catch( Exception e )
{
System.err.println( e.toString() );
}
finally {
System.err.println(
"Finally executed in doesNotThrowException" );
}
System.out.println(
"End of method doesNotThrowException" );
}
}

UsingException1.java
Created with JBuilder
// UsingExceptions.java
// Demonstration of stack unwinding.
public class UsingException1 {
public static void main( String args[] )
{
try {
throwException();
}
catch ( Exception e ) {
System.err.println( "Exception handled in main" );
}
}
public static void throwException() throws Exception
{
// Throw an exception and catch it in main.
try {
System.out.println( "Method throwException" );
throw new Exception(); // generate exception
}
catch( RuntimeException e ) { // nothing caught here
- -

System.err.println( "Exception handled in " +


"method throwException" );
}
finally {
System.err.println( "Finally is always executed" );
}
}
}

UsingException2.java
Created with JBuilder
// UsingExceptions.java
// Demonstrating the getMessage and printStackTrace
// methods inherited into all exception classes.
public class UsingException2 {
public static void main( String args[] )
{
try {
method1();
}
catch ( Exception e ) {
System.err.println( e.getMessage() + "\n" );
e.printStackTrace();
}
}
public static void method1() throws Exception
{
method2();
}
public static void method2() throws Exception
{
method3();
}
public static void method3() throws Exception
{
throw new Exception( "Exception thrown in method3" );
}
}

- -


]<gj]<]<j<^]<]

K K

- -


Event Handling

command line

console application

graphical user interface (GUI)

pull down menu Text field


close window click button

Event Sources Event listeners Event

java window manager

eventsevent


mouse event

W event listener
Keyboard events

mouse move events

mouse click events


Window close events

Button click events


- -

event listener classes


K

event source
event listener

W user interface component

Button click eventsbutton


menu selection eventmenu

scrollbar adjustment eventscrollbar

Kevent source
W

an applet

MouseEventThe event class J


EyxF

MouseListenerThe listener class J



MouseEvent

component
The event source J
the applet

EJ FEventObject event classes

getSourceEventObjectK


getYgetXMouseEvent

- -

EventObject

AWTEvent

ActionEvent

Component Event

InputEvent

MouseEvent

WindowEvent

KeyEvent

EJ F


MouseListener interface
public interface Mouselistener
{
void mouseClicked (MouseEvent event)
// called when the mouse has been clicked on a component
void mouseEntered (MouseEvent event)
// called when the mouse enters a component
void mouseExited (MouseEvent event)
// called when the mouse exits a component
void mousePressed (MouseEvent event)
// called when the mouse button has been presseded on a component
void mouseReleaseded (MouseEvent event)
// called when the mouse button has been releaseded on a component
}

- -

MouseSpy
EYxF Mouselistener

EJ F

appletaddMouseListener

addMouseListenerMouseSpy

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.

//listen to mouse evnts in an applet


import java.awt.*;
import java.applet.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
public class MouseSpyApplet extends Applet
{
public MouseSpyApplet()
{
MouseSpy listener = new MouseSpy();
addMouseListener(listener);
}
}
class MouseSpy implements MouseListener
{
public void mouseClicked (MouseEvent event)
{
System.out.println("Mouse cliked. x= " +event.getX() +
" Y= " +event.getY());
}
public void mouseEntered (MouseEvent event)
{
System.out.println("Mouse entered. x= " +event.getX() +
" Y= " +event.getY());
}
public void mouseExited (MouseEvent event)
{
System.out.println("Mouse exited. x= " +event.getX() +
" Y= " +event.getY());
}
public void mousePressed (MouseEvent event)
{
System.out.println("Mouse pressed. x= " +event.getX() +
" Y= " +event.getY());
}
public void mouseReleased (MouseEvent event)
{
System.out.println("Mouse released. x= " +event.getX() +
" Y= " +event.getY());
}
41. }
(-)

- -


the applet
EJ F
EJ F

mousePressedy=147x=474
mouseReleasedy=161x=168

y=103x=94
mouseClickedmouseReleasedmousePressed
y=286x=216 applet

y=319x=239 mouseEntered

KmouseExited

EJ F
- -

Event Adapter

listener

Klistener methods
mouse click
mouse releasedmouse pressed

methods
W
1. class MouseClickListener implements MouseListener
2. {
3. public void mouseClicked (MouseEvent event)
4. {
5.
// mouse click action here
6. }
7. public void mouseEntered (MouseEvent event)
8.
{
9.
// do nothing
10. }
11. public void mouseExited (MouseEvent event)
12. {
13.
// do nothing
14. }
15. public void mousePressed (MouseEvent event)
16. {
17.
// do nothing
18.
19. }
20. public void mouseReleased (MouseEvent event)
21. {
22.
// do nothing
23.
24. }
25. }
methods MouseListener interface adapter class
do nothing
1. class MouseAdapter implements MouseListener
2. // This class is defined in the java.awt.event package
3. {
4. public void mouseClicked (MouseEvent event)
5. {
6.
// do nothing
7. }
8. public void mouseEntered (MouseEvent event)
9.
{
- -

10.
// do nothing
11. }
12. public void mouseExited (MouseEvent event)
13. {
14.
// do nothing
15. }
16. public void mousePressed (MouseEvent event)
17. {
18.
// do nothing
19. }
20. public void mouseReleased (MouseEvent event)
21. {
22.
// do nothing
23. }
24. }

MouseAddapterK

class MouseClickListener extends MouseAdapter


{
public void mouseClicked (MouseEvent event)
{
// mouse click action here
}

ActionListener listener interface


implement interface

java.awt.event extend the adapter


E F

two methods adapter class

WindowListener

Implementing Listener as inner class

System.out

ellipse EJ F
K

W
import java.awt.*;
- -

import java.applet.*;
import java.awt.event.*;
import java.awt.geom.*;
public class EggApplet extends Applet
{
public EggApplet()
{
egg = new Ellipse2D.Double(0,0,EGG_WIDTH, EGG_HIGHT);
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
g2.draw(egg);
}
private Ellipse2D.Double egg;
private static final double EGG_WIDTH = 30;
private static final double EGG_HIGHT = 50;

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.geom.*;
public class EggApplet extends Applet
{
public EggApplet()
{
egg = new Ellipse2D.Double(0,0,EGG_WIDTH, EGG_HIGHT);
// add mouse click listener
MouseClickListener listener = new MouseClickListener();
addMouseListener(listener);
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
g2.draw(egg);
}
private Ellipse2D.Double egg;
private static final double EGG_WIDTH = 30;
private static final double EGG_HIGHT = 50;
class MouseClickListener extends MouseAdapter
{
public void mouseClicked(MouseEvent event)
- -

int mouseX=event.getX();
int mouseY=event.getY();
// now move the ellipse to (mouseX, MouseY)
egg.setFrame(mouseX-EGG_WIDTH/2, mouseY-EGG_HIGHT/2,
EGG_WIDTH, EGG_HIGHT);
repaint();

MouseClickListener

KEggApplet

C:\programming 3\chapter10\EggApplet\EggApplet.java:52: cannot resolve symbol


symbol : variable EGG_WIDTH
location: class MouseClickListener
egg.setFrame(mouseX-EGG_WIDTH/2, mouseY-EGG_HIGHT/2,
^
C:\programming 3\chapter10\EggApplet\EggApplet.java:52: cannot resolve symbol
symbol : variable EGG_HIGHT
location: class MouseClickListener
egg.setFrame(mouseX-EGG_WIDTH/2, mouseY-EGG_HIGHT/2,
^
C:\programming 3\chapter10\EggApplet\EggApplet.java:53: cannot resolve symbol
symbol : variable EGG_WIDTH
location: class MouseClickListener
EGG_WIDTH, EGG_HIGHT);
^
C:\programming 3\chapter10\EggApplet\EggApplet.java:53: cannot resolve symbol
symbol : variable EGG_HIGHT
location: class MouseClickListener
EGG_WIDTH, EGG_HIGHT);
^
C:\programming 3\chapter10\EggApplet\EggApplet.java:52: cannot resolve symbol
symbol : variable egg
location: class MouseClickListener
egg.setFrame(mouseX-EGG_WIDTH/2, mouseY-EGG_HIGHT/2,
^
C:\programming 3\chapter10\EggApplet\EggApplet.java:54: cannot resolve symbol
symbol : method repaint ()
location: class MouseClickListener
repaint();
^
6 errors
Process completed.

- -

event listener
inner class

instance variables
W
Class OuterClassName
{

accessSpecifier
{
methods
variables
}

class

InnerClassName

EJ FEJ F

1. // using inner class


2. import java.awt.*;
3. import java.applet.*;
4. import java.awt.event.*;
5. import java.awt.geom.*;
6. public class EggApplet extends Applet
7. {
8. public EggApplet()
9. {
10. egg = new Ellipse2D.Double(0,0,EGG_WIDTH, EGG_HIGHT);
11. // add mouse click listener
12. MouseClickListener listener = new MouseClickListener();
13. addMouseListener(listener);
14. }
15. public void paint(Graphics g)
16. {
17. Graphics2D g2 = (Graphics2D)g;
18. g2.draw(egg);
19. }
20. private Ellipse2D.Double egg;
21. private static final double EGG_WIDTH = 30;
22. private static final double EGG_HIGHT = 50;
23. // inner class definition
24.
25. private class MouseClickListener extends MouseAdapter
26. {
- -

27. public void mouseClicked(MouseEvent event)


28. {
29. int mouseX=event.getX();
30. int mouseY=event.getY();
31. // now move the ellipse to (mouseX, MouseY)
32. egg.setFrame(mouseX-EGG_WIDTH/2, mouseY-EGG_HIGHT/2,
33. EGG_WIDTH, EGG_HIGHT);
34. repaint();
35. }
36. }
37. }

EJ F

EJ F

- -

Frame Windows

applets

java applications

bordertitle barframe window

javax.swingJFrame

showsetTitle setSize

EJ Fwindow manager

main

JFrameEmptyFrame

frame

main EmptyFrame

1. import javax.swing.JFrame;
2. public class FrameTest1
3. { public static void main (String[] args)
4.
{ EmptyFrame frame = new EmptyFrame();
5.
frame.setTitle("frameTest");
6.
frame.show();
7.
}
8. }
9. class EmptyFrame extends JFrame
10. {
11. public EmptyFrame()
12. {
13. final int DEFAULT_FRAME_WIDTH =300;
14. final int DEFAULT_FRAME_HIGHT =300;
15. setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HIGHT);
16. }
17. }

EJ F

main

graphical programsconsole programs

new thread
main

threadmain
- -



System.exit(0)

mainK
public class FrameTest1
public static void main (String[] args)
{ EmptyFrame frame = new EmptyFrame();
frame.setTitle("frameTest");
frame.show();
System.exit(0); // Error

window events

dispose

K
K

K
EF K
K

window listener
WWindowListener

Public interface WindowListener


void windowOpend(windowEvent e);
void windowClosed(windowEvent e);
void windowActivated(windowEvent e);
void windowDeactivated(windowEvent e);
void windowIconified(windowEvent e);
void windowDeiconfied(windowEvent e);
- -

void windowClosing(windowEvent e);

JFrame

System.exit JFrame K


windowClosing

WindowListener WindowAdapter
WindowCloser

do

nothing

WindowAdapter

class WindowCloser extends WindowAdapter


public void windowClosing(WindowEvent event)
System.exit(0);

WindowCloser
EJ FaddWindowListener

import javax.swing.JFrame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class FrameTest2
{
public static void main (String[] args)
{ EmptyFrame frame = new EmptyFrame();
frame.setTitle("Close me!");
frame.show();
}
}
class EmptyFrame extends JFrame
{public EmptyFrame()
{
final int DEFAULT_FRAME_WIDTH =300;
final int DEFAULT_FRAME_HIGHT =300;
setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HIGHT);
WindowCloser listener = new WindowCloser();
addWindowListener(listener1);
- -

private class WindowCloser extends WindowAdapter


public void windowClosing(WindowEvent event)
System.exit(0);

EJ F

EJ F

- -


]<gj]<]<j<^]<]

K
W
W
K K
K

K K

K K

- -


W



K

components

objects
W


JLabel

JTextField

JButton
JCheckBox

JcomboBox

JList

JPanel

swing

Java 2 javax.swing

swing K1.2 platform


KPure Java Components
- -

AWT
GUI

button platform

KApple Macintosh Apple Macintosh

swing

K
swing
JLabel

KGUI JLabel
JLabel

K
WJLabel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// Demonstrating the JLabel class.


// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class LabelTest extends JFrame {
private JLabel label1, label2, label3;
// set up GUI
public LabelTest()
{
super( "Testing JLabel" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// JLabel constructor with a string argument

- -

24
25

label1 = new JLabel( "Label with text" );


label1.setToolTipText( "This is label1" );

26
27
28
29

container.add( label1 );
// JLabel constructor with string, Icon and
// alignment arguments

30
31
32

Icon bug = new ImageIcon( "bug1.gif" );


label2 = new JLabel( "Label with text and icon",
bug, SwingConstants.LEFT );

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

label2.setToolTipText( "This is label2" );


container.add( label2 );
// JLabel constructor no arguments
label3 = new JLabel();
label3.setText( "Label with icon and text at bottom" );
label3.setIcon( bug );
abel3.setHorizontalTextPosition(SwingConstants.CENTER );
label3.setVerticalTextPosition( SwingConstants.BOTTOM );
label3.setToolTipText( "This is label3" );
container.add( label3 );
setSize( 275, 170 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
LabelTest application = new LabelTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}

// end class LabelTest

- -

K JLabelEF
JLabelKEJ FLabelTest Constructor

KK?Label with text?

setToolTipText

Kcontent pane label1


Iconswing
KsetIcon

ImageIcon Icon interface

KGPEGGIF, PNGWimage formats

bug1.gif KImageIcon

folder ImageIcon
Kbug Icon ImageIconK

KIconImageIconIconImageIcon

JLabelJ JLabel

bug?Label with text and Icon?label


KLabel

KSwingConstants.LEFT
K label

setHorizontalAlignment label

Klabel2 tool tip KsetVerticalAlignment


label Kcontent pane

label3 setText
label3 setIcon KgetText label

J KgetIcon

setVerticalTextPosition setHorizontalTextPosition
- -

Klabel
K

label3 label3
Kcontent pane

- -

KJPasswordFieldJTextField
JPasswordField JTextField
JPasswordFieldK

enter K
event

Klistener

JPasswordField JTextField

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

// Demonstrating the JTextField class.


// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class TextFieldTest extends JFrame {
private JTextField textField1, textField2, textField3;
private JPasswordField passwordField;
// set up GUI
public TextFieldTest()
{
super( "Testing JTextField and JPasswordField" );
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// construct textfield with default sizing
textField1 = new JTextField( 10 );
container.add( textField1 );
// construct textfield with default text
textField2 = new JTextField( "Enter text here" );
container.add( textField2 );
// construct textfield with default text and
// 20 visible elements and no event handler
textField3 = new JTextField( "Uneditable text field", 20 );
textField3.setEditable( false );
container.add( textField3 );
// construct textfield with default text
passwordField = new JPasswordField( "Hidden text" );

- -

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

container.add( passwordField );
// register event handlers
TextFieldHandler handler = new TextFieldHandler();
textField1.addActionListener( handler );
textField2.addActionListener( handler );
textField3.addActionListener( handler );
passwordField.addActionListener( handler );
setSize( 325, 100 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
TextFieldTest application = new TextFieldTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// private inner class for event handling
private class TextFieldHandler implements ActionListener {
// process text field events
public void actionPerformed( ActionEvent event )
{
String string = "";
// user pressed Enter in JTextField textField1
if ( event.getSource() == textField1 )
string = "textField1: " + event.getActionCommand();
// user pressed Enter in JTextField textField2
else if ( event.getSource() == textField2 )
string = "textField2: " + event.getActionCommand();
// user pressed Enter in JTextField textField3
else if ( event.getSource() == textField3 )
string = "textField3: " + event.getActionCommand();
// user pressed Enter in JTextField passwordField
else if ( event.getSource() == passwordField ) {
JPasswordField pwd =
( JPasswordField ) event.getSource();
string = "passwordField: " +
new String( passwordField.getPassword() );
}
JOptionPane.showMessageDialog( null, string );
}
}

// end private inner class TextFieldHandler

- -

93
94

// end class TextFieldTest

JPasswordField JTextField J

KJ constructors

textField1 K textField1

Kcontent pane

?Enter Text Here?textField2

Kcontent paneK
- -

JTextField textField3
KEF,?Uneditable Text field?

false setEditable
Kcontent paneK

?Hidden Text? PasswordField passwordField


K
K asterisks

Kcontent pane

TextFieldHandler
ActionListener interface EJ F

K ActionListener TextFieldHandler
Handler TextFieldHandler

Kevent-listener

handler J
EenterF

KactionPerformed

actionPerformed

ActionEvent getSource

getActionCommand String string

TextField ActionEvent
JPasswordField getPassword
K

- -

JButtonEF

command buttons, check boxes, radio buttons


K

KCommand Buttons
K ActionEvent

KJButton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

// Creating JButtons.
// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class ButtonTest extends JFrame {
private JButton plainButton, fancyButton;
// set up GUI
public ButtonTest()
{
super( "Testing Buttons" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// create buttons
plainButton = new JButton( "Plain Button" );
container.add( plainButton );
Icon bug1 = new ImageIcon( "bug1.gif" );
Icon bug2 = new ImageIcon( "bug2.gif" );
fancyButton = new JButton( "Fancy Button", bug1 );
fancyButton.setRolloverIcon( bug2 );
container.add( fancyButton );
// create an instance of inner class ButtonHandler
// to use for button event handling
ButtonHandler handler = new ButtonHandler();
fancyButton.addActionListener( handler );
plainButton.addActionListener( handler );

- -

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

setSize( 275, 100 );


setVisible( true );
}
// execute application
public static void main( String args[] )
{
ButtonTest application = new ButtonTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// inner class for button event handling
private class ButtonHandler implements ActionListener {
// handle button event
public void actionPerformed( ActionEvent event )
{
JOptionPane.showMessageDialog( null,
"You pressed: " + event.getActionCommand() );
}
}
}

// end private inner class ButtonHandler

// end class ButtonTest

- -

JButtons
KJLabel
KEJ FButtonHandlerinner class

fancyButton plainButton W JButton


K

K?plain button? plainButton


Kcontent pane

JButton
rollover icon
ImageIcon J K

K rolover icon
K

Kbug1 ? Fancy Button? fancyButton


setRolloverIcon K

K
Kcontent pane

J ActionEvent EJTextField F JButton


J K listener

actionPerformedButtonHandler
K

- -

KJCheckBox
JCheckBox
E F JCheckBox

JTextField
K
K

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

// Creating Checkbox buttons.


// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class CheckBoxTest extends JFrame {
private JTextField field;
private JCheckBox bold, italic;
// set up GUI
public CheckBoxTest()
{
super( "JCheckBox Test" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up JTextField and set its font
field =
new JTextField( "Watch the font style change", 20 );
field.setFont( new Font( "Serif", Font.PLAIN, 14 ) );
container.add( field );
// create checkbox objects
bold = new JCheckBox( "Bold" );
container.add( bold );
italic = new JCheckBox( "Italic" );
container.add( italic );
// register listeners for JCheckBoxes
CheckBoxHandler handler = new CheckBoxHandler();
bold.addItemListener( handler );
italic.addItemListener( handler );
setSize( 275, 100 );
setVisible( true );

- -

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

}
// execute application
public static void main( String args[] )
{
CheckBoxTest application = new CheckBoxTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// private inner class for ItemListener event handling
private class CheckBoxHandler implements ItemListener {
private int valBold = Font.PLAIN;
private int valItalic = Font.PLAIN;
// respond to checkbox events
public void itemStateChanged( ItemEvent event )
{
// process bold checkbox events
if ( event.getSource() == bold )
if ( event.getStateChange() == ItemEvent.SELECTED )
valBold = Font.BOLD;
else
valBold = Font.PLAIN;
// process italic checkbox events
if ( event.getSource() == italic )
if ( event.getStateChange() == ItemEvent.SELECTED )
valItalic = Font.ITALIC;
else
valItalic = Font.PLAIN;
// set text field font
field.setFont(
new Font( "Serif", valBold + valItalic, 14 ) );
}
}
}

// end private inner class CheckBoxHandler

// end class CheckBoxTest

- -


K PLAINserif

KJ JCheckBox
KJCheckBox

ItemEvent
ItemListener

KitemStateChanged

bold itemStateChanged

K event.getSource() Kitalic

getStateChanged J if/else bold


W ItemEvent

EItemEvent.DESELECTED ItemEvent.SELECTEDF
valBold Font.BOLD

italic K Font.PLAIN
valItalic Font.ITALIC

valItalic valBoldK Font.PLAIN


KJTextFieldJ

- -

KJRadioButton
JCheckBox JRadioButton
radio buttons H Eselected and deselectedF

JRadioButtonsKdeselected

F ButtonGroup
Ejavax.swing

KJRadioButtons

JCheckBox

radio buttonsK
K

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

// Creating radio buttons using ButtonGroup and JRadioButton.


// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class RadioButtonTest extends JFrame {
private JTextField field;
private Font plainFont, boldFont, italicFont, boldItalicFont;
private JRadioButton plainButton, boldButton, italicButton,
boldItalicButton;
private ButtonGroup radioGroup;
// create GUI and fonts
public RadioButtonTest()
{
super( "RadioButton Test" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up JTextField
field =
new JTextField( "Watch the font style change", 25 );
container.add( field );

- -

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

// create radio buttons


plainButton = new JRadioButton( "Plain", true );
container.add( plainButton );
boldButton = new JRadioButton( "Bold", false);
container.add( boldButton );
italicButton = new JRadioButton( "Italic", false );
container.add( italicButton );
boldItalicButton = new JRadioButton(
"Bold/Italic", false );
container.add( boldItalicButton );
// register events for JRadioButtons
RadioButtonHandler handler = new RadioButtonHandler();
plainButton.addItemListener( handler );
boldButton.addItemListener( handler );
italicButton.addItemListener( handler );
boldItalicButton.addItemListener( handler );
// create logical relationship between JRadioButtons
radioGroup = new ButtonGroup();
radioGroup.add( plainButton );
radioGroup.add( boldButton );
radioGroup.add( italicButton );
radioGroup.add( boldItalicButton );
// create font objects
plainFont = new Font( "Serif", Font.PLAIN, 14 );
boldFont = new Font( "Serif", Font.BOLD, 14 );
italicFont = new Font( "Serif", Font.ITALIC, 14 );
boldItalicFont =
new Font( "Serif", Font.BOLD + Font.ITALIC, 14 );
field.setFont( plainFont );
setSize( 300, 100 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
RadioButtonTest application = new RadioButtonTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// private inner class to handle radio button events
private class RadioButtonHandler implements ItemListener {
// handle radio button events
public void itemStateChanged( ItemEvent event )
{

- -

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

// user clicked plainButton


if ( event.getSource() == plainButton )
field.setFont( plainFont );
// user clicked boldButton
else if ( event.getSource() == boldButton )
field.setFont( boldFont );
// user clicked italicButton
else if ( event.getSource() == italicButton )
field.setFont( italicFont );
// user clicked boldItalicButton
else if ( event.getSource() == boldItalicButton )
field.setFont( boldItalicFont );
}
}
}

// end private inner class RadioButtonHandler

// end class RadioButtonTest

JRadioButton J
content pane
ElabelF JRadioButton
KselecttrueK

ItemEvent JCheckBox JRadioButtons


) RadioButtonHandler J K

ItemEvent (J
KJRadioButtons

- -

radioGroup ButtonGroup
JRadioButton
ButtonGroup add J K
KradioGroupJRadioGroup

ItemListener EJ F RadioButtonHandler
KJRadioButton ItemEvent
radioGroup JRadioButton
EJ F itemStateChanged
KgetSource

JComboBox
K JComboBox

JRadioButtonJCheckBoxJComboBox
KKItemEvent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

// Using a JComboBox to select an image to display.


// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class ComboBoxTest extends JFrame {
private JComboBox imagesComboBox;
private JLabel label;
private String names[] =
{ "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif" };
private Icon icons[] = { new ImageIcon( names[ 0 ] ),
new ImageIcon( names[ 1 ] ), new ImageIcon( names[ 2 ] ),
new ImageIcon( names[ 3 ] ) };
// set up GUI
public ComboBoxTest()
{
super( "Testing JComboBox" );

- -

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

// get content pane and set its layout


Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up JComboBox and register its event handler
imagesComboBox = new JComboBox( names );
imagesComboBox.setMaximumRowCount( 3 );
imagesComboBox.addItemListener(
// anonymous inner class to handle JComboBox events
new ItemListener() {
// handle JComboBox event
public void itemStateChanged( ItemEvent event )
{
// determine whether check box selected
if ( event.getStateChange() == ItemEvent.SELECTED )
label.setIcon( icons[
imagesComboBox.getSelectedIndex() ] );
}
}

// end anonymous inner class

); // end call to addItemListener


container.add( imagesComboBox );
// set up JLabel to display ImageIcons
label = new JLabel( icons[ 0 ] );
container.add( label );
setSize( 350, 100 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
ComboBoxTest application = new ComboBoxTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}

// end class ComboBoxTest

- -

JComboBox


K JLabelIcon

iconsJ

names StringImageIcon
K

names JComboBox
EF K K
KEF

KK

JComboBoxsetMaximumRowCount
K

EF J K
KimagesComboBox ItemListener
EJ F itemStateChanged

- -

icons Klabel
KgetSelectedIndex

Layout Managers
Containers GUI Components

WKContainer

java.awt.Applet, FlowLayout

java.awt.Panel, javax.swing.Jpanel.
K

Content pane BorderLayout


WJApplet JFrame
K

K GridLayout
K

FlowLayout
1
2
3
4
5
6
7
8
9
10
11
12
13
14

// Demonstrating FlowLayout alignments.


// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class FlowLayoutDemo extends JFrame {
private JButton leftButton, centerButton, rightButton;
private Container container;
private FlowLayout layout;
- -

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

// set up GUI and register button listeners


public FlowLayoutDemo()
{
super( "FlowLayout Demo" );
layout = new FlowLayout();
// get content pane and set its layout
container = getContentPane();
container.setLayout( layout );
// set up leftButton and register listener
leftButton = new JButton( "Left" );
leftButton.addActionListener(
// anonymous inner class
new ActionListener() {
// process leftButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.LEFT );
// re-align attached components
layout.layoutContainer( container );
}
}

// end anonymous inner class

); // end call to addActionListener


container.add( leftButton );
// set up centerButton and register listener
centerButton = new JButton( "Center" );
centerButton.addActionListener(
// anonymous inner class
new ActionListener() {
// process centerButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.CENTER );
// re-align attached components
layout.layoutContainer( container );
}
}
);
container.add( centerButton );
- -

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

// set up rightButton and register listener


rightButton = new JButton( "Right" );
rightButton.addActionListener(
// anonymous inner class
new ActionListener() {
// process rightButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.RIGHT );
// re-align attached components
layout.layoutContainer( container );
}
}
);
container.add( rightButton );
setSize( 300, 75 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
FlowLayoutDemo application = new FlowLayoutDemo();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}

// end class FlowLayoutDemo

- -

FlowLayout JButtons
Left

Center Right
K
K

Container Layout
setLayout
KLayout.setAlignment

BorderLayout

W Container

K K

K container
K K
K

K
WBorderLayout
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

// Demonstrating BorderLayout.
// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class BorderLayoutDemo extends JFrame
implements ActionListener {
private JButton buttons[];
private String names[] = { "Hide North", "Hide South",
"Hide East", "Hide West", "Hide Center" };
- -

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

private BorderLayout layout;


// set up GUI and event handling
public BorderLayoutDemo()
{
super( "BorderLayout Demo" );
layout = new BorderLayout( 5, 5 );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( layout );
// instantiate button objects
buttons = new JButton[ names.length ];
for ( int count = 0; count < names.length; count++ ) {
buttons[ count ] = new JButton( names[ count ] );
buttons[ count ].addActionListener( this );
}
// place buttons in BorderLayout; order not important
container.add( buttons[ 0 ], BorderLayout.NORTH );
container.add( buttons[ 1 ], BorderLayout.SOUTH );
container.add( buttons[ 2 ], BorderLayout.EAST );
container.add( buttons[ 3 ], BorderLayout.WEST );
container.add( buttons[ 4 ], BorderLayout.CENTER );
setSize( 300, 200 );
setVisible( true );
}
// handle button events
public void actionPerformed( ActionEvent event )
{
for ( int count = 0; count < buttons.length; count++ )
if ( event.getSource() == buttons[ count ] )
buttons[ count ].setVisible( false );
else
buttons[ count ].setVisible( true );
// re-layout the content pane
layout.layoutContainer( getContentPane() );
}
// execute application
public static void main( String args[] )
- -

65
66
67
68
69
70
71
72

{
BorderLayoutDemo application = new BorderLayoutDemo();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}

// end class BorderLayoutDemo

GridLayout
Grid container

KGridLayoutK
1
2
3
4
5
6

// Demonstrating GridLayout.
// Java core packages
import java.awt.*;
import java.awt.event.*;
- -

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

// Java extension packages


import javax.swing.*;
public class GridLayoutDemo extends JFrame
implements ActionListener {
private JButton buttons[];
private String names[] =
{ "one", "two", "three", "four", "five", "six" };
private boolean toggle = true;
private Container container;
private GridLayout grid1, grid2;
// set up GUI
public GridLayoutDemo()
{
super( "GridLayout Demo" );
// set up layouts
grid1 = new GridLayout( 2, 3, 5, 5 );
grid2 = new GridLayout( 3, 2 );
// get content pane and set its layout
container = getContentPane();
container.setLayout( grid1 );
// create and add buttons
buttons = new JButton[ names.length ];
for( int count = 0; count < names.length; count++ ) {
buttons[ count ] = new JButton( names[ count ] );
buttons[ count ].addActionListener( this );
container.add( buttons[ count ] );
}
setSize( 300, 150 );
setVisible( true );
}
// handle button events by toggling between layouts
public void actionPerformed( ActionEvent event )
{
if ( toggle )
container.setLayout( grid2 );
else
container.setLayout( grid1 );
toggle = !toggle;
// set toggle to opposite value
container.validate();
}
// execute application
public static void main( String args[] )
{
- -

62
63
64
65
66
67
68

GridLayoutDemo application = new GridLayoutDemo();


application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}

// end class GridLayoutDemo

- -

WE

a) buttonName =JButton(Caption);
b) JLabel aLabel, JLabel;
c) TextField = new JTextField(50, Default Text);
d) Container c = getContentPane();
setLayout (new BorderLayout());
button1 = newJButton (North Star);
button2 = newJButton (South Pole);
c.add(button1);
c.add(button2);

E
OK
X: 8

Snap to Grid

Cancel

Show Grid
Y: 8

Help

E
K

EJTextFieldJButtons F

7
4
1
0

8
5
2
.

9
6
3
=
- -

/
*
+


]<gj]<]<j<^]<]

KK
W

W
K
K

K
K

- -

variable scope

K
K


K
W

Sequential Access Files Ka

Random Access Files Kb

W Text files Ki
Characters
W Binary files Kii
Bytes

- -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20


K
import java.io.*;
//Class Definition
class ReadTextFilel
{
public static void main (String args[]) throws IOException
{
String fileName = c:/temp/toRead.txt;
String line;
BufferedReader in = new BufferedReader (new
FileReader (filename) );
line = in.readLine();
while (line != null) // continue until end of file;
{
System.out.prinln(line);
Line = in.readLine();
}
in.close();
}
}

java.io package W
K

ReadTextFile1 W J

? main
main ?FileNotFound
Kthrows IOException

- -

W
fileName

String fileName = c:/temp/toRead.txt;

line W
K

BufferedReader in WJ
fileName

KFileReader
BufferedReader in = new BufferedReader (new FileReader (fileName) );

in W
K
line = in.readln ();
linein
K
W

EwhileF
Knull
while (line != null)

WJ
{

System.out.prinln(line);
line = in.readLine();

}
- -

Kin

in.close();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

import java.io.*;
class ReadWithTokenizer
{
public static void main (String args[]) throws IOException
{
String fileName = c:/temp/toRead.txt;
BufferedReader in = new BufferedReader (
new FileReader (fileName) );
StreamTokenizer reader = new StreamTokenizer(in);
reader.nextToken();
While (reader.ttype != StreamTokenizer.TT_EOF)
//continue until end of file
{
String word = reader.sval;
System.out.println (word);
Reader.nextToken();
}
in.close();
}
}

- -

java.io package W

ReadwithTokenizerWJ
Kmain

W
KfileName
String fileName = c:/temp/toRead.txt;

BufferedReader in WJ

fileName

KFileReader
BufferedReader in = new BufferedReader (new FileReader (fileName) );
W
Tokens
readerStreamTokenizer
StreamTokenizer reader = new StreamTokenizer(in);

nextToken()W

KreaderStreamTokenizer
reader.nextToken();
W
abstracted

StreamTokenizerTT_EOF
W

while (reader.ttype != StreamTokenizer.TT_EOF)


- -

reader.nextTokenW

reader

Ksvalnval
String word = reader.sval;
W
System.out.println (word);

W
K
reader.nextToken ();
WW
in.close ();

While (reader.nextToken() != StreamTokenizer.TT_EOF)


//continue until end of file
{
if (reader.ttype == StreamTokenizer.TT_WORD)
System.out.println( A word: + reader.sval);
Else if (reader.ttype == StreamTokenizer.TT_NUMBER)
System.out.println( A number: + reader.nal);
}
StreamTokenizer
TT_NUMBERStringTT_WORD

readerK

WKttype
if (reader.ttype == StreamTokenizer.TT_WORD)
- -

WK

1
2
3
5
6
7
8
9
10
11
12
13
14
15
16

import java.io.*;
public class WriteTextFile
{
public static void main (String args[] throws IOExcepetion
{
String filename = reaper.txt
PrintWriter print = new PrintWriter( new BufferedWriter (
new FileWriter (filename)));
print.println(College of Telecommunication and Information);
print.println(Computer Department);
print.println(Programming);
print.println(Java 3);
print.close();
}
}


KPrintWriterprint

println print
K

- -

KK

1
2 import java.io.*
3 class ReadWrite
4 {
5
public static void main(String[] args) throws IOException
6
{
7
String[] line = new String[10];
8
load (line);
9
10
/* --------m ----------------*/
11
12
commit (line);
13
}
14
//
15
Public static void load (String[] line) throws IOException
16
17 {
String filename =c:/temp/toRead.txt;
18
BufferedReader in = new BufferedReader (new
19
FileReader(filename));
20
Line[0] = in.readln();
21
int i = 0;
22
while (line[i] != null) //
23
24
{
25
System.out.println(line[i]);
26
i++;
27
Line[i] = in.readln();
28
}
29
in.close();
30
}
- -

31 //
32
33
public static void commit (String[] line) throws IOException
34 {
35
String filename =c:/temp/toRead.txt;
36
BufferedWriter print = new BufferedWriter (new
37
38 FileWriter(filename));
39
int i = 0;
40
while (line[i] != null) //
41
{
42
print.println(line[i]);
43
i++;
44
}
45
print.close();
46
}
47
48 }

- -

E
________________________________________________________

________________________________________________________

________________________________________________________

WE

_______________________________________K

_______________________________________K

WEE

_______________________________________K

_______________________________________K

E
EADTFK


K
- -


]<gj]<]<j<^]<]

K
W
W
K
K

- -

Random- Sequential files W

access files
K

K
Relational Database

Structured systems
Query Language (SQL)

K
K SQL

Microsoft Access, Sybase, Oracle, Informix, Microsoft SQL W

Microsoft KServer
KSQL OracleAccess

Books

KOracleAccess

ISBN W
W

- -

Primary F

AutherID

FirstName

LastName

YearBorn

EKey

W
AutherId
1
2
3

FirstName
Ali
Salem
Abdullah

LastName
Suliman
Khalid
Amer

YearBorn
1960
1975
1963

EF


PublisherID

PublisherName
W

PublisherID
1
2

PublisherName
Prentice Hall
Prentice Hall PTR

ISBN

ISBN

ISBN

AutherID

- -

WISBN
ISBN
0-13-010671-2
0-13-015231-2
0-14-044131-7
0-11-028271-4
0-10-070471-1

AutherID
1
2
1
3
2


ISBN

ISBN

Title
EditionNo

YearPublished

PublisherId

ISBN

Title

0-13-010671-2
0-13-015231-2
0-14-044131-7
0-11-028271-4
0-10-070471-1

C How to program
C++ How to Program
Java How to program
Oracle PL/SQL
Internet Programming

:
Edition YearPublisherID
No
Published
2
1994
1
3
1997
1
2
1992
1
2
1999
2
1
1998
1

Access Relational database Management Systems


KOracle

- -

KW

SELECT * from Author


ORDER BY FirstName

KJTable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

// Fig. 18.24: TableDisplay.java


// This program displays the contents of the Authors table
// in the Books database.
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TableDisplay extends JFrame {
private Connection connection;
private JTable table;
public TableDisplay()
{
// The URL specifying the Books database to which
// this program connects using JDBC to connect to a
// Microsoft ODBC database.
String url = "jdbc:odbc:Books";
String username = "anonymous";
String password = "guest";
// Load the driver to allow connection to the database
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
connection = DriverManager.getConnection(
- -

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

url, username, password );


}
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"Failed to load JDBC/ODBC driver." );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to connect" );
sqlex.printStackTrace();
}
getTable();
setSize( 450, 150 );
show();
}
private void getTable()
{
Statement statement;
ResultSet resultSet;
try {
String query = "SELECT * FROM Author";
statement = connection.createStatement();
resultSet = statement.executeQuery( query );
displayResultSet( resultSet );
statement.close();
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private void displayResultSet( ResultSet rs )
throws SQLException
{
// position to first record
- -

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

boolean moreRecords = rs.next();


// If there are no records, display a message
if ( ! moreRecords ) {
JOptionPane.showMessageDialog( this,
"ResultSet contained no records" );
setTitle( "No records to display" );
return;
}
setTitle( "Authors table from Books" );
Vector columnHeads = new Vector();
Vector rows = new Vector();
try {
// get column heads
ResultSetMetaData rsmd = rs.getMetaData();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );
// get row data
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );
// display table with ResultSet contents
table = new JTable( rows, columnHeads );
JScrollPane scroller = new JScrollPane( table );
getContentPane().add(
scroller, BorderLayout.CENTER );
validate();
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private Vector getNextRow( ResultSet rs,
ResultSetMetaData rsmd )
throws SQLException
- -

112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153

{
Vector currentRow = new Vector();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
switch( rsmd.getColumnType( i ) ) {
case Types.VARCHAR:
currentRow.addElement( rs.getString( i ) );
break;
case Types.INTEGER:
currentRow.addElement(
new Long( rs.getLong( i ) ) );
break;
default:
System.out.println( "Type was: " +
rsmd.getColumnTypeName( i ) );
}
return currentRow;
}
public void shutDown()
{
try {
connection.close();
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to disconnect" );
sqlex.printStackTrace();
}
}
public static void main( String args[] )
{
final TableDisplay app = new TableDisplay();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
app.shutDown();
System.exit( 0 );
}
- -

154
155
156

);
}
}


import java.sql.*
Classes java.sql

K
private Connection connection;
Connection Object

SQL
KTransactions

TableDisplay Class Constructor


KgetTable
String url = "jdbc:odbc:Books";
String username = "anonymous";
String password = "guest";

URL W
odbc jdbc
password username K

ODBC

jdbc.odbc.jdbcodbcDriver Driver
K
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
class forName

Database driver
- -

try block java.lang.classNotFound


Kcatch block
connection = DriverManager.getConnection(url, username, password );
DriverManager getConnection
K URL
java.sql.sqlException
KgetTable

displayResultSet gettable
KJTable

Statement statement

Ejava.sql F Statement SQL


SQL

ResultSet resultSet

resultSet
KSQL

statement = connection.createStatement();
statement CreateStatement


resultSet = statement.executeQuery(query);
executeQuery

displayResult resultSetK
K

displayResultSet

boolean moreRecords = rs.next();

moreRecords

next ResultSet

BooleannextK

ETrueF
- -

Vector KEFalseF
ResultSet

KResultSetJTableResultSet
W

ResultSetMetaData rsmd = rs.getMetaData();


ResultSet

MetaData

ResultSetMetaData Krsmd
getColumnCount ResultSet

getColumnName
W

do
rows.addElement (getNextRow (rs, rsmd ) );
while (rs.next() );
getNextRow ResultSet


ResultSet rs.next()
KResultSet

JTable

ResultSetMetaData ResultSet E F getNextRow


KResultSet

Kcloseshutdown

- -

KODBCBooks.mdb??

ODBC

KODBC
W

WindowsControl Panel

KODBC Data Sources


Add User DSN

KMicrosoft Access DriverAccess


K

- -

ODBC Microsoft Access

Data JDBC

KSource Name

- -

DescriptionEF
Select K

EBooks.mdbF K
OK K

Advanced K
anonymous K
guest K

OK K
ODBC Microsoft Access SetupOKK K

ODBC Data Source AdministratorOKK K

- -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

// DisplayQueryResults.java
// This program displays the ResultSet returned by a
// query on the Books database.
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class DisplayQueryResults extends JFrame {
// java.sql types needed for database processing
private Connection connection;
private Statement statement;
private ResultSet resultSet;
private ResultSetMetaData rsMetaData;
- -

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

// javax.swing types needed for GUI


private JTable table;
private JTextArea inputQuery;
private JButton submitQuery;
public DisplayQueryResults()
{
super( "Enter Query. Click Submit to See Results." );
// The URL specifying the Books database to which
// this program connects using JDBC to connect to a
// Microsoft ODBC database.
String url = "jdbc:odbc:test";
String username = "moh";
String password = "moh";
// Load the driver to allow connection to the database
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
connection = DriverManager.getConnection(
url, username, password );
}
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"Failed to load JDBC/ODBC driver." );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to connect" );
sqlex.printStackTrace();
System.exit( 1 ); // terminate program
}
// If connected to database, set up GUI
inputQuery =
new JTextArea( "SELECT * FROM Authors", 4, 30 );
submitQuery = new JButton( "Submit query" );
submitQuery.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
- -

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

{
getTable();
}
}
);
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
topPanel.add( new JScrollPane( inputQuery),
BorderLayout.CENTER );
topPanel.add( submitQuery, BorderLayout.SOUTH );
table = new JTable( 4, 4 );
Container c = getContentPane();
c.setLayout( new BorderLayout() );
c.add( topPanel, BorderLayout.NORTH );
c.add( table, BorderLayout.CENTER );
getTable();
setSize( 500, 500 );
show();
}
private void getTable()
{
try {
String query = inputQuery.getText();
statement = connection.createStatement();
resultSet = statement.executeQuery( query );
displayResultSet( resultSet );
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private void displayResultSet( ResultSet rs )
throws SQLException
{
- -

101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

// position to first record


boolean moreRecords = rs.next();
// If there are no records, display a message
if ( ! moreRecords ) {
JOptionPane.showMessageDialog( this,
"ResultSet contained no records" );
setTitle( "No records to display" );
return;
}
Vector columnHeads = new Vector();
Vector rows = new Vector();
try {
// get column heads
ResultSetMetaData rsmd = rs.getMetaData();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );
// get row data
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );
// display table with ResultSet contents
table = new JTable( rows, columnHeads );
JScrollPane scroller = new JScrollPane( table );
Container c = getContentPane();
c.remove( 1 );
c.add( scroller, BorderLayout.CENTER );
c.validate();
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private Vector getNextRow( ResultSet rs,
ResultSetMetaData rsmd )
throws SQLException
- -

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
171
172
173
174
175
176
177
178
179
180
181
182
183

{
Vector currentRow = new Vector();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
switch( rsmd.getColumnType( i ) ) {
case Types.VARCHAR:
case Types.LONGVARCHAR:
currentRow.addElement( rs.getString( i ) );
break;
case Types.INTEGER:
currentRow.addElement(
new Long( rs.getLong( i ) ) );
break;
default:
System.out.println( "Type was: " +
rsmd.getColumnTypeName( i ) );
}
return currentRow;
}
public void shutDown()
{
try {
connection.close();
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to disconnect" );
sqlex.printStackTrace();
}
}
public static void main( String args[] )
{
final DisplayQueryResults app =
new DisplayQueryResults();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
app.shutDown();
- -

184
185
186
187
188

System.exit( 0 );
}
}
);
}}

- -

W E

___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________

K E

K

K K
K K

- -


Java How to Program, Deitel and Deitel, Fourth Edition

- -

.........................................................................................

.............................................................................

....................................................................................................................

....................................................................................................................

.............................................................................

....................................................................................................................

....................................................................................................................

..................................................................................................

....................................................................................................................

............................................................................................

.................................................................................................................

....................................................................................................................

........................................................................................................

........................................................................................................

......................................................................................

...........................................................................................................

..................................................................................................

...........................................................................................................

...................................................................................
......

.........................................................................................................................................

.........................................................................................

swing

.........................................................................................

JLabel

.............................

........................................................................................

JButton

.........................................................................................

JComboBox

................................................................................

JPassWordFieldJTextField

JRadioButton

............................................................................................

JComboBox

............................................................................................

.....................................................................................................

.............................................................................................................................

.................................................................................................................

.................................................................................................................

.................................................................................................................

...................................................................................

..............................................................................................................

..............................................................................................................

..........................

..............................................................................................................

.......................................................................

ODBC


EF
GOTEVOT appreciates the financial support provided by BAE SYSTEMS

Potrebbero piacerti anche