Java Programming Matt Tsai. JavaOne Outline SDK and tools Object-Oriented Programming Java concept

Preview:

Citation preview

Java Programming

Matt Tsai

JavaOne

Outline SDK and tools Object-Oriented Programming Java concept

Java Development Kit (JDK) JDK 1.4 (http://java.sun.com) Other tools—kawa,UltraEdit,EditPlus jar xvf src.jar jar cvf myClass.jar test1.class [test2.class]

JDK 主要程式 javac:java 的編譯器 ,source code->byte

code javac HelloWorld.java HelloWorld.class

java:java 的解譯器 java HelloWorld

appletviewer:java 的解譯器 , 可以執行 HTML檔案中的 applet 程式 在 HelloWorld.html 檔案中加入

<applet code=HelloWorld.class width=300 height=400></applet>

appletviewer HelloWorld.html 其他 :javadoc,jdb,javah,javap,etc.

Java 程式的執行 假設 JDK 安裝在 c:\jdk1.4 autoexec.bat 中加入

Set path= %path%;.;c:\jdk1.4\bin Classpath 以前舊的版本要加 , 現在的

版本不用加 , 除非是自己定義的且不在程式目前所在的目錄 Set classpath=%classpath%;d:\

myJava

Java 程式的執行 (classpath)

import iecs;

public class Hello{

public static void main(String args[]){

iecs myIECS=new iecs();

System.out.println(myIECS.Information());

}

}

public class iecs{

public iecs(){

}

public String Information(){

return " Hello World!!!";

}

}

E:\Hello.java D:\myJava\iecs.java

Set classpath=%classpath%;d:\myJava

D:\myJava\java iecs.java

E:\javac Hello.java

E:\java Hello

Hello World!!!

Java 程式的執行 (package)

import edu.fcu.iecs.*;

public class Hello{

public static void main(String args[]){

iecs myIECS=new iecs();

System.out.println(myIECS.Information());

}

}

package edu.fcu.iecs;

public class iecs{

public iecs(){

}

public String Information(){

return " Hello World!!!";

}

}

E:\Hello.java D:\myJava\edu\fcu\iecs\iecs.java

Set classpath=%classpath%;d:\myJava

D:\myJava\edu\fcu\iecs\java iecs.java

E:\javac Hello.java

E:\java Hello

Hello World!!!

D:\myJava\jar cvf myJava.jar eduSet classpath=%classpath%;d:\myJava\myJava.jar

Object-Oriented Programming 封裝 資訊隱藏 繼承性 多型 : 同一個函式在多個類別中

繼承 Overloading( 同名但參數相異 ) 介面

封裝 , 資訊隱藏Class MyObject{

private int ID;

private String name;

public void getInformation(){

System.out.println(ID+”:”+name);

}

public void setup(int ID,String name){

this.ID=ID;

this.name=name;

}

private void reset(){

}

}

private int ID;

private String name;

getInformation()

setup(…)

reset()

MyObject

封裝 , 資訊隱藏public class Test{

public static void main(String argv[]){

MyObject MyObj=new MyObject();

MyObj.setup(123,”ChinYiTsai”);

System.out.println(MyObj.ID+”:”+MyObj.name);

MyObj.getInformation();

MyObj.reset();

}

}

繼承性A

B C

D E F

public class Parent{

Parent(){

}

public void funcation1(){

System.out.println(“Parent”);

}

}

public class Child extends Parent {

public void function1(){

System.out.println(“child”);

}

public void function2(){

System.out.println(“child child”);

}

}

public interface MyInterface{

}

implements MyInterface

Java Concept First Program(Hello World) Java 類別函式庫 Abstract class and Interface Inner class Static this

//import java.io.*;

//import javax.swing.*;

public class HelloWord{

public static void main(String argv[]){

System.out.println(“Hello Word”);

}

} 不 必 先 new 一 個 實

體 即 可 使 用

檔名必須為HelloWorld.ja

va

程式的進入點

import javax.swing.*;

import java.awt.*;

public class HelloWord extends JFrame{

JButton Button_hello;

JLabel Label_hello;

HelloWord(){

Container con=getContentPane();

con.setLayout(new FlowLayout());

Button_hello=new Jbutton(“Hello Button”);

Label_hello=new Jlabel(“Hello Label”);

con.add(Label_hello);

con.add(Button_hello);

}

public static void main(String argv[]){

HelloWord helloword=new HelloWord();

helloword.setBounds(0,0,400,400);

helloword.setVisible(true);

}

}

設 定 版 面 管

建構

實體化

繼承 JFrame 類別

加入Container

Java 類別函式庫 java.applet java.io java.awt javax.swing java.awt.event org.omg.CORBA …

Abstract class and Interface Abstract class

不能直接使用 , 須以繼承 (extends) 的方式才可以

Interface 以 implements 的方式來實作

public interface windowListener extends EventListener{

public void windowOpened(WindowEvent e){

}

public void windowClosing(WindowEvent e){

}

public void windowClosed(WindowEvent e){

}

public void windowIconified(WindowEvent e){

}

public void windowDeiconified(WindowEvent e){

}

public void windowActivated(WindowEvent e){

}

public void windowDeactivated(WindowEvent e){

}

}

public WinHandler implements windowListener{

public void windowOpened(WindowEvent e){

}

public void windowClosing(WindowEvent e){

System.exit(1);

}

public void windowClosed(WindowEvent e){

}

public void windowIconified(WindowEvent e){

}

public void windowDeiconified(WindowEvent e){

}

public void windowActivated(WindowEvent e){

}

public void windowDeactivated(WindowEvent e){

}

}

Inner class

Class A

Class B

public class A{

int ID;

A(){

}

public void A2(){

}

class B{

B(){

A2();

}

}

}

public class Sample{

private JTextArea show_textatea;

private JButton button;

Sample(){

Container con=getContentPane();

show_textarea=new JTextArea(20,20);

button=new Jbutton(“show”);

con.add(button);

con.add(show_textatea);

button.addActionListener(new ActionHandler());

}

class ActionHandler implements ActionListener{

public void actionPerformed(ActionEvent e){

show_textarea.append("textfield\n");

}

}

}

public class Sample{

JTextArea show_textatea;

JButton button;

Sample(){

Container con=getContentPane();

show_textarea=new JTextArea(20,20);

button=new Jbutton(“show”);

con.add(button);

con.add(show_textatea);

button.addActionListener(new ActionHandler(this));

}

}

class ActionHandler implements ActionListener{

Sample samp;

ActionHandler(Sample samp){

this.samp=samp;

}

public void actionPerformed(ActionEvent e){

samp.show_textarea.append("textfield\n");

}

}

匿名內部類別public class sample{

Sample(){

button.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

show_textarea.append("textfield\n");

}

});

}

}

