software engineering methods winter 2002-3

80
Software Engineering Methods Winter 2002-3 – Lecture: Prof. Shmuel Katz. Teaching Assistants Adam Carmi Zvika Gutterman – Grader Berliner Yaniv

Upload: yepa

Post on 15-Jan-2016

40 views

Category:

Documents


0 download

DESCRIPTION

Software Engineering Methods Winter 2002-3. Lecture: Prof. Shmuel Katz. Teaching Assistants Adam Carmi Zvika Gutterman Grader Berliner Yaniv. Course Administration. Follow the web page: www.cs.technion.ac.il/~cs234321 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Software Engineering Methods Winter 2002-3

Software Engineering MethodsWinter 2002-3

– Lecture:Prof. Shmuel Katz.

– Teaching Assistants

Adam Carmi

Zvika Gutterman

– GraderBerliner Yaniv

Page 2: Software Engineering Methods Winter 2002-3

Course Administration

• Follow the web page: www.cs.technion.ac.il/~cs234321

• Email: Use only the course e-mail! [email protected]

• Grade:– test > 50 ? 0.6 HW + 0.4 Test : Test

• Tests– Moed A - 07/Feb/2003– Moed B - 07/Mar/2003

Page 3: Software Engineering Methods Winter 2002-3

Time Table

• Lecture: Sundays, 10:30-12:30 at Taub 2.

• Group 11:Sundays, 14:30-15:30 at Taub 6.

• Group 12:Tuesdays, 10:30-11:30 at Taub 3.

• Group 13:Wednesdays, 14:30-15:30 at Taub 3.

• Group 14:Cancelled !

Page 4: Software Engineering Methods Winter 2002-3

Software engineering methods

Written By: Zvi Avidor

Additions: Adam Carmi

Zvi Gutterman

for the c++ programmer

Thanks to Oleg Pozniansky for his comments

Page 5: Software Engineering Methods Winter 2002-3

Reading

• BooksIn Amazon: – 1662 Entries with Java … (03/2002)– 1918 Entries with Java … (10/2002)

• Course Web Site.

• Java.sun.com

Page 6: Software Engineering Methods Winter 2002-3

Why Java ?

• Object Oriented

• New (1995)

• Easy to learn

• Many additional features integrated:

Security, JDBC, GUI, MT, Communication,

Documentation, … and lots more!

Page 7: Software Engineering Methods Winter 2002-3

JVM

• JVM stands for

Java Virtual Machine

• Unlike most other languages, Java “executables” are executed on a CPU that does not exist.

Page 8: Software Engineering Methods Winter 2002-3

JVM - Cont.C++

file1.cpp

file2.cpp

file1.obj

file2.obj

compilation

main.exe

link

CPU1

CPU2 main.exefile1.obj

file2.obj

execute

Imm

ediate

sources

Page 9: Software Engineering Methods Winter 2002-3

JVM - Cont.Java

file1.java

file2.java

main.java

sources

compilation

file1.class

file2.class

main.class

Executeon CPU1

Executeon CPU1

java main

java main

Page 10: Software Engineering Methods Winter 2002-3

Primitive types

• int 4 bytes• short 2 bytes• long 8 bytes• byte 1 byte• float 4 bytes• double 8 bytes• char Unicode encoding (2 bytes) • boolean {true,false}

Behaviors is exactly as in C++

Page 11: Software Engineering Methods Winter 2002-3

• Constants

37 integer

37.2 float

42F float

0754 integer (octal)

0xfe integer (hexadecimal)

Primitive types - cont.

Page 12: Software Engineering Methods Winter 2002-3

Wrappers

Java provides Objects which wrap primitive types and supply methods.

Example:

Integer n = new Integer(“4”);int m = n.intValue();

Read more about Integer in JDK Documentation

Page 13: Software Engineering Methods Winter 2002-3

Hello World

class Hello {public static void main(String[] args) {

System.out.println(“Hello World !!!”); }

}

Hello.java

C:\javac Hello.java

C:\java Hello

( compilation creates Hello.class )

(Execution on the local JVM)

Page 14: Software Engineering Methods Winter 2002-3

More sophisticatedclass Kyle {

private boolean kennyIsAlive_;public Kyle() { kennyIsAlive_ = true; }public Kyle(Kyle aKyle) {

kennyIsAlive_ = aKyle.kennyIsAlive_;}public String theyKilledKenny() {

if (kennyIsAlive_) {kennyIsAlive_ = false;return “You bastards !!!”;

} else {return “?”;

}}public static void main(String[] args) {

Kyle k = new Kyle();String s = k.theyKilledKenny();System.out.println(“Kyle: “ + s);

}}

