Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
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
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
--
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
class
subclass
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.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)
this
deposit(amount)
deposit(double
amount)CheckingAccount
super
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
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
*/
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
- -
]<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
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
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
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
(-)
- -
EJ F
finally
catch
try
catch
K
EJ F
try
ArithmeticExceptioncatch
KArrayIndexOutOfBoundsException
finally
W
Ktry
( -)
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();
}
- -
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
- -
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
eventsevent
mouse event
W event listener
Keyboard events
event source
event listener
Kevent source
W
an applet
component
The event source J
the applet
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.
- -
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
WindowListener
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
- -
event listener
inner class
instance variables
W
Class OuterClassName
{
accessSpecifier
{
methods
variables
}
class
InnerClassName
EJ FEJ F
EJ F
EJ F
- -
Frame Windows
applets
java applications
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
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
JFrame
System.exit JFrame K
windowClosing
WindowListener WindowAdapter
WindowCloser
do
nothing
WindowAdapter
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);
- -
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
AWT
GUI
button platform
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
- -
24
25
26
27
28
29
container.add( label1 );
// JLabel constructor with string, Icon and
// alignment arguments
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
- -
K JLabelEF
JLabelKEJ FLabelTest Constructor
setToolTipText
bug1.gif KImageIcon
folder ImageIcon
Kbug Icon ImageIconK
KIconImageIconIconImageIcon
JLabelJ JLabel
KSwingConstants.LEFT
K label
setHorizontalAlignment label
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
- -
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 );
}
}
- -
93
94
JPasswordField JTextField J
KJ constructors
textField1 K textField1
Kcontent pane
Kcontent paneK
- -
JTextField textField3
KEF,?Uneditable Text field?
false setEditable
Kcontent paneK
Kcontent pane
TextFieldHandler
ActionListener interface EJ F
K ActionListener TextFieldHandler
Handler TextFieldHandler
Kevent-listener
handler J
EenterF
KactionPerformed
actionPerformed
ActionEvent getSource
TextField ActionEvent
JPasswordField getPassword
K
- -
JButtonEF
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
- -
JButtons
KJLabel
KEJ FButtonHandlerinner class
JButton
rollover icon
ImageIcon J K
K rolover icon
K
K
Kcontent pane
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
- -
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 ) );
}
}
}
- -
K PLAINserif
KJ JCheckBox
KJCheckBox
ItemEvent
ItemListener
KitemStateChanged
bold itemStateChanged
K event.getSource() Kitalic
EItemEvent.DESELECTED ItemEvent.SELECTEDF
valBold Font.BOLD
italic K Font.PLAIN
valItalic Font.ITALIC
- -
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
- -
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
- -
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
JRadioButton J
content pane
ElabelF JRadioButton
KselecttrueK
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
- -
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
- -
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
K GridLayout
K
FlowLayout
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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
- -
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
65
66
67
68
69
70
71
72
{
BorderLayoutDemo application = new BorderLayoutDemo();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}
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
62
63
64
65
66
67
68
- -
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
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
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
reader.nextTokenW
reader
Ksvalnval
String word = reader.sval;
W
System.out.println (word);
W
K
reader.nextToken ();
WW
in.close ();
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
- -
access files
K
K
Relational Database
Structured systems
Query Language (SQL)
K
K SQL
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
- -
KW
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
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
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
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
URL W
odbc jdbc
password username K
ODBC
jdbc.odbc.jdbcodbcDriver Driver
K
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
class forName
Database driver
- -
displayResultSet gettable
KJTable
Statement statement
ResultSet resultSet
resultSet
KSQL
statement = connection.createStatement();
statement CreateStatement
resultSet = statement.executeQuery(query);
executeQuery
displayResult resultSetK
K
displayResultSet
moreRecords
next ResultSet
BooleannextK
ETrueF
- -
Vector KEFalseF
ResultSet
KResultSetJTableResultSet
W
MetaData
ResultSetMetaData Krsmd
getColumnCount ResultSet
getColumnName
W
do
rows.addElement (getNextRow (rs, rsmd ) );
while (rs.next() );
getNextRow ResultSet
ResultSet rs.next()
KResultSet
JTable
Kcloseshutdown
- -
KODBCBooks.mdb??
ODBC
KODBC
W
WindowsControl Panel
- -
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
- -
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
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
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