Static 類別載入即自動建立 不須實體化即可使用

public class TryWin{

static JFrame aWin=new JFrame(“This is the Window”);

public static void main(String args[]){

aWin.setBounds(0,0,400,400);

aWin.setVisible(true);

}

}

JFrame aWin=new JFrame(“This is the Window”);

JFrame MyFrame=new JFrame();

Color myColor=new Color();

MyFrame.setBackground(myColor.yellow);

MyFrame.setBackground(myColor.getColor(“yellow”));

public class Color extends Object implements Paint, Serializable{

public static final Color yellow

public static Color getColor(String nm) … }

JavaTwo

Outline Object-Oriented Programming Class and Object Abstract class and interface Books Practice Schedule

Object-Oriented Programming 封裝 資料隱藏 繼承性

封裝 , 資訊隱藏Class MyObject{

private int ID;

private String name;

public void getInformation(){

System.out.println(ID+”:”+name);

}

public void setup(int ID,String name){

this.ID=ID;

this.name=name;

}

private void reset(){

}

}

private int ID;

private String name;

getInformation()

setup(…)

reset()

MyObject

封裝 , 資料隱藏

public class Test{

public static void main(String argv[]){

MyObject MyObj=new MyObject();

MyObj.setup(123,”ChinYiTsai”);

System.out.println(MyObj.ID+”:”+MyObj.name);

MyObj.getInformation();

MyObj.reset();

}

}

繼承性A

C

B

public class A{ public void A1(){} public void A2(){}}

public class C extends B{ public void B3(){…} public void C4(){}}

public class B extends A{ public B3(){}}

A1A2

A1A2B3

A1A2B3C4

不可以被繼承 final

public static final int FINAL public final class Test

static public static int ID; public static boolean isStatic(int mod)

private private int ID private funtion1()

Class and Object

存取類別 publc protected private相同類別 v v v相同 package 中的類別

v v x

不同 package 的子類別

v v x

非子類別 , 不同package

v x x

存取控制

public class MyObject {

private int ID;

private String name;

public void getInformation(){

System.out.println(ID+”:”+name);

}

public void setup(int ID,String name){

this.ID=ID;

this.name=name;

}

private void reset(){

}

}

public class Test {

public static void main(String argv[]){

MyObject MyObj=new MyObject();

MyObj.setup(123,”ChinYiTsai”);

System.out.println(MyObj.ID+”:”+MyObj.name);

MyObj.getInformation();

MyObj.reset();

}

}

public class HelloWord{

public static void main(String argv[]){

System.out.println(“Hello Word”);

}

}

屬 於 類 別 , 不 屬

於 任 何 物 件

程式的進入點

public class System extends Object{

public static final PrintStream out;

. . .

}public class PrintStream extends FilterOutputStream{

public void println(boolean x){…}

public void println(char x) {…}

public void println(char[] x) {…}

public void println(double x) {…}

public void println(float x) {…}

public void println(int x) {…}

public void println(long x) {…}

public void println(Object x) {…}

public void println(String x) {…}

}

Class and Object Class

類別欄位 類別方法 實體欄位 實體方法 成員類別

Object: Class1 obj=new Class1();

public class Test{ public static int class_ID; public int obj_ID; public ststic void class_Function(){

} public void obj_Function(){

} class Test1{ … }}

類別欄位實體欄位

類別方法

成員類別

實體方法

類別轉換 子類別型別的物件可視為父類型別的物