Default C’tor

Copy C’tor

Page 15: Software Engineering Methods Winter 2002-3

Results

javac Kyle.java ( to compile )

java Kyle ( to execute )

Kyle: You bastards !!!

Page 16: Software Engineering Methods Winter 2002-3

Case Sensitive

• Case sensitivity:– String is not the same as string– MAIN is not the same as main

• Java keywords are all lower case– e.g. public class static void

Page 17: Software Engineering Methods Winter 2002-3

Naming Conventions

• Methods, variables and objects start with a leading lowercase letter :

next, push(), index, etc.

• Classes starts with a leading upper-case letter :

String, StringBuffer, Vector, Calculator, etc.

Page 18: Software Engineering Methods Winter 2002-3

Naming Conventions (2)

• Constants (final) are all upper-case : DEBUG, MAX_SCROLL_X, CAPACITY.

E.g.

final double PI = 3.1415926;

• Word separation in identifiers is done by capitalization, except for constants where underscore is used.

Page 19: Software Engineering Methods Winter 2002-3

Comments

• C++ Like:// bla bla ../* this is a bla bla */

• And JavaDoc Comments:/** comment */

Page 20: Software Engineering Methods Winter 2002-3

Flow control

It is like c/c++:

if/else

do/while

for

switch

If(x==4) { // act1} else { // act2}

int i=5;do { // act1 i--;} while(i!=0);

int j;for(int i=0;i<=9;i++) { j+=i;}

char c=IN.getChar();switch(c) { case ‘a’: case ‘b’: // act1 break; default: // act2}

Page 21: Software Engineering Methods Winter 2002-3

Everything is a referenceto an Object

Every variable in Java (almost…) is a reference/pointer.

C++

5

9

a

b

MyObject *x ( not initialized !!!)

Java

MyObject x

a=b

MyObject x(5)

Since we’re handling pointers, the following is obvious :

5

9

a

b

N/A

Page 22: Software Engineering Methods Winter 2002-3

Garbage Collection• In C++ we use the ‘delete’ operator to release

allocated memory. ( Not using it means : memory leaks )

• In Java there is no ‘delete’ and there are no memory leaks ! How could this be ?– answer : reference count

6a

1

6a

2b{

b=a}

Page 23: Software Engineering Methods Winter 2002-3

Garbage collection - cont.

6a

2b

{ Number b=a;}

6

1

Out ofscope

6

0

Garbage Collector

Page 24: Software Engineering Methods Winter 2002-3

Arrays

• Array is an object

• Array size is fixed

Animal[] arr; // nothing yet …

arr = new Animal[4]; // only array of pointers

for(int i=0 ; i < arr.length ; i++) {arr[i] = new Animal();

// now we have a complete array

Page 25: Software Engineering Methods Winter 2002-3

Arrays - Multidimensional

• In C++ Animal arr[2][2]

Is:

• In Java

What is the type of the object here ?

Animal[][] arr= new Animal[2][2]

Page 26: Software Engineering Methods Winter 2002-3

String is an Object

• Constant strings as in C, does not exist.

• The function call foo(“Hello”) creates a String object, containing “Hello”, and passes reference to it to foo.

• There is no point in writing :

• The String object is a constant. It can’t be changed using a reference to it.

String s = new String(“Hello”);

Page 27: Software Engineering Methods Winter 2002-3

Static• Member data - Same data is used for all the

instances (objects) of some Class.

Class A { public static int x_ = 1;};

A a = new A();A b = new A();System.out.println(b.x_);a.x_ = 5;System.out.println(b.x_);A.x_ = 10;System.out.println(b.x_);

Assignment performed on the first access to theClass.Only one instance of ‘x’exists in memory

Output:

1510

Page 28: Software Engineering Methods Winter 2002-3

Static – cont.• Member function

– Static member function can access only static members

– Static member function can be called without an instance.

Class TeaPot {private static int numOfTP = 0;private Color myColor_;public TeaPot(Color c) {

myColor_ = c; numOfTP++;

}public static int howManyTeaPots()

{ return numOfTP; }

// error :public static Color getColor()

{ return myColor_; }}

Example

Page 29: Software Engineering Methods Winter 2002-3

Static - cont.

Usage:

TeaPot tp1 = new TeaPot(Color.RED);

TeaPot tp2 = new TeaPot(Color.GREEN);

System.out.println(“We have “ + TeaPot.howManyTeaPots()+ “Tea Pots”);

Page 30: Software Engineering Methods Winter 2002-3

Packages

• Java code has hierarchical structure.• The environment variable CLASSPATH contains

the directory names of the roots.• Every Object belongs to a package ( ‘package’

keyword)• Object’s full name contains the full name of the

package containing it.

Page 31: Software Engineering Methods Winter 2002-3

Packages – After compilation

package P1;public class C1 {}

package P2;public class C2 {}

package P1;class C3 {}

package P3.A.B;class C1 {}

F:\MyClasses\P1\C1.class F:\MyClasses\P2\C2.class

F:\MyOtherClasses\P1\C3.class F:\MyClasses\P3\A\B\C1.class

When compiling the -d option defines the target root

Directories are automatically

created

Page 32: Software Engineering Methods Winter 2002-3

Packages - Example, cont.

F:\MyClasses\P1\C1.class

F:\MyClasses\P2\C2.class

F:\MyOtherClasses\P1\C1.class

F:\MyClasses\P3\A\B\C1.class

Assume that CLASSPATH=F:\MyClasses;F:\MyOtherClasses

C1 c=new C1(); Error !!

P1.C1 c=new P1.C1();

import P1.*;C1 c=new C1();

import P3.A.B.C1;import P1.*;C1 c=new C1();

Page 33: Software Engineering Methods Winter 2002-3

Access control public class

– ‘new’ is allowed from other packages ( default: only from the same package (note: not necessarily

from the same file) )

package P1;public class C1 {}class C2 {}

package P2;class C3 {}

package P3;import P1.*;import P2.*;

public class DO { void foo() {

C1 c1 = new C1(); C2 c2 = new C2(); // ERRORC3 c3 = new C3(); // ERROR

}}

Page 34: Software Engineering Methods Winter 2002-3

Access Control - cont

• public member (function/data) – Can be called/modified from outside.

• Protected– Can called/modified from derived classes

• private– Can called/modified only from the current class

• Default ( if no access modifier stated )– Usually referred to as “Friendly”.

– Can called/modified/instantiated from the same package.

Page 35: Software Engineering Methods Winter 2002-3

Access Control - cont.

Base

Derived

Package P1

Package P2

SomeClass

prot

ecte

d public

SomeClass2

private

Friendl

yInheritance

Usage

Page 36: Software Engineering Methods Winter 2002-3

Inheritance

Base

Derived

class Base { Base(){} Base(int i) {} protected void foo() {…}}

class Derived extends Base { Derived() {} protected void foo() {…} Derived(int i) { super(i); … super.foo(); }}

As opposed to C++, it is possible to inherit only from ONE class.Pros avoids many potential problems and bugs.

Cons might cause code replication

Page 37: Software Engineering Methods Winter 2002-3

Polymorphism

• Inheritance creates an “is a” relation:

For example, if B inherits from A, than we say that “B is also an A”.

Implications are:– access rights (Java forbids reducing of access rights)

- derived class can receive all the messages that the base class can.

– behavior

– precondition and postcondition

Page 38: Software Engineering Methods Winter 2002-3

Inheritance (2)• In Java, all methods are virtual :

class Base { void foo() { System.out.println(“Base”); }}class Derived extends Base { void foo() { System.out.println(“Derived”); }}public class Test { public static void main(String[] args) { Base b = new Derived(); b.foo(); // Derived.foo() will be activated }}

Page 39: Software Engineering Methods Winter 2002-3

Abstract• abstract member function, means that the function

does not have an implementation.• abstract class, is class that can not be instantiated.

NOTE: Every class with at least one abstract member function mustbe abstract class

Example

Page 40: Software Engineering Methods Winter 2002-3

Abstract - Examplepackage java.lang;public abstract class Shape {

public abstract void draw(); public void move(int x, int y) { setColor(BackGroundColor);

draw(); setCenter(x,y);

setColor(ForeGroundColor); draw(); }}

package java.lang;public class Circle extends Shape {

public void draw() { // draw the circle ... }}

Page 41: Software Engineering Methods Winter 2002-3

Interface• abstract “class”

• Helps defining a “usage contract” between classes

• All methods are public

• Java’s compensation for removing the multiple inheritance. You can “inherit” as many interfaces as you want.

Example * - The correct term is “to implement”an interface

Page 42: Software Engineering Methods Winter 2002-3

Interface

interface SouthParkCharacter { void curse();}

interface IChef { void cook(Food);}

interface Singer { void sing(Song);}

class Chef implements IChef, SouthParkCharacter {// overridden methods MUST be public// can you tell why ?public void curse() { … }public void cook(Food f) { … }

}

Page 43: Software Engineering Methods Winter 2002-3

When to use an interface ?

Perfect tool for encapsulating the classes inner structure. Only the interface will be exposed

Page 44: Software Engineering Methods Winter 2002-3

final

• final member dataConstant member

• final member function The method can’t be overridden.

• final class‘Base’ is final, thus it can’t be extended

final class Base { final int i=5; final void foo() { i=10; }}

class Derived extends Base { // Error // another foo ... void foo() { }}

Page 45: Software Engineering Methods Winter 2002-3

Collectionsbehavior

implementation

HashSet TreeSet

Set

LinkedList ArrayList

ArrayMap HashMap TreeMap

MapList

Collection Iteratorproduces

Page 46: Software Engineering Methods Winter 2002-3

import java.util.*;

class ListTest { static void showCollection(Collection col) { Iterator it = col.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } static void showList(List lst) {

for(int i=0;i<lst.size();i++) { System.out.println("" + i + ": " + lst.get(i)); } }

public static void main(String[] args) { LinkedList ll = new LinkedList(); ArrayList al = new ArrayList(); ll.add("one");ll.add("two");ll.add("three"); al.add("one");al.add("two");al.add("three"); showList(ll);showCollection(ll); showList(al);showCollection(al); }}

List

0: one1: two2: threeonetwothree0: one1: two2: threeonetwothree

Page 47: Software Engineering Methods Winter 2002-3

import java.util.*;

class MapTest { static void ShowMap(Map m) { Set s = m.entrySet(); Iterator it = s.iterator(); while(it.hasNext()) { Map.Entry entry = (Map.Entry)it.next(); // downcast System.out.println(entry.getKey() +

"-->" + entry.getValue()); } } public static void main(String[] args) { TreeMap tm = new TreeMap(); HashMap hm = new HashMap();

tm.put(new Integer(1),"one");tm.put(new Integer(2),"two"); tm.put(new Integer(3),"three"); hm.put(new Integer(1),"one");hm.put(new Integer(2),"two"); hm.put(new Integer(3),"three"); ShowMap(tm); ShowMap(hm); }}

Map

1-->one2-->two3-->three3-->three2-->two1-->one

Page 48: Software Engineering Methods Winter 2002-3

IO - Introduction• Definition

– Stream is a flow of data• characters read from a file

• bytes written to the network

• …

• Philosophy – All streams in the world are basically the same.

– Streams can be divided (as the name “IO” suggests) to Input and Output streams.

• Implentation– Incoming flow of data implements “Reader”

– Outgoing flow of data implements “Writer”

Page 49: Software Engineering Methods Winter 2002-3

SourceSink Filter

Stream concepts

Page 50: Software Engineering Methods Winter 2002-3

IO - Examples (1)

Reading input by lines

FileReader in = new FileReader(“CrimeAndPunishment.txt”));

String s;

while((s = in.readLine()) != null) {System.out.println(s);

}

Page 51: Software Engineering Methods Winter 2002-3

IO - Examples (2)

Reading standard input

BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)));

System.out.println(“Enter a line:”);System.out.println(stdin.readLine());

System.in is a reference of type InputStream.InputStream, is the “Reader” of JDK 1.0 . It is still required sometimes ( as in this case, where System.in type must be keptfor backward compatibility )

Page 52: Software Engineering Methods Winter 2002-3

IO - Examples (3)

Reading from String

StringReader in = new StringReader(“Hello World”);

int c;

while((c = in.read()) != -1)System.out.println((char)c);

Page 53: Software Engineering Methods Winter 2002-3

Advanced Usage

// Load drug information from a reader stream.

public void load(Reader r) throws IOException {

// File is ordered in 3 columns: name toxicity effectDuration

StreamTokenizer st = new StreamTokenizer(r);

// Check if there is a data to read

...

public static void main(String[] arg) {

DrugInfo drug;

try {

drug = new DrugInfo();

drug.load(new StringReader("LSD 4 4"));

...

} ...

from DrugInfo class

Page 54: Software Engineering Methods Winter 2002-3

IO - Advanced topics

• Redirecting standard IO– System contains setIn, setOut and setErr.

• E.g. System.setIn(new FileInputStream(“x.dat”));

– Standard streams could be from/to anything you want!

• Compression– Read about ZipInputStream and ZipOutputStream

Page 55: Software Engineering Methods Winter 2002-3

Exception - Why ?

• Handling all possible irregularities in the execution can be too complicated– Too many “if” statements– Return value must always be an error value– Need to handle errors in constructor (there is no

return value from a constructor)

Page 56: Software Engineering Methods Winter 2002-3

Exceptions – How to handle ?public class ThrowingBufferedReader extends BufferedReader {

public ThrowingBufferedReader(Reader r) {

super(r);

}

public ThrowingBufferedReader(Reader r, int sz) {

super(r,sz);

}

public String readLine() throws EOFException,IOException{

String s;

s = super.readLine();

if (s == null) throw new EOFException();

return s;

}

}

Page 57: Software Engineering Methods Winter 2002-3

Exception – How to handle (2)

void foo(Reader r) { ThrowingBufferedReader br = new ThrowingBufferedReader(r); try { // Suppose we’re expecting three lines to appear // in the stream. a = br.readLine(); b = br.readLine(); c = br.readLine(); } catch(EOFException e) { System.err.println(“Error with input”); } catch(Exception e) { System.err.println(“Caught unexpected exception”); } }

Page 58: Software Engineering Methods Winter 2002-3

Exception - What is it ?• Exception is an Object

• Exception class must be descendent of Throwable.

• When thrown– Stops the current path of execution.

– Control is returned to the first matching catch block on the stack.

• Every method must declare the exceptions it might throw.

Page 59: Software Engineering Methods Winter 2002-3

Exceptions – Creating your own

Class UglyException extends Exception { public String response_; UglyException(String str) {

response_ = str; }}

class Woman { void התחל() throws UglyException { // … throw new UglyException(“Go away !”); // … }}

Page 60: Software Engineering Methods Winter 2002-3

Inner class

class A { int i; public class B { int getI() { return i; } }

public static class C { int getI() { // error return i; } }

}

Class B holds a hidden referenceto the father class A

With the static keyword, C’s name is changed toA.C

Note: This is the last static usage.

Page 61: Software Engineering Methods Winter 2002-3

Anonymous class

Rational

- Suppose you have a class, which has only one instantiation place

- Suppose that this class is very small

- Suppose you have several classes with the characteristics above

Do you really want to define a formal class for each and every such class ? - Sure you don’t ….

Page 62: Software Engineering Methods Winter 2002-3

Anonymous class - cont.

Define a derived class

class Derived extends Base { void foo() { print(“Derived”); }}

Instantiation

bar(new Derived());

class Base { void foo() { System.out.println(“Base”); }}

Define & instantiate

bar( new Base() { void foo() { print(“Derived”); } } );

More meaningful examples when we will talk about GUI

Another call with the exact same class is IMPOSSIBLE !

Page 63: Software Engineering Methods Winter 2002-3

GUI ( Graphical User Interface)

• AWT - Abstract Windows Toolkit – Usually referred to as Awful Windows Toolkit (in Java 1.0)

– Defines Event-Based Framework for writing GUI.

• Swing– Rich set of easy-to-use, easy-to-understand GUI

Components (called Java Beans) to allow you creating a GUI that you can be satisfied with.

It don’t mean a thing, if it ain’t got that Swing …

Page 64: Software Engineering Methods Winter 2002-3

GUI - cont.

• GUI in Java has hierarchical structure

JComponent

Component

JButtom

Container

1

*

Window

Dialog

JDialog

1

*

JLabelJCheckBox

Page 65: Software Engineering Methods Winter 2002-3

Event Model• A component can initiate (“fire”) an event.

• Each type of event is represented by a distinct class (derived from ComponentEvent )

• When an even is fired, it is received by one or more “listeners”, which act on that event. ( listener is a class, derived from EventListener )

• Each event listener is an object of a class that implements a particular type of listener interface.

Page 66: Software Engineering Methods Winter 2002-3

Example - MessageBox

Page 67: Software Engineering Methods Winter 2002-3

package Mackey;

import java.awt.*; import javax.swing.*; import javax.swing.border.*;import java.awt.event.*;

public class MackeyBox extends JDialog { /** Panel serves as a container. **/ JPanel pnlMessageBox = new JPanel();

/** Components in the action **/ JButton btnCancel = new JButton(“Cancel”); JButton btnMkay = new JButton(“Mkay”); JTextArea txtQuestion = new JTextArea(“

Do you want to continue ?”);

Page 68: Software Engineering Methods Winter 2002-3

/** c’tor **/ public MackeyBox(Frame frame,

String title, boolean modal) { // call JDialog ctor. // if frame is closed, out dialog will be disposed. super(frame, title, modal);

try { jbInit();// initialize all the components pack(); // shrink the window to match // the preffered size of the // contained components } catch(Exception ex) { ex.printStackTrace(); }}

Page 69: Software Engineering Methods Winter 2002-3

public MackeyBox() { // transfer control from // one ctor to another this((Frame)null, "", false); }

/** entry point **/ public static void main(String[] args) { MackeyBox mb = new MackeyBox(); mb.setVisible(true); }

Page 70: Software Engineering Methods Winter 2002-3

/** initialize components **/void jbInit() throws Exception {

txtQuestion.setWrapStyleWord(true); txtQuestion.setEditable(false); txtQuestion.setFont(

new Font("Dialog", 0, 25)); txtQuestion.setBounds(

new Rectangle(36, 22, 225, 90)); txtQuestion.setLineWrap(true); txtQuestion.setBackground(SystemColor.text); pnlMessageBox.setLayout(null); pnlMessageBox.setPreferredSize(

new Dimension(291, 172));

Page 71: Software Engineering Methods Winter 2002-3

btnCancel.setBounds( new Rectangle(157, 132, 80, 27));

// notice the anonymous class usage here !!! btnCancel.addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { /* The reason we can call this method, is because the created anonymous class, has a hidden pointer to the current instance of MackeyBox class. */

btnCancel_mousePressed(e); } });

Page 72: Software Engineering Methods Winter 2002-3

btnMkay.setBounds(new Rectangle(36, 132, 79, 27));

btnMkay.addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) {

System.out.println("Mkay pressed"); System.exit(0);

} });

pnlMessageBox.add(btnMkay); pnlMessageBox.add(btnCancel); pnlMessageBox.add(txtQuestion); getContentPane().add(pnlMessageBox); setResizable(false);}

Page 73: Software Engineering Methods Winter 2002-3

void btnCancel_mousePressed(MouseEvent e) {System.out.println("Cancel pressed");

System.exit(0); }}

Page 74: Software Engineering Methods Winter 2002-3

(Much) Shorter version

Page 75: Software Engineering Methods Winter 2002-3

Code

/** entry point **/public static void main(String[] args) { Object[] options = { "Mkay", "Cancel" }; int selectedValue =

JOptionPane.showOptionDialog(null, "Do you want to continue ?", "",

JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[0]);

System.out.println(selectedValue);}

Page 76: Software Engineering Methods Winter 2002-3

Layout Manager

• null – Each component has specific place and size.

• FlowLayout – Components are added from left to right,

top to bottom, by the order they are added to the container

(components are sized according to preferred size)

• GridLayout – Table-like order.

• BorderLayout – 5 regions subdivision.

• GridbagLayout – The most robust and complicated one.

• BoxLayout – Order by y or x axis

Page 77: Software Engineering Methods Winter 2002-3

Example

Page 78: Software Engineering Methods Winter 2002-3

BoxLayout (y-axis) GridLayout (2,2)

BoxLayout (x-axis)

Page 79: Software Engineering Methods Winter 2002-3

class MyDialog extends JDialog{

...

Container cnt = this.getContentPane();

cnt.setLayout(new BoxLayout(cnt,BoxLayout.Y_AXIS));

JPanel pnlMain = new JPanel();

pnlMain.setLayout(new GridLayout(2,2,10,10));

JPanel pnlButtons = new JPanel();

pnlButtons.setLayout(

new BoxLayout(pnlButtons,BoxLayout.X_AXIS));

pnlMain.add(lblLogin);

pnlMain.add(txtLogin);

pnlMain.add(lblPass);

pnlMain.add(txtPass);

pnlButtons.add(btnCont);

pnlButtons.add(btnExit);

pnlButtons.add(btnExpload);

txtLogin.setPreferredSize(new Dimension(200,30));

cnt.add(pnlMain);

cnt.add(pnlButtons);

this.setResizable(false); …}

Setting theGrid section

Setting theButtons section

MainCode

full code on the web-site

Page 80: Software Engineering Methods Winter 2002-3

Java Applet• Applet is basically, a panel, with special functions,

required for working with a browser.– init() Called when the applet is first created to perform

the first-time initialization

– start() Called every time the applet moves into sight on the Web-Browser

– paint() Allows special painting of the applet.

– stop() Called every time the applet moves out of sight on the Web-Browser.

– destroy() Called every time the applet is being unloaded from the page

More material is out of the scope of this course ...