件 Object o=new Object() String s=new String() o=s ( 子 -> 父 ) ; s=(String)o ( 父 ->

子 )

內部類別 成員類別

與所處類別的實體相關連 不可含有 static 欄位 , 方法 , 類別 介面不可被定義為成員類別

匿名類别 沒有名字 類別很小 使用一次 馬上使用

內部類別

Class A

Class B

public class A{

int ID;

A(){

}

public void A2(){

}

class B{

B(){

A2();

}

}

}

public class Sample{

private JTextArea show_textatea;

private JButton button;

Sample(){

Container con=getContentPane();

show_textarea=new JTextArea(20,20);

button=new Jbutton(“show”);

con.add(button);

con.add(show_textatea);

button.addActionListener(new ActionHandler());

}

class ActionHandler implements ActionListener{

public void actionPerformed(ActionEvent e){

show_textarea.append("textfield\n");

}

}

}

Mybutton.addActionListener(

new ActionListener(){

public void actionPerformed(ActionEvent e){

System.out.println(“click button”);

}

}

);

public class ActionHandler implements ActionListener{

Abstract class and Interface Abstract class

至少含有一個抽象方法 , 也可以有已實作的方法

Interface 介面中的方法是抽象方法 , 若沒有完全實作 ,

則會變作抽象類別 可多重繼承與實作

public abstract class Car{ public abstract void move(); public abstract void stop(); public void back(){ System.out.println(“back”); }}

public class March extends Car{

March(){

}

public void move(){

}

public void stop(){

back();

}

}

public interface user{ public void setNumber(int num); public void setTime(int time); public void getInformation();}

public class student implements user{

public void setNumber(int num){… } public void setTime(int time){… } public void getInformation(){… } …}

public abstract class student2 implements user{

public void setTime(int time){… } public void getInformation(){… } …}

public class Test extends Object implements Interface1,Interface2,Interface3,Interface4{

…}

public interface MyInterface extends Interface1, Interface2,Interface3{

…}

Adapter 類別 已實作 interface 中的方法 overridding 事件的處理

WindowAdapter 類別

Example(Adapter 類別 + 匿名類別 )

frameOBJ.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

System.exit(0);

}});

public class MyHandler extends WindowAdapter{

public void windowClosing(WindowEvent e){

System.exit(0);

}

}

public abstract class WindowAdapter extends Object implements WindowListener

JavaThree

Java Event Handle

Event Handle

Event Handler

Ignore

Source

Java Event Handle Event 的要素

事件發生的來源 ( 元件 ) Listener(class) 處理事件的程式碼 (response)

Button按下 Button

ActionEvent

產生 ActionEvent 物件

ActionListner

public void actionPerformed(ActionEvent){

.

.

.

}

事件發生的來源 ( 元件 ) Listener(class)處理事件的程式碼

JFrameClose Frame

WindowEvent

產生 WindowEvent 物件

WindowListner

windowOpened(windowEvent)

Windowclosing(windowEvent)

Windowclosed(windowEvent)

windowIconified(windowEvent)

windowDeiconified(windowEvent)

windowActivated(windowEvent)

windowDeactivated(windowEvent)

java.awt.event 事件類別java.lang.Object

java.util.EventObject

java.awt.AwtEvent

ActionEvent

AdjustmentEvent

ItemEvent

ComponentEvent

Container

FocusEvent

PaintEvent

WindowEvent

KeyEvent MouseEvent

InputEvent

import java.awt.event.*;

java.awt.event 的 Listener介面

Interface SummaryActionListenerAdjustmentListenerAWTEventListenerComponentListenerContainerListenerFocusListenerHierarchyBoundsListenerHierarchyListenerInputMethodListenerItemListenerKeyListner MouseListenerMouseMotionListenerTextListenerWindowListener

void KeyPressed(KeyEvent e)           Invoked when a key has been pressed. void keyReleased(KeyEvent e)           Invoked when a key has been released. void keyTyped(KeyEvent e)           Invoked when a key has been typed.

The listener interface for receiving keyboard events (keystrokes)

Event Handle Review元件button addActionListener( )

ActionListener

實作 Listener 介面

public void actionPerformed(ActionEvent e)

addActionListener

ActionListener

ActionEvent

事件 觸發者 Listener 處理方法keyEvent All KeyListener keyTyped()

keyPressed()keyReleased()

MouseEvent All MouseListenerMouseMotionListener

mouseClicked()mousePressed()mouseReleased()mouseEntered()mouseExited()mouseDragged()mouseMoved()

ActionEvent JbuttonJCheckBoxMenuItemJComboBoxJFileChooserJlistJRadioButtonMenuItemJTextFieldJToggleButton

ActionListener actionPerformed()

ActionEvent JButton ActionListener actionPerformed()

事件 觸發者 Listener 處理方法ItemEvent JCheckBoxMenuIte

mJComBoxJRadioButtonMenuItemJToggleButton

ItemListener itemStateChanged()

MenuEvent JMenu MenuListener menuCanceled()menuDeselected()menuSelected()

WindowEvent JDialogJFrameJWindow

WindowListener windowOpened()windowClosing()windowClosed()windowIconified()windowDeiconified()windowActivated()windowDeactivated()

AdjustmentEvent

JScrollBar AdjustmentListener

adjustmentValueChanged()

Program Example ActionEvent WindowEvent AdjustmentEvent KeyEvent MouseEvent

ActionEventpublic class ActionEvent extends AWTEvent{ … public String getActionCommand() public int getModifiers() public String paramString() }

Methods inherited from class java.awt.AWTEvent consume, finalize,getID, isConsumed,toString Methods inherited from class java.util.EventObject

getSource  Methods inherited from class java.lang.Object

clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait

WindowEventpublic class WindowEvent extends ComponentEvent{

public Window getWindow()

public String paramString()

}

Methods inherited from class java.awt.event.ComponentEventgetComponent 

Methods inherited from class java.awt.AWTEventconsume,finalize, getID, isConsumed, toString 

Methods inherited from class java.util.EventObjectgetSource 

Methods inherited from class java.lang.Objectclone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait

public class ExActionEvent extends JFrame{ public ExActionEvent(){

Container con=getContentPane();con.setLayout(new FlowLayout());button_one=new JButton("Button One");button_two=new JButton("Button Two");button_three=new JButton("Button Three");button_four=new JButton("Button Four");textarea_show=new JTextArea(20,20);con.add(button_one);con.add(button_two);con.add(button_three);con.add(button_four);con.add(textarea_show);button_one.addActionListener(new ActionEventHandler());button_two.addActionListener(new ActionEventHandler());button_three.addActionListener(new ActionEventHandler());button_four.addActionListener(new ActionEventHandler());

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

ExActionEvent myframe=new ExActionEvent();myframe.setBounds(0,0,500,500);myframe.setVisible(true);

}

}

ExActionEvent

Class ActionEventHandler implements ActionListener

class ActionEventHandler implements ActionListener{public void actionPerformed(ActionEvent e){

if(e.getActionCommand()=="Button One")textarea_show.append("You click button one"+"\n");

else if(e.getActionCommand()=="Button Two")textarea_show.append("You click button two"+"\n");

else if(e.getActionCommand()=="Button Three")textarea_show.append("You click button three"+"\n");

else if(e.getActionCommand()=="Button Four")textarea_show.append("You click button four"+"\n");

}}

ExWindowEvent

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

public class ExWindowEvent{

public ExWindowEvent(){JFrame myframe=new JFrame();Container con=myframe.getContentPane();con.setLayout(new FlowLayout());myframe.addWindowListener(new WindowEventHandler());myframe.setBounds(0,0,200,200);myframe.setVisible(true);

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

new ExWindowEvent(); }

}

class WindowEventHandler implements WindowListener

class WindowEventHandler implements WindowListener { public void windowClosing(WindowEvent e) {

System.out.println("window closing");System.exit(0);

} public void windowClosed(WindowEvent e) { } public void windowOpened(WindowEvent e) {

System.out.println("window opened"); } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowActivated(WindowEvent e) {

System.out.println("window activated"); } public void windowDeactivated(WindowEvent e) {

System.out.println("window deactived"); }}

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

public class ExAdjustmentEvent extends JFrame{JTextArea textarea_show;JScrollBar scrollbar_test;

public ExAdjustmentEvent(){Container con=getContentPane();con.setLayout(new GridLayout(2,1));textarea_show=new JTextArea(20,20);scrollbar_test=new JScrollBar(0,50,10,0,100);con.add(textarea_show);con.add(scrollbar_test);scrollbar_test.addAdjustmentListener(new AdjustmentEventHandler());

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

ExAdjustmentEvent myframe=new ExAdjustmentEvent();myframe.setBounds(0,0,500,500);myframe.setVisible(true);

} class AdjustmentEventHandler implements AdjustmentListener{

public void adjustmentValueChanged(AdjustmentEvent e){textarea_show.append(e.getValue()+"\n");

}}

}

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

public class ExKeyEvent extends JFrame{ JTextField textfield_input; JLabel label_show; String KeyString; public ExKeyEvent(){

Container con=getContentPane();con.setLayout(new GridLayout(2,1));textfield_input=new JTextField();label_show=new JLabel();con.add(label_show);con.add(textfield_input);textfield_input.addKeyListener(new KeyEventHandler());

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

ExKeyEvent myframe=new ExKeyEvent();myframe.setBounds(0,0,200,200);myframe.setVisible(true);

} class KeyEventHandler implements KeyListener{ public void keyTyped(KeyEvent e){

char c=e.getKeyChar();KeyString=KeyString+c;label_show.setText(KeyString);

} public void keyPressed(KeyEvent e){ } public void keyReleased(KeyEvent e){ } } }

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

public class ExMouseEvent extends JFrame{ JButton button_test; JLabel label_show; public ExMouseEvent(){

Container con=getContentPane();con.setLayout(new GridLayout(2,1));button_test=new JButton("button");label_show=new JLabel();con.add(button_test);con.add(label_show);button_test.addMouseListener(new MouseEventHandler());

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

ExMouseEvent myframe=new ExMouseEvent();myframe.setBounds(0,0,200,200);myframe.setVisible(true);

}

}

Class MouseEventHandler implements MouseListener

class MouseEventHandler implements MouseListener{ public void mouseClicked(MouseEvent e){

label_show.setText("mouse click"); } public void mousePressed(MouseEvent e){ label_show.setText("mouse press"); } public void mouseReleased(MouseEvent e){

label_show.setText("mouse release"); } public void mouseEntered(MouseEvent e){

label_show.setText("mouse enter"); } public void mouseExited(MouseEvent e){

label_show.setText("mouse exit"); }}

JavaFour

Java Window Programming

Outline First window programming Layout Manager Pracitce

First Java window programming

import java.awt.*;

import javax.swing.*;

public class BasicJFrame extends JFrame{

public BasicJFrame(){

}

public static void main(String args[]){

BasicJFrame myBasicJFrame=new BasicJFrame();

myBasicJFrame.setBounds(0,0,300,300);

myBasicJFrame.setVisible(true);

}

}

import java.awt.*;

import javax.swing.*;

public class BasicJFrame2{

public static void main(String args[]){

JFrame myBasicJFrame=new JFrame();

myBasicJFrame.setBounds(0,0,300,300);

myBasicJFrame.setVisible(true);

}

}

Top-level component JFrame,JDialog,JWindow,Japplet

實作 RootPaneContainer 介面 JRootPane GlassPane LayeredPane ContentPane

MenuBarContentPane

LayeredPaneGlassPane

RootPane

MenuBar

ContentPane

JRootPaneGlassPaneLayeredPaneContentPane

Add Component

getGlassPane()

getLayeredPane()

getRootPane()

getContentPane()

元件的加入

public class AddComponent extends JFrame{

public AddComponent(){

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

} }

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

AddComponent myBasicJFrame=new AddComponent();myBasicJFrame.setBounds(0,0,300,300);myBasicJFrame.setVisible(true);

JButton myButton1;JButton myButton2;

Container con=getContentPane();con.setLayout(new FlowLayout());

myButton1=new JButton("button 1");myButton2=new JButton("button 2");con.add(myButton1);con.add(myButton2);

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

public class AddEvent extends JFrame{JButton myButton1;JButton myButton2;public AddEvent(){

Container con=getContentPane();con.setLayout(new FlowLayout());myButton1=new JButton("button 1");myButton2=new JButton("button 2");con.add(myButton1);con.add(myButton2);myButton1.addActionListener(new ActionHandler());

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

AddEvent myBasicJFrame=new AddEvent();myBasicJFrame.setBounds(0,0,300,300);myBasicJFrame.setVisible(true);

}class ActionHandler implements ActionListener{

public void actionPerformed(ActionEvent e){if(e.getActionCommand()=="button 1")

myButton1.setText("click button 1");else if(e.getActionCommand()=="click button 1")

myButton1.setText("button 1");}

}}

Event

Event

視窗程式所需之 Package java.awt.*;

Container javax.swing.*;

Swing components(JButton,JList,etc) java.awt.event.*;

Event Handle

Layout Manager FlowLayout

以加入的順序自左而右排放元件 BorderLayout

東 , 南 , 西 , 北 , 中 GridLayout

以行列的方式擺放元件 BoxLayout

沿著水平的 x 軸 , 垂直的 y 軸擺放 GardLayout

最上層的才看的到 GridBagLayout

和 GridLayout 很像 , 但元件可以變化大小

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

public class FlowLayoutDemo extends JFrame{ public FlowLayoutDemo() { Container con = getContentPane(); con.setLayout(new FlowLayout());

con.add(new JButton("first")); con.add(new JButton("second")); con.add(new JButton("third")); con.add(new JButton("fourth")); con.add(new JButton("fifth")); con.add(new JButton("This is the last button")); } public static void main(String args[]) { FlowLayoutDemo myFlowLayout = new FlowLayoutDemo(); myFlowLayout.setBounds(0,0,200,200); myFlowLayout.setVisible(true); }}

FlowLayout

con.setLayout(new FlowLayout(FlowLayout.LEFT));

myFlowLayout.setBounds(0,0,300,300);

BorderLayout

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

public class BorderLayoutDemo extends JFrame{ public BorderLayoutDemo() { Container con= getContentPane(); con.setLayout(new BorderLayout()); con.add(new JButton("EAST"),BorderLayout.EAST); con.add(new JButton("WEST"),BorderLayout.WEST); con.add(new JButton("SOUTH"),BorderLayout.SOUTH); con.add(new JButton("NORTH"),BorderLayout.NORTH); con.add(new JButton("CENTER"),BorderLayout.CENTER); }

public static void main(String args[]) { BorderLayoutDemo myBorderLayout = new BorderLayoutDemo(); myBorderLayout.setBounds(0,0,400,400); myBorderLayout.setVisible(true); }}

GridLayout

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

public class GridLayoutDemo extends JFrame{ public GridLayoutDemo() { Container con = getContentPane(); con.setLayout(new GridLayout(6,1)); con.add(new JButton("first")); con.add(new JButton("second")); con.add(new JButton("third")); con.add(new JButton("fourth")); con.add(new JButton("fifth")); con.add(new JButton("This is the last button"));

} public static void main(String args[]) { GridLayoutDemo myGridLayout = new GridLayoutDemo(); myGridLayout.setBounds(0,0,300,300); myGridLayout.setVisible(true); }}

con.setLayout(new GridLayout(2,3));

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

public class BoxLayoutDemo extends JFrame{ JButton myButton_1; JButton myButton_2; JButton myButton_3; JButton myButton_4; JButton myButton_5; JButton myButton_6; public BoxLayoutDemo() { Container con = getContentPane(); Box conBox = Box.createHorizontalBox(); con.add(conBox); Box vBox_1 = Box.createVerticalBox(); myButton_1 = new JButton("first_V"); myButton_2 = new JButton("two_V"); vBox_1.add(myButton_1); vBox_1.add(Box.createVerticalGlue()); vBox_1.add(myButton_2); Box vBox_2 = Box.createVerticalBox(); myButton_3 = new JButton("three_V"); myButton_4 = new JButton("four_V"); Box hBox_1 = Box.createHorizontalBox(); vBox_2.add(myButton_3); vBox_2.add(Box.createVerticalStrut(50)); vBox_2.add(hBox_1); myButton_5=new JButton("five_H"); myButton_6=new JButton("six_H");

hBox_1.add(myButton_5); hBox_1.add(myButton_6); vBox_2.add(myButton_4); conBox.add(vBox_1); conBox.add(vBox_2); } public static void main(String args[]) { BoxLayoutDemo myBoxLayout = new BoxLayoutDemo(); myBoxLayout.setBounds(0,0,250,250); myBoxLayout.setVisible(true); }}

垂直 Box

垂直 Box

CardLayout

Card1 Card2

GridBagLayout

Swing 元件JButtonJCheckBoxJListJComboBoxJDialogJLabelJMenu

JMenuItemJMenuBarJPanelJScrollBarJTableJTextAreaJTextFieldJToolBar

JPanel

Component

Container

Window

Frame

JFrame

Panel

Applet

JApplet

Dialog

JDialog JWindow

JComponent

class About extends JDialog {JPanel aboutPane;JTextArea text;

public About(JFrame parentFrame,String title,boolean modal){super(parentFrame,title,modal); setBounds(200,200,300,300);

aboutPane=new JPanel(new GridLayout(1,1));aboutPane.setBackground(Color.blue);

aboutPane.setForeground(Color.blue); text=new JTextArea(30,30); text.setBackground(Color.black); text.setForeground(Color.yellow);

if(title=="About version"){text.setText("******Verson 1.0 ******"+"\n");

}else{

text.setText("Author:Chin-Yi Tsai" +"\n" );

}

aboutPane.add(text);this.getContentPane().add(aboutPane);show();

}}

JDialog(demo)

JavaFive

Java I/O

import java.io.*;

import java.io.*;Object

InputStream

File

RandomAccessFile

OutputStream

Reader

Wrtier

ByteArrayInputStream

StringBufferInputStream

FileInputStream

SequenceInputStream

FilterInputStream

PipedInputStreamObjectInputStream

ByteArrayOutputStream

StringBufferOutputStream

FileOutputStream

SequenceOutputStream

FilterOutputStream

PipedOutputStreamObjectOutputStream

BufferedInputStreamDataInputStream

LineNumberInputStreamPushbackInputStream

BufferedOutputStreamDataOutputStream

PrintStream

BufferedWriter

StringWriter

CharArrayWriter

PrintWriter

FilterWriter

PipedWriterOutputStreamWriter FileWriter

BufferedReader

StringReader

CharArrayReaderFilterReader

PipedReaderInputStreamReader FileReader

I/O

字元

Writer Reader

BufferedWriterCharArrayWriterFilterWriterPipedWriterStringWriter

BufferedReaderCharArrayReaderFilterReaderPipedReaderStringReader

位元組

InputStreamOutputStream

ByteArrayOutputStreamFileOutputStreamFilterOutputStreamObjectOutputStreamPipedOutputStream

ByteArrayInputStreamFileIntputStreamFilterIntputStreamObjectIntputStreamPipedIntputStream

InputStreamReaderOutputStreamWriter

Java I/O 作用 讀取及寫入檔案 網路通訊 過濾資料 加 / 解 密 壓 / 解壓 縮 在 thread 之間傳送資料 把物件寫入串流 檔案和目錄之操作 讓 user 中 GUI 介面選取檔案 Java 所有 I/O 動作都是以串流為基礎

InputStreamOutputStream

FilterInputStreamFilterOutputStream

PipedInputStreamPipedOutputStream

ObjectInputStreamObjectOutputStream

File

FileInputStreamFileOutputStream

write

read

OutputStream

InputStream

Stream 操作

PipedInputStreamPipedOutputStream

File2_out

File1_in

各種分類 InputStream OutputStream Reader Writer File

--- 表示其子類別有各自不同的型態運用BufferedWriterCharArrayWriterFilterWriterPipedWriterStringWriter

不同種類的串流 輸入串流 輸出串流 檔案串流 網路串流 濾器串流 資料串流

記憶中的串流 壓縮串流 密文串流 物件串流 Reader Writer

I/O

字元

Writer Reader

BufferedWriterCharArrayWriterFilterWriterPipedWriterStringWriter

BufferedReaderCharArrayReaderFilterReaderPipedReaderStringReader

位元組

InputStreamOutputStream

ByteArrayOutputStreamFileOutputStreamFilterOutputStreamObjectOutputStreamPipedOutputStream

ByteArrayInputStreamFileIntputStreamFilterIntputStreamObjectIntputStreamPipedIntputStream

InputStreamReaderOutputStreamWriter

資料串流

記憶中的串流

壓縮串流

密文串流

物件串列化

InputStream stdin=System.in; OutputStream stdout=System.out; OutputStream stderr=System.err;

InputStreamReader converter=new InputStreamReader(System.in);

BufferedReader in=new BufferedReader(converter);

InputStream

InputStreamReader

BufferedReader

過濾串流 Super class

FilterInputStream FilterOutputStream FilterReader FilterWriter

java.io.FileFile f=new File(“/temp/file.txt”);File f=new File(“/temp/temp2”);File f=new File(“/tmep”,”fiel.txt”);File tempDir=new File(“/temp”);File f=new File(tempDir,”file.txt”)

InputStreamimport java.io.*;public class StreamPrinter{ InputStream myInput; public static void main(String[] args){ myInput=System.in; try{ while(true){ int datum=myInput.read(); if(datum==-1) break; System.out.println(datum); } }catch(IOException e){ } } }

InputStream stdin=System.in;

OutputStreamimport java.io.*;

public class AsciiChart{

public static void main(String[] args){

for(int i=32;i<127;i++){

System.out.write(I);

if(i%8==7)

System.out.write(‘\n’);

else

System.out.write(‘\t’);

}

System.out.write(‘\n’);

}

}

OutputStream stdout=System.out;

File Stream FileInputStream FileOutputStream

import java.io.*;

public class FileCopier{

public static void main(String[] args){

if(args.length!=2){

System.err.println(“Usage:java FileCopier infile outfile”);

}

try{

FileInputStream fin=null;

FileOutputStream fout=null;

fin=new FileInputStream(args[0]);

fout=new FileOutputStream(args[1]);

byte[] buffer=new byte[256];

while(true){

int byteRead=fin.read(buffer);

if(byteRead==-1) break;

fout.write(buffer,0,byteRead);

}

}catch(IOException e){}

fin.close();

fout.close();

}

}

Network Stream Stream source

URL,URLConnection, Socket,ServerSocket

try{ URL u=new URL(http://www.fcu.edu.tw/); InputStream in=u.openStream(); int b; while((b=in.read())!=-1){ System.out.write(b); }}catch(MalformedURLException e){ System.err.println(e);}catch(IOException e){ System.err.println(e);}

URL

try{ URL u=new URL(http://www.fcu.edu.tw/); URLConnection uc=u.getCOnnection(); uc.connect(); InputStream in=uc.getInputStream();} catch(IOException e){ System.err.println(e);}

URLConnection

Socket s=new Socket(host,80);String request=“my Request”;byte[] b=request.getBytes();

OutputStream out=s.getOutputStream();InputStream in=s.getInputStream();out.write(b);out.flush();

Socket

try{ ServerSocket ss=new ServerSocket(80); while(true){ Socket s=ss.accept(); OutputStream out=s.getOutputStream(); … s.close(); } catch(IOException e){ System.err.println(e); }}

ServerSocket

Filter Stream

Source

Destinationtranslation

compression

encryptionFilter

資料壓縮 Java.util.zip

GZIP,ZIP GZIPOutputStream GZIPInputStream

GZIPOutputStream

*.gz

source

GZIPInputStreamsource

import java.io.*;import java.util.zip.*;public class GZip { public static int sChunk = 8192; public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GZip source"); }

String zipname = args[0] + ".gz"; GZIPOutputStream zipout; try { FileOutputStream out = new FileOutputStream(zipname); zipout = new GZIPOutputStream(out); }catch (IOException e) { System.out.println("Couldn't create " + zipname + "."); } byte[] buffer = new byte[sChunk]; try { FileInputStream in = new FileInputStream(args[0]); int length; while ((length = in.read(buffer, 0, sChunk)) != -1) zipout.write(buffer, 0, length); in.close( ); } } catch (IOException e) { System.out.println("Couldn't compress " + args[0] + "."); } try { zipout.close( ); } catch (IOException e) {} }}

GZIPOutputStream

FileInputStream in=new FileInputStream(zipname);Zipin=new GZIPInputStream(in);

FileOutputStream out=new FileOutputStream(source);Int length;While((length=zipin.read(buffer,0,sChunk))!=-1) out.write(buffer,0,length);out.close();

GZIPInputStream

記憶體中的 Stream Sequence input stream

將幾個輸入串流串聯起來 , 讓它們看起來像單一串流

byte array stream 可以把輸出放在位元組陣列 , 並從位元

組陣列讀取輸入 Piped I/O stream

可以讓 thread 的輸出成為另一個thread 的輸入

Piped I/O Stream

Thread1

Thread2

PipedInputStream

PipedOutputStream

PipedOutputStream pout=new PipedOutputStream();PipedInputStream pin=new pipedInputStream(pout);

FibonacciWriter fw=new FibonacciWriter(pout,howMany); FibonacciReader fr=new FibonacciReader(pin);fw.start();fr.start();

物件串列化 自動儲存和載入物件狀態

import java.io.*;import java.util.*;

public class Save { public static void main(String[] args) { Hashtable h = new Hashtable( ); h.put("string", "Gabriel Garcia Marquez"); h.put("int", new Integer(26)); h.put("double", new Double(Math.PI));

try { FileOutputStream fileOut = new FileOutputStream("h.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(h); } catch (Exception e) { System.out.println(e); } }}

save

import java.io.*;import java.util.*;

public class Load { public static void main(String[] args) { try { FileInputStream fileIn = new FileInputStream("h.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); Hashtable h = (Hashtable)in.readObject( ); System.out.println(h.toString( )); } catch (Exception e) { System.out.println(e); } }}

Load

Object

InputStream

File

RandomAccessFile

OutputStream

Reader

Wrtier

ByteArrayInputStream

StringBufferInputStream

FileInputStream

SequenceInputStream

FilterInputStream

PipedInputStreamObjectInputStream

ByteArrayOutputStream

StringBufferOutputStream

FileOutputStream

SequenceOutputStream

FilterOutputStream

PipedOutputStreamObjectOutputStream

BufferedInputStreamDataInputStream

LineNumberInputStreamPushbackInputStream

BufferedOutputStreamDataOutputStream

PrintStream

BufferedWriter

StringWriter

CharArrayWriter

PrintWriter

FilterWriter

PipedWriterOutputStreamWriter FileWriter

BufferedReader

StringReader

CharArrayReaderFilterReader

PipedReaderInputStreamReader FileReader

檔案作業

檔案作業 (java.io.File)boolean canRead()--- 此目錄或檔案是否可讀 ?boolean canWrite() --- 此目錄或檔案是否可寫 ?boolean exists() --- 此目錄或檔案是否存在 ?boolean isFile() --- 是否為檔案 ?boolean isDirectory() --- 是否為目錄 ?boolean isAbsolute()-- 是否為絶對路徑 ?String getAbsolutePath()— 取得絶對路徑String getName()-- 取得檔案或目錄的名稱String getPath()-- 取得檔案或目錄的路徑String length()-- 取得檔案長度long lastModified()-- 取得檔案或目錄的最後修正時間String[] list()-- 取得目錄下的檔案列表

import java.io.*;

class ExFile { public static void main ( String args[] ) throws Exception { File myFile = new File( args[0] );

if ( !myFile.exists() || !myFile.canRead( ) ) { System.out.println( "Can't read " + myFile ); return; }

if ( myFile.isDirectory( ) ) { String [] files = myFile.list( ); for (int i=0; i< files.length; i++) System.out.println( files[i] ); } else try { FileReader fr = new FileReader ( myFile ); BufferedReader in = new BufferedReader( fr ); String line; while ((line = in.readLine( )) != null) System.out.println(line); System.out.println(myFile+"'s length="+myFile.length()); } catch ( FileNotFoundException e ) { System.out.println( "File Disappeared" ); } }}

Reader and Writer

各種編碼方式( 如 ASCII…)

Java 本身字元集Reader

Writer

以 Unicode 字元為基準 ,藉以轉換各種不同的字元集

OutputStreamWriterInputStreamReader Writer and Reader 抽象類別

FileOutputStream fos=new FileOutputStream(“book.txt”);

OutputStreamWriter bookWriter=new OutputStreamWriter(fos,”8859_7”);

String text=“\u03B1\u03C1\u03C4\u03B7”;

bookWriter.write(text,0,text.length());

編碼方式 :ASCII 加希臘文

255,241,229,244,231 五個位元組

五個 unicode 字元 (十個位元組 )

import java.io.*;

public class ExOSW{

public static void main(String[] args){

String encoding=System.getProperty("file.encoding");

String lineSpearator=System.getProperty("line.separator","\r\n");

OutputStream target=null;

try{

target=new FileOutputStream(args[0]);

}

catch(Exception e){}

System.out.println(encoding);

OutputStreamWriter osw=null;

try{

osw=new OutputStreamWriter(target,encoding);

}

catch(Exception ee){}

try{

osw.write("Test");

osw.close();

}

catch(Exception eee){}

}

}

import java.io.*;

public class ExConverter{

public static void main(String[] args){

if(args.length<2){

System.out.println("usage: java ExConverter infile_encoding outfile_encoding infile outfile"); }

try{

File infile=new File(args[2]);

File outfile=new File(args[3]);

FileInputStream fin=new FileInputStream(infile);

FileOutputStream fout=new FileOutputStream(outfile);

InputStreamReader isr=new InputStreamReader(fin,args[0]);

OutputStreamWriter osw=new OutputStreamWriter(fout,args[1]);

while(true){

int c=isr.read();

if(c==-1) break;

osw.write(c);

}

osw.close();

isr.close();

}catch(Exception e){}

}

}

ABC ABC

位元組一 位元組二

字元 ABC