java ui - smith.n studio

Upload: smith-nguyen-studio

Post on 06-Apr-2018

253 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Java UI - Smith.N Studio

    1/49

    1

    a. CC THNH PHN CA AWTCc iu khin c bn: Buttons, Checkboxes, Choices, Lists, Menus, and Text FieldsCc lp Button, Checkbox, Choice, List, MenuItem, and TextField cung cp nhng cng c iu khinc bn. y l nhng cc ph bin nht ngi s dng xy dng mt chng trnh JAVA. Khingi s dng kch hot mt trong nhng iu khin trn, v d nh khi nhp chut vo mt nt haykhi nhn phm trong mt hp Text th n s thng bo mt s kin (ACTION_EVENT). Mt i tngcha iu khin c th p tr s kin bng vic s dng phng thc action()

    Cc cng c khc ly thng tin u vo ca ngi s dng: Sliders, Scrollbars, and Text AreasKhi nhng iu khin c bn khng cn thch hp na, bn c th s dng cc lp Scrollbar andTextArea lp d liu ngi s dng nhp vo. Lp Scrollbar c s dng cho c hai chc nng:thanh cun v con trc. Scrollbars khng c t ng nm trong Lists, Text Areas v trong nhngi tng ScrollPane.Lp TextArea ch n gin cung cp vng hin th hay cho php sa mt vi dng vn bnTo mt thnh phn theo mun: CanvasesLp Canvas cho php bn vit mt thanh phn theo mnh. Vi cc lp con ca Canvas, bn c th vcc hnh nh nh mnh ra mn hnhThnh phn LabelsLabel ch n gin hin th mt ding vn bn khng th chn laCc i tng cha: Windows, Panels, and Scroll PanesAWT cung cp 3 kiu i tng cha, tt c c thc hin nh cc lp con ca lp Cotainer. Lp con

    Window (Dialog, FileDialog, v Frame) cung cp nhng ca s dng cha cc thnh phn. Panel ddng nhm cc thnh phn trong mt vng ca ca s. ScrollPane cng ging nh Panel, nhng nc bit hn: n hin th mt thnh phn ln khng c gii hn v khng gian, thng thng dngthanh cun iu khin hin th mt phn no ca thnh phnFrames to mt ca s kh mnh, khc vi cc ca s do Dialogs to ra, cc ca s do Dialogs to ra sph thuc trn ca s do Frames to raB. CC LP AWT KHCAWT cha nhiu thnh phn khc. N cha cc lp c lin quan n vic v v nm bt s kin. Phnny chng ta tho lun v cc lp ca AWT c trong gi java.awt. AWT cha hai gi khc ljava.awt.image v java.awt.peer m hu ht cc chng trnh khng s dng n. Lp v giao din trongnhng gi ny s c cp n khi cn thitGi java.awt mt vi lp layout manager. Gi java.awt cung cp vi lp v kch thc v hnh dng.Lp Shape bao gm Point, Rectangle, and Polygon.

    Lp Color class rt thch hp cho vic miu t v thao cc mu sc. N nh ngha cc hng s cho ccmu c dng ph bin nh Color.black. Trong khi mu s dng ph bin theo ng dng RGB (red-green-blue), th n cng c th hiu c mu inh dang theo HSB (hue-saturation-brightness).Lp Image cung cp cch trnh din d liu nh. Mt ng dng c th ly nhng i tng Image chocc nh GIF v JPEG bng cch dng phng thc getImage().

    1. S DNG CC THNH PHN, CC KHI XY DNG MT GUI a. S dng cc thnh phn ca AWTHnh v sau cho thy h thng phn cp c tnh tha k cho cc lp thnh phn ca AWT.

    Object

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    2/49

    2

    |MenuComponent

    |

    +------------+| |

    MenuItem MenuBar|

    +----+| |

    Menu CheckboxMenuItemCc quy tc chung khi s dng cc thnh phnLm th no thm mt thnh phn vo mt i tng chaKhi bn c bi ny, nn ch . Bi khng c thnh phn no ngoi tr ca s t hin th trn mn hnhc. Trc ht bn phi thm n vo mt i tng cha. Bn thn i tng cha ny l mt thnhphn, cng c th c thm vo i tng cha khc. Windows cng nh Frames and Dialogs n lnhng i tng cha mc cao nht; l nhng thnh phn khng thm vo c i tng chakhc.Lp Container ng ngha 3 phng thc cho vic thm thnh phn vo trong no: mt phng thcadd() mt thng s v 2 phng thc add() c hai thng s. N ph thuc vo cch b tr ca mt itng cha ang dng.

    Phng thc add() mt thng s thng thng ch yu cu ch nh thnh phn thm vo. Phng thcadd() 2 thng s. Phng thc 2 thng s u tin cho php bn thm mt thng s ch nh v tr mthnh thnh phn c thm vo. Thng s th 2 ca phng thc add () 2 thng s th 2 ch nhthnh phn c thm vo Container. Thng s u l chui ph thuc.Ch :Thm mt thnh phn vo Container l chuyn thnh phn t Container ang cha n sangContainer khc. V th khng th c mt thnh phn trong 2 Container, ngay c khi 2 Container khng xut hin cng mt lc trn mn hnh.Cc lp thnh phn cung cp ci gTt c cc thnh phn ngoi tr Menus c thc thi nh nhng lp con ca lp Component. N thak phn ln cc chc nng ca lp nyCc h tr c bn cho vic vLp Component cung cp cc phng thc paint(), update(), v repaint() h tr cho vic vCc s kin

    Lp Component nh ngha mt phng thc handleEvent() cho mc ch chung v mt nhm ccphng thc nh action() nm bt cc s kin xc nh. Lp Component cng nhn s iu khin tbn phm.iu khin hnh thc: fontLp Component cung cp cc phng thc ly v xc lp font, v ly thng tin v Font hin tiiu khin hnh thc: muLp Component cung cp cc phng thc sau ly v xc lp mu nn v mu ch :setForeground(Color), getForeground(), setBackground(Color), and getBackground(). Mu ch l mudng cho tt c vn bn c trong thnh phn. mu nn l mu ng sau vn bn hoc nhNm bt nhLp Component cung cp nn tng cho vic hin th nh. Lu rng phn ln cc thnh phn khnghin th c nh. Canvases v hu ht cc Container c th hin th c nh.iu khin kch thc v v tr trn mn hnh

    Phng thc preferredSize() v minimumSize() cho php mt thnh phn thit k cc thnh phn vikch thc thch hp v nh nht.Lm th no thay i hnh thc v cch thc tc ng ca mt thnh phnHnh thc ca hu ht cc thnh phn u ph thuc vo Platform. Buttons h thng Motif khc sovi Buttons h thng Macintosh.Bn khng th d dng thay i hon ton hnh thc ca cc thnh phn. bn ch c th thay i mtphn nh hnh thc ca cc thnh phn m thi nh l thay i Font v mu nn.Mc d bn khng th thay i hon ton hnh thc ca cc thnh phn, nhng bn c th thay i cchc x ca n. V d, nu ch c gi tr s mi ph hp vi Textfied, th bn c th thc thi lp conTextField kim tra mi gi tr nhp vo ca bn phm, khng nhn nhng gi tr khng phi l s.

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    3/49

    3

    S dng ButtonsButton l mt cng c iu khin n gin pht ra mt s kin hnh ng khi ngi s dng nhnvo .Hnh thc ca Buttons trn mn hnh ph thuc vo nn m n ang chy v n c nhn c s tcng hay khng. Nu bn mun cc Button ca chng trnh ging nhau mi nn hoc cho tht cbit, bn nn to mt lp con Canvas lm c ngoi hnh ca cc nt theo mun; bn khng thdng lp con Button thay i ngoi hnh ca cc nt. nhng nt ca hnh thc ca mt Button c th

    thay i c l Font v chui hin th , mu nn v mu ch ca n, v v n c th c tc ng haykhng.Sau y l mt Applet hin th 3 Button. Khi bn kch chut vo nt bn tri, n s lm cho nt giakhng nhn c s tc ng (v n lm cho n khng th nhn s tc ng) v lm cho nt phi nhnc s tc ng. Khi kch chut vo nt bn phi, n kch hot s hot ng ca nt gia v nt triv lm cho n s khng nhn c s tc ng.//In initialization code:

    b1 = new Button();

    b1.setLabel("Disable middle button");

    b2 = new Button("Middle button");

    b3 = new Button("Enable middle button");

    b3.disable();. . .

    public boolean action(Event e, Object arg) {Object target = e.target;

    if (target == b1) { //They clicked "Disable middle button"

    b2.disable();

    b1.disable();

    b3.enable();

    return true;

    }

    if (target == b3) { //They clicked "Enable middle button"

    b2.enable();b1.enable();

    b3.disable();

    return true;

    }

    return false;

    }

    S dng CanvasesLp Canvas tn ti nh l mt lp con. N khng lm g cho bn thn n; n ch cung cp cho bn cchthc thi cc thnh phn t to. V d, Canvases rt thun li cho vic hin th cc vng ca hnh nh,trong bt c trng hp no bn cng c th nm bt c cc s kin xy ra trong sut thi gian hinth nh.Canvases cng thun tin khi iu khin -- Button, for example n khng ging nh s thc th mcnh ca mt iu khin. V l rng bn khng th thay i hnh thc ca cc iu khin chun bngcc lp con m cc thnh phn tng ng vi no (v d ch Button), do bn phi thc thi lp conCanvas bn c th c hnh thc nh mun v cch c x tng t nh s thc thi mc nh caiu khin.Khi thc thi mt lp con Canvas , cn thn khi thc thi nhng phng thc minimumSize() vpreferredSize() mang li kch thc ng n cho cc Canva. Mc khc, ph thuc vo cch b trica cc i tng cha cc Canva, cc Canva c th c kch thc qu nh, c khi khng thy cngnn.Sau y l mt Applet s dng 2 trng hp ca lp con Canvas subclass: ImageCanvas.

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    4/49

    4

    Sau y l mt on m lnh ca ImageCanvas. Bi v d lii nh c ti v khng ng b nnImageCanvas khng cho bit c ln ca n cho n vi giy sau khi n to c. V l do ny,ImageCanvas dng rng v cao ban u to nh cho n khi kch thc ca nh hon ton xcnh c th n mi thay i kch thc ca n.class ImageCanvas extends Canvas {

    Container pappy;

    Image image;

    boolean trueSizeKnown = false;Dimension minSize;

    int w, h;

    public ImageCanvas(Image image, Container parent,

    int initialWidth, int initialHeight) {

    if (image == null) {

    System.err.println("Canvas got invalid image object!");

    return;

    }

    this.image = image;

    pappy = parent;

    w = initialWidth;

    h = initialHeight;

    minSize = new Dimension(w,h);

    }

    public Dimension preferredSize() {

    return minimumSize();

    }

    public synchronized Dimension minimumSize() {return minSize;

    }

    public void paint (Graphics g) {

    if (image != null) {

    if (!trueSizeKnown) {int imageWidth = image.getWidth(this);

    int imageHeight = image.getHeight(this);

    if ((imageWidth > 0) && (imageHeight > 0)) {

    trueSizeKnown = true;

    //Ooh... component-initiated resizing.

    w = imageWidth;

    h = imageHeight;minSize = new Dimension(w,h);

    resize(w, h);

    pappy.layout();

    pappy.repaint();

    }

    }

    g.drawRect(0, 0, w - 1, h - 1);

    g.drawImage(image, 0, 0, this);

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    5/49

    5

    }

    }

    }

    S dng CheckboxesLp Checkbox cung cp nhng checkbox 2 trng thi ca Checkbox c th l on hoc off. Khingi s dng nhn chut vo Checkbox, trng thi ca Checkbox s thay i v tr v mt s kin.Mc khc, n cng nhm cc thnh phn ngi dng c th chn nh l Choices, Lists, v Menus.

    Nu bn mun to mt nhm Checkbox m ch c mt Checkbox trong mt thi im trng thi onth bn c th thm vo mt i tng CheckboxGroup gim st cc Checkbox .V d :Panel p1, p2;

    Checkbox cb1, cb2, cb3; //These are independent checkboxes.

    Checkbox cb4, cb5, cb6; //These checkboxes are part of a group.

    CheckboxGroup cbg;

    cb1 = new Checkbox(); //Default state is "off" (false).

    cb1.setLabel("Checkbox 1");

    cb2 = new Checkbox("Checkbox 2");

    cb3 = new Checkbox("Checkbox 3");

    cb3.setState(true); //Set state to "on" (true).

    . . .cbg = new CheckboxGroup();

    cb4 = new Checkbox("Checkbox 4", cbg, false); //initial state: off (false)

    cb5 = new Checkbox("Checkbox 5", cbg, false); //initial state: offcb6 = new Checkbox("Checkbox 6", cbg, false); //initial state: off

    S dng ChoicesLp Choice cung cp mt thc n la chn, truy nhp bng mt nt c bit. ngi s dng nhnnt v n s lit ra mt menu v bn c th chn mt th trong menu . Khi ngi dng chn, ns phn hi mt s kin.

    V d ://...Where instance variables are defined:

    Choice choice; //pop-up list of choices

    //...Where initialization occurs:choice = new Choice();

    choice.addItem("ichi");

    choice.addItem("ni");

    choice.addItem("san");

    choice.addItem("yon");

    label = new Label();

    setLabelText(choice.getSelectedIndex(), choice.getSelectedItem());

    . . .

    public boolean action(Event e, Object arg) {

    if (e.target instanceof Choice) {

    setLabelText(choice.getSelectedIndex(), (String)arg);

    return true;

    }

    return false;

    }

    }

    S dng DialogsAWT cung cp nhng h tr cho dialogs l nhng ca s ph thuc vo nhng ca s khcvi lpDialog. N cung cp nhng lp con hu ch nh : FileDialog, cung cp mt ca s m bn c th mhoc lu file.

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    6/49

    6

    Mt yu t phn bit Dialog v cc ca s thng thng khc l Dialog ph thuc vo cc ca skhc (Frame). Khi ca s ng th cc Dialog ph thc n cng bin mt. Khi nhng ca s cthu nh cc Dialog ph thuc n s khng xut hin trn mn hnh. Khi ca s c tr v kch thcthng thng th cc Dialog s hin th ra mn hnh. AWT t ng cung cp cc hnh thc ny chobn.Dialogs c th l modal. Modal dialogs i hi s chm sc k lng ca ngi s dng, chng li vicngi s dng lm bt c ci g khc trn ng dng cho n khi Dialog c gt b

    V d :class SimpleDialog extends Dialog {TextField field;DialogWindow parent;

    Button setButton;

    SimpleDialog(Frame dw, String title) {

    super(dw, title, false);

    parent = (DialogWindow)dw;

    ...//Create and add components, such as the set button.

    //Initialize this dialog to its preferred size.

    pack();}

    public boolean action(Event event, Object arg) {

    if ( (event.target == setButton)

    | (event.target instanceof TextField)) {

    parent.setText(field.getText());

    }

    field.selectAll();

    hide();

    return true;

    }}

    S dng FramesLp Frame cung cp nhng ca s cho applets v applications. Mi ng dng phi c t nht 1 Frame.Nu mt ng dng c 1 ca s ph thuc vo ca s khc th bn nn dng Dialog th ay v dng Framecho ca s ph thuc . ng tic l applets khng th dng tt dialogs, v vy ngi s dng thngdng Frame.V d:public class MenuWindow extends Frame {

    boolean inAnApplet = true;

    TextArea output;

    public MenuWindow() {

    ...//This constructor implicitly calls the Frame no-argument

    //constructor and then adds components to the window.

    }

    public boolean handleEvent(Event event) {

    if (event.id == Event.WINDOW_DESTROY) {

    if (inAnApplet) {

    dispose();

    } else {

    System.exit(0);

    }

    }

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    7/49

    7

    return super.handleEvent(event);

    }

    . . .

    public static void main(String args[]) {

    MenuWindow window = new MenuWindow();

    window.inAnApplet = false;

    window.setTitle("MenuWindow Application");window.pack();

    window.show();

    }

    }

    S dng LabelsL thnh phn n gin nht ca UI Components, l mt chui k t c th c dng lm nhn chocc UI Components khc. Labels khng sa c, n ch lm nhn cho cc UI Components khc trnmn hnhLi im ca Lables so vI cc chuI k t thng thng khc l:Bn khng phI t v lI Labels. Labels l nhng thnh phn ca AWT v AWT theo di v lm vic

    Labels tun theo s sp xp ca Panel cha n v c th cn chnh vi cc UI Components khcLabels cha chui khng th sa i c m ch dng m t cc thnh phn khc ca AWT to mt Label, s dng mt trong cc cu trc sau:Label() to mt nhn rng, vi chui c canh chnh bn tri.Label(String) to mt chui c ni dung l String cung c canh chnh bn tri.Label(String,int) to mt nhn c ni dung l StringTham s Int bao gm:Label.RIGHT: chui c canh chnh bn phiLabel.LEFT : chui c canh chnh bn triLabel.CENTER: chui c canh chnh giaBn c th thay i font ca Label bng phng thc setFont()Sau y l mt v d minh ho s dng Label

    import java.awt.*;public class LabelTest extends java.applet.Applet {

    public void init() {

    setFont(new Font ("Helvetica", Font.BOLD, 14));setLayout(new GridLayout(3,1));

    add(new Label("aligned left", Label.LEFT));

    add(new Label("aligned center", Label.CENTER));

    add(new Label("aligned right", Label.RIGHT));

    }

    }

    S dng ListsLp List cung cp mt vng c th cun c m trong n cha cc chui vn bn c th chn c(mt dng mt chui). Ngi s dng c th chn bn cch kch chut. Lists c th cho php chnnhiu hay ch c mt s la chn trong mt thi im.V d :

    ...//Where instance variables are declared:TextArea output;

    List spanish, italian;

    ...//Where initialization occurs:

    //Build first list, which allows multiple selections.

    spanish = new List(4, true); //prefer 4 items visible

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    8/49

    8

    spanish.addItem("uno");

    spanish.addItem("dos");

    spanish.addItem("tres");

    spanish.addItem("cuatro");

    spanish.addItem("cinco");

    spanish.addItem("seis");

    spanish.addItem("siete");

    //Build second list, which allows one selection at a time.

    italian = new List(); //Defaults to none visible, only one selectableitalian.addItem("uno");

    italian.addItem("due");

    italian.addItem("tre");

    italian.addItem("quattro");

    italian.addItem("cinque");

    italian.addItem("sei");

    italian.addItem("sette");

    . . .

    public boolean action(Event e, Object arg) {if (e.target instanceof List) {

    String language = (e.target == spanish) ?"Spanish" : "Italian";

    output.appendText("Action event occurred on \""

    + (String)arg + "\" in "

    + language + ".\n");

    }

    return true;

    }

    public boolean handleEvent(Event e) {if (e.target instanceof List) {

    List list = (List)(e.target);String language = (list == spanish) ?

    "Spanish" : "Italian";

    switch (e.id) {

    case Event.LIST_SELECT:int sIndex = ((Integer)e.arg).intValue();

    output.appendText("Select event occurred on item #"

    + sIndex + " (\""

    + list.getItem(sIndex) + "\") in "

    + language + ".\n");

    break;

    case Event.LIST_DESELECT:

    int dIndex = ((Integer)e.arg).intValue();

    output.appendText("Deselect event occurred on item #"+ dIndex + " (\""

    + list.getItem(dIndex) + "\") in "

    + language + ".\n");

    }

    }

    return super.handleEvent(e);

    }

    S dng Menus

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    9/49

    9

    Applet sau cho thy nhiu nt c trng ca menu ging nh menu bn s dng. Ca s a ra mtthanh menu (Menu Bar) cha nm menu. Mi menu cha mt hoc nhiu menu conMenu ch tn ti trn Menu Bar v Menu Bar ch tn ti khi n gn vi nhng ca s (c bit lFrame)AWT cung cp nhng lp con MenuComponent sau h tr menu:MenuItemCheckboxMenuItem

    MenuMenuBar

    y l on m ch ra cc phng thc, c x ca menu:public class MenuWindow extends Frame {

    . . .

    public MenuWindow() {

    MenuBar mb;

    Menu m1, m2, m3, m4, m4_1, m5;

    MenuItem mi1_1, mi1_2, mi3_1, mi3_2, mi3_3, mi3_4,

    mi4_1_1, mi5_1, mi5_2;

    CheckboxMenuItem mi2_1;

    ...//Add the output displayer to this window...

    //Build the menu bar.

    mb = new MenuBar();setMenuBar(mb);

    //Build first menu in the menu bar.

    //Specifying the second argument as true

    //makes this a tear-off menu.

    m1 = new Menu("Menu 1", true);

    mb.add(m1);

    mi1_1 = new MenuItem("Menu Item 1_1");

    m1.add(mi1_1);mi1_2 = new MenuItem("Menu Item 1_2");

    m1.add(mi1_2);

    //Build help menu.

    m5 = new Menu("Menu 5");

    mb.add(m5); //just setting the help menu doesn't work; must add itmb.setHelpMenu(m5);

    mi5_1 = new MenuItem("Menu Item 5_1");

    m5.add(mi5_1);

    mi5_2 = new MenuItem("Menu Item 5_2");

    m5.add(mi5_2);

    //Build second menu in the menu bar.

    m2 = new Menu("Menu 2");

    mb.add(m2);mi2_1 = new CheckboxMenuItem("Menu Item 2_1");

    m2.add(mi2_1);

    //Build third menu in the menu bar.

    m3 = new Menu("Menu 3");

    mb.add(m3);

    mi3_1 = new MenuItem("Menu Item 3_1");

    m3.add(mi3_1);

    mi3_2 = new MenuItem("Menu Item 3_2");

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    10/49

    10

    m3.add(mi3_2);

    m3.addSeparator();

    mi3_3 = new MenuItem("Menu Item 3_3");

    m3.add(mi3_3);

    mi3_4 = new MenuItem("Menu Item 3_4");

    mi3_4.disable();

    m3.add(mi3_4);

    //Build fourth menu in the menu bar.

    m4 = new Menu("Menu 4");mb.add(m4);

    m4_1 = new Menu("Submenu 4_1");

    m4.add(m4_1);

    mi4_1_1 = new MenuItem("Menu Item 4_1_1");

    m4_1.add(mi4_1_1);

    }

    . . .

    public boolean action(Event event, Object arg) {

    String str = "Action detected";

    if (event.target instanceof MenuItem) {MenuItem mi=(MenuItem)(event.target);

    str += " on " + arg;if (mi instanceof CheckboxMenuItem) {

    str += " (state is "

    + ((CheckboxMenuItem)mi).getState()

    + ")";

    }

    MenuContainer parent = mi.getParent();

    if (parent instanceof Menu) {

    str += " in " + ((Menu)parent).getLabel();

    } else {str += " in a container that isn't a Menu";

    }}

    str += ".\n";

    ...//Display the string in the output area...

    return false;}

    S dng PanelsLp Panel l mt lp con Container. Bn c th s dng n nm bt cc Component, hoc bn c thnh ngha mt lp con iu khin cc chc nng c bit.Lp Applet l mt lp con Panel vi s mc ni c bit cho cc Browser hoc khung nhn cho Applet.Sau y l mt v d dng Panel cha mt vi Component :Panel p1 = new Panel();

    p1.add(new Button("Button 1"));

    p1.add(new Button("Button 2"));p1.add(new Button("Button 3"));

    Sau y l mt v d ca lp con Panel dng v mt khung.class FramedArea extends Panel {

    public FramedArea(CoordinatesDemo controller) {

    ...//Set the layout manager.

    //Add any Components this Panel contains...

    }

    //Ensure that no Component is placed on top of the frame.

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    11/49

    11

    //The inset values were determined by trail and error.

    public Insets insets() {

    return new Insets(4,4,5,5);

    }

    //Draw the frame at this Panel's edges.

    public void paint(Graphics g) {

    Dimension d = size();Color bg = getBackground();

    g.setColor(bg);

    g.draw3DRect(0, 0, d.width - 1, d.height - 1, true);

    g.draw3DRect(3, 3, d.width - 7, d.height - 7, false);

    }

    }

    S dng ScrollbarsScrollbars c hai cch s dng:Scrollbar c th hot ng nh mt con trt cho ngi dng li ko xc lp gi tr. Nh iu khin cun mt vung(Scroll pane). Scrollbars trong Scroll panes cho ngi dng chnchnh xc vng cn hin th.

    to mt scrollbar, bn cn to mt thnh phn ca lp Scrollbar. Bn phi xc lp cc gi tr ban uca Scrollbar bng vic gi phng thc setValues() trc khi Scrollbar hin th ln mn hnh.int orientationCh cho bit hoc c th thanh nm ngang hoc c th l nm ng. Gi tr ch nh lScrollbar.HORIZONTAL hoc Scrollbar.VERTICAL.int valueGi tr khi u ca scrollbar, cho vng c th iu khin ca Scrollbars, c ngha l gi tr x (chothanh cun ngang) v gi tr y (cho thanh cun ng) ca vng cun m c th thy u tin khi nhin th.int visibleKch thc ca phn hin th ca vng c th cun.int minimumGi tr nh nht ca scrollbar can have, thng l 0.int maximumGi tr ln nht ca scrollbar.Sau y l hnh v minh ho ngha ca cc gi tr trn:

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    12/49

    12

    Sau y l on m cho Aplet trn.import java.awt.*;

    import java.applet.*;

    import java.net.URL;

    class ScrollableCanvas extends Canvas {

    Image image;

    int tx = 0;

    int ty = 0;

    Dimension preferredSize;

    ScrollableCanvas(Image img, Dimension prefSize) {

    image = img;preferredSize = prefSize;

    }

    public Dimension minimumSize() {

    return new Dimension(10, 10);

    }

    public Dimension preferredSize() {

    return preferredSize;

    }

    public void paint(Graphics g) {g.translate(-tx, -ty);

    g.drawImage(image, 0, 0, getBackground(), this);

    }

    }

    public class ImageScroller extends Applet {

    Scrollbar vert;

    Scrollbar horz;

    ScrollableCanvas canvas;

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    13/49

    13

    boolean inAnApplet = true;

    String imageFile = "../images/people.gif";

    Dimension imageSize = new Dimension(600, 320);

    Dimension preferredImageSize = new Dimension(300, 100);

    //This method assumes this Applet is visible.

    public void init() {

    Image img;

    if (inAnApplet) {img = getImage(getCodeBase(), imageFile);

    } else {

    img = Toolkit.getDefaultToolkit().getImage(imageFile);

    }

    canvas = new ScrollableCanvas(img, preferredImageSize);

    //Create horizontal scrollbar.

    horz = new Scrollbar(Scrollbar.HORIZONTAL);

    //Create vertical scrollbar.

    vert = new Scrollbar(Scrollbar.VERTICAL);

    //Add Components to the Applet.setLayout(new BorderLayout());

    add("Center", canvas);

    add("East", vert);

    add("South", horz);

    validate();

    //Now that we've validated, then assuming this Applet is

    //visible, the canvas size is valid and we can adjust the//scrollbars to match the image area. [CHECK]

    resizeHorz();resizeVert();

    }

    public boolean handleEvent(Event evt) {switch (evt.id) {

    case Event.SCROLL_LINE_UP:

    case Event.SCROLL_LINE_DOWN:

    case Event.SCROLL_PAGE_UP:

    case Event.SCROLL_PAGE_DOWN:

    case Event.SCROLL_ABSOLUTE:

    if (evt.target == vert) {

    canvas.ty = ((Integer)evt.arg).intValue();

    canvas.repaint();}

    if (evt.target == horz) {

    canvas.tx = ((Integer)evt.arg).intValue();

    canvas.repaint();

    }

    }

    return super.handleEvent(evt);

    }

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    14/49

    14

    //Don't call this until the canvas size is valid.

    void resizeHorz() {

    int canvasWidth = canvas.size().width;

    if (canvasWidth

  • 8/3/2019 Java UI - Smith.N Studio

    15/49

    15

    0,

    //maximum image y to specify:

    imageSize.height - canvasHeight);

    //"visible" arg to setValues() has no effect after scrollbar is visible.

    vert.setPageIncrement((int)(canvasHeight * 0.9));

    return;

    }

    public void paint(Graphics g) {//This method probably was called due to applet being resized.

    resizeHorz();

    resizeVert();

    return;

    }

    }

    S dng Scroll PanesScrollPane qun l thnh phn con n l, ch hin th phn m khng gian cho php.Mc nh, thanh cun ca Scroll pane ch hin th khi cn thit. V d, nu Scoll pane rng hin

    th thnh phn con ca n theo b ngang th thyanh cun ngang ca Scoll pane s khng cn thit vmc nh thanh cun ngang ca Scoll pane s khng xut hin. Hnh sau cho thy mt Aplet c mtScoll pane, n c c hai thanh cun.

    Sau y l on m to mt Scoll pane v t thnh phn con vo trong :ScrollPane sp1 = new ScrollPane();

    sp1.add(aComponent);

    Khi bn to mt mt Scoll pane, bn c th xc lp thng s xc nh khi no hin th thanh cun, sdng mt trong 3 gi tr sau:SCROLLBARS_AS_NEEDEDGi tr mc nh, hin th thanh cun khi cn thit.SCROLLBARS_ALWAYSLun lun hin th thanh cun.SCROLLBARS_NEVERKhng bao gi hin th thanh cun. Bn nn chn gi tr ny khi bn khng mun ngi s dng trctip iu khin phn m thnh phn con hin th.y l mt v d xc lp quyn hin th thanh cun:ScrollPane sp2 = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);

    S dng TextAreas and TextFieldsLp TextArea v TextField hin th vn bn c th la chn v thay th c. Bn c th dng lp conTextArea v TextField thi hnh cc thao tc nh kint ra li nhp liu. Nh vi mi Component, bnc th xc lp mu nn v mu ch ca TextAreas and TextFields. Tuy nhin bn khng th thay ihnh thc c bn ca n.TextArea v TextField l cc lp con ca TextComponent. T TextComponent n c th tha k ccphng thc cho php chng xc lp v ly gi tr c chn.V d ://Where instance variables are defined:TextField textField;

    TextArea textArea;

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    16/49

    16

    public void init() {

    textField = new TextField(20);

    textArea = new TextArea(5, 20);

    textArea.setEditable(false);

    ...//Add the two components to the panel.}

    public boolean action(Event evt, Object arg) {

    String text = textField.getText();textArea.appendText(text + "\n");

    textField.selectAll();

    return true;

    }

    Lp cha TextComponent cung cp cc phng thc getText(), setText(), setEditable(), v selectAll()dng trong on m trn. N cng cung cp cc phng thc sau :: getSelectedText(), isEditable(),getSelectionStart(), v getSelectionEnd(). N cng cung cp phng thc select() cho bn c thchn on vn bn t v tr u v v tr cui.Lp TextField c 4 cu trc: TextField(), TextField(int), TextField(String), and TextField(String, int).gi tr int xc lp s ct trong TextField. Gi tr String xc lp chui m xut hin ban u trong

    TextField. Lp TextField cng cung cp cc phng thc sau:int getColumns()Tr v s ct trong Text Field.setEchoChar()Xc lp lai k t hin th, n rt c ch cho vic nhp mt khu.char getEchoChar()boolean echoCharIsSet()cc phng thc trn cho bit thng tin v k t hin th.Ging nh lp TextField, lp TextArea cng c 4 cu trc: TextArea(), TextArea(int, int),TextArea(String), and TextArea(String, int, int). Gi tr Int xc lp s hng v s ct trong TextArea.Gi tr String xc lp chui ban u cho TextArea.Lp TextArea cung cp phng thc appendText() dng trong on m trn. N cng cung cp ccphng thc sau:

    int getRows(), int getColumns()Tr v s hng v s ct trong TextArrea.void insertText(String, int)Chn mt chui vo vt tr Int.void replaceText(String, int, int)Thay th on vn bng t v tr int n v tr int bng chui String.

    b. Cc kiu s kin mi ca AWT Gii thiu cc kiu s kin mi ca AWTCc s kin (events) c pht ra bi ngun s kin. Mt hoc nhiu listeners c th ng k cc thngbo v cc Event. i khi cc kiu ny cn c gi l delegatioMt v d n ginSau y l on m thc thi s nm b s kin cho mt Button:

    public class Beeper ... implements ActionListener {...

    //where initialization occurs:

    button.addActionListener(this);

    ...

    public void actionPerformed(ActionEvent e) {

    ...//Make a beep sound...}

    }Mt v d v cc kiu s kin khc

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    17/49

    17

    Aplet sau hin th mt mt vng hnh ch nht v mt vng vn bn...

    //where initialization occurs:

    //Register for mouse events on blankArea and applet (panel).

    blankArea.addMouseListener(this);

    addMouseListener(this);

    }

    public void mousePressed(MouseEvent e) {

    saySomething("Mouse button press", e);}

    public void mouseReleased(MouseEvent e) {

    saySomething("Mouse button release", e);

    }

    public void mouseEntered(MouseEvent e) {

    saySomething("Cursor enter", e);

    }

    public void mouseExited(MouseEvent e) {saySomething("Cursor exit", e);

    }

    public void mouseClicked(MouseEvent e) {

    saySomething("Mouse button click", e);

    }

    void saySomething(String eventDescription, MouseEvent e) {

    textArea.append(eventDescription + " detected on "

    + e.getComponent().getClass().getName()

    + ".\n");textArea.setCaretPosition(maxInt); //hack to scroll to bottom

    }}

    S dng Adapters and Inner Classes nm bt cc s kinPhn ny hng dn bn s dng cc lp adapters v inner lm gim bt s ln xn trong on mca chng trnh bn.Hu ht cc giao din AWT listener, khng nh ActionListener, cha nhiu hoc mt phng thc. Vd, giao din MouseListener cha nm phng thc: mousePressed, mouseReleased, mouseEntered,mouseExited, v mouseClicked. D l bn ch quan tm v nhn chut, nu lp bn ang s dng thcthi MouseListener th bn phi thc thi tt c 5 phng thc.V d :MyClass implements MouseListener {

    ...

    someObject.addMouseListener(this);

    .../* Empty method definition. */

    public void mousePressed(MouseEvent e) {

    }

    /* Empty method definition. */

    public void mouseReleased(MouseEvent e) {

    }

    /* Empty method definition. */

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    18/49

    18

    public void mouseEntered(MouseEvent e) {

    }

    /* Empty method definition. */

    public void mouseExited(MouseEvent e) {

    }

    public void mouseClicked(MouseEvent e) {...//Event handler implementation goes here...

    }}ng tic l kt qu ca s la chn cc phng thc rng c th kh c v duy tr. gip bn trnhc cc ln xn vi nhng phng thc rng trong chng trnh, AWT cung cp lp adapterclasscho mi listener interface vi nhiu hn mt phng thc. s dng adapter, bn to mt lp con cho n, thay v phi thc thi mt listener interface./*

    * An example of extending an adapter class instead of

    * directly implementing a listener interface.

    */

    MyClass extends MouseAdapter {

    ...someObject.addMouseListener(this);

    ...public void mouseClicked(MouseEvent e) {

    ...//Event handler implementation goes here...}

    }Gi d bn mun vit mt applet, v bn mun Applet ca bn cha vi on m nm bt cc skin ca chut. T khi ngn ng Java khhong cho php a tha k th bn khng th m rng c 2 lpApplet and MouseAdapter. Gii php l nh ngha mt lp inner -- mt lp nm trong Aplet -- thatextends the MouseAdapter class,

    //An example of using an inner class.MyClass extends Applet {

    ...someObject.addMouseListener(new MyAdapter());

    ...

    class MyAdapter extends MouseAdapter {

    public void mouseClicked(MouseEvent e) {

    ...//Event handler implementation goes here...

    }

    }

    }

    Nm bt cc s kin ca AWT chunListener Interface Adapter Class Methods

    ActionListener none actionPerformedAdjustmentListener none adjustmentValueChanged

    ComponentListener ComponentAdapter

    componentHiddencomponentMovedcomponentResized

    componentShown

    ContainerListener ContainerAdaptercomponentAdded

    componentRemoved

    FocusListener FocusAdapter focusGained

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    19/49

    19

    focusLost

    ItemListener none itemStateChanged

    KeyListener KeyAdapter

    keyPressed

    keyReleasedkeyTyped

    MouseListener MouseAdapter

    mouseClicked

    mouseEnteredmouseExited

    mousePressedmouseReleased

    MouseMotionListener MouseMotionAdaptermouseDragged

    mouseMoved

    TextListener none textValueChanged

    WindowListener WindowAdapter

    windowActivated

    windowClosedwindowClosing

    windowDeactivated

    windowDeiconified

    windowIconifiedwindowOpened

    Cc s kin c to ra bi cc thnh phn ca AWT

    AWT Component

    Types of Events It Can Generate

    i

    adjustment component container focus item key mouse mouse motion

    Button X X X X X

    Canvas X X X X X

    Checkbox X X X X X X

    CheckboxMenuItem

    Note: This is not aComponent subclass!

    X

    Choice X X X X X X

    Component X X X X X

    Container X X X X X X

    Dialog X X X X X X

    Frame X X X X X X

    Label X X X X X

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    20/49

    20

    List X X X X X X

    MenuItemNote: This is not aComponent subclass!

    Panel X X X X X X

    Scrollbar X X X X X X

    ScrollPane X X X X X X

    TextArea X X X X X

    TextComponent X X X X X

    TextField X X X X X

    Window X X X X X XVit mt Action ListenerKhi ngi s dng kich chut vo Button, p chut vo ListItem, chn MenuItem, hoc nhn phmtrong TextField,mt s kin s xy ra. Kt qu l mt thng bo actionPerformed c gi i ntt c cc action listener v n ng k vi cc thnh phn c lin quan.Cc phng thc, s kin ca hnh ngGiao din ActionListener cha mt phng thc n, v do n khng c lp adapter tng ng.y l phng thc ActionListener c c:void actionPerformed(ActionEvent)

    Mt v d v nm bt cc s kin ca hnh ngMt v d n gin

    public class Beeper ... implements ActionListener {...//where initialization occurs:

    button.addActionListener(this);

    ...

    public void actionPerformed(ActionEvent e) {...//Make a beep sound...

    }

    }

    Vit mt Adjustment ListenerCc s kin Adjustment thng bo cho bn bit s thay i gi tr trong cc thnh phn. i tngAdjustable c mt gi tr nguyn, v n tr v cc cc s kin adjustment bt c khi no gi tr thayi. Ch c mt lp ca AWT thc thi Adjustable l lp Scrollbar.

    C 5 loi s kin adjustment:trackngi s dng hon ton thay i gi tr ca thnh phn.unit increment, unit decrementngi s dng ch biu th s thay di nh v gi tr ca thnh phn.block increment, block decrementngi s dng biu th s thay i gi tr ca thnh phn vi s lng ln.Cc phng thc s kin ca Adjustment Giao din Adjustment Listener cha mt phng thc n, v v th n khng c lp m phng tngng. Sau y l phng thc :

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    21/49

    21

    void adjustmentValueChanged(AdjustmentEvent)c gi bi AWT va sau khi thay i gi tr ca thnh phn.V d v Handling Adjustment Eventsclass ConversionPanel ... implements AdjustmentListener ... {

    ...

    Scrollbar slider;

    ...

    ConversionPanel(...) {...

    slider.addAdjustmentListener(this);}

    ...

    /** Respond to the slider. */

    public void adjustmentValueChanged(AdjustmentEvent e) {

    textField.setText(String.valueOf(e.getValue()));

    controller.convert(this);

    }

    ...

    }Lp AdjustmentEvent

    Phng thc adjustmentValueChanged c mt thng s: mt i tng AdjustmentEvent. LpAdjustmentEvent nh ngha cc phng thc sau:Adjustable getAdjustable()Tr v thnh phn m sinh ra s kin . Bn c th dng n thay v dng phng thc getSource.int getAdjustmentType()

    Tr v kiu ca adjustment c tm thy. gi tr tr v l mt trong nhng gi tr sau c nh nghatrong lp AdjustmentEvent: UNIT_INCREMENT, UNIT_DECREMENT, BLOCK_INCREMENT,BLOCK_DECREMENT, TRACK.int getValue()Tr v gi tr ca thnh phn ngay sau khi adjustment c tm thy. Vit mt Component Listenerl mt trong nhng s ken ca thnh phn c pht ra bi i tng Component ngay sau khi thnhphn mt i, lm n i, chuyn v tr hoc thay i kch thc

    Cc phng thc, s kin ca thnh phnGiao din ComponentListener v lp m phng tng ng, ComponentAdapter, cha 4 phng thc:void componentHidden(ComponentEvent)c gi bi AWT sau khi thnh phn bin mt bi phng thc setVisible.void componentMoved(ComponentEvent)

    c gi bi AWT sau khi thnh phn di chuyn, n quan h vi i tng cha n.void componentResized(ComponentEvent)c gi bi AWT sau khi thnh phn thay i kch thc.void componentShown(ComponentEvent)

    c gi bi AWT sau khi thnh phn xut hin bi phng thc setVisible.V d v Handling Component Eventspublic class ComponentEventDemo ... implements ComponentListener {

    ...

    //where initialization occurs:aFrame = new Frame("A Frame");

    ComponentPanel p = new ComponentPanel(this);

    aFrame.addComponentListener(this);

    p.addComponentListener(this);

    ...

    public void componentHidden(ComponentEvent e) {

    displayMessage("componentHidden event from "

    + e.getComponent().getClass().getName());

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    22/49

    22

    }

    public void componentMoved(ComponentEvent e) {

    displayMessage("componentMoved event from "

    + e.getComponent().getClass().getName());

    }

    public void componentResized(ComponentEvent e) {displayMessage("componentResized event from "

    + e.getComponent().getClass().getName());}

    public void componentShown(ComponentEvent e) {

    displayMessage("componentShown event from "

    + e.getComponent().getClass().getName());

    }

    }

    class ComponentPanel extends Panel ... {

    ...ComponentPanel(ComponentEventDemo listener) {

    ...//after creating the label and checkbox:label.addComponentListener(listener);

    checkbox.addComponentListener(listener);

    }

    ...

    }Lp ComponentEventMi mt phng thc ca s kin cc thnh phn c mt thng sn: i tng ComponentEventlp ComponentEvent nh ngha mt phng thc hay dng, getComponent, tr v thnh phn mpht ra s kin. Vit mt Container ListenerNhng s kin ca Container c pht ra ngay sau khi mt thnh phn c thm vo Container hocchuyn i khi Container.Cc phng thc, s kin ca ContainerGiao din ContainerListener v lp m phng tng ng, ContainerAdapter cha hai phng thc:void componentAdded(ContainerEvent)c gi sau khi mt thnh phn c thm vo Container.void componentRemoved(ContainerEvent)c gi sau khi mt thnh phn c chuyn i khi Container.V d v Handling Container Eventspublic class ContainerEventDemo ... implements ContainerListener ... {

    ...//where initialization occurs:

    buttonPanel = new Panel();

    buttonPanel.addContainerListener(this);

    ...public void componentAdded(ContainerEvent e) {

    displayMessage(" added to ", e);

    }

    public void componentRemoved(ContainerEvent e) {

    displayMessage(" removed from ", e);

    }

    void displayMessage(String action, ContainerEvent e) {

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    23/49

    23

    display.append(((Button)e.getChild()).getLabel()

    + " was"

    + action

    + e.getContainer().getClass().getName()

    + "\n");

    }

    ...

    }Lp ContainerEventMi phng thc ca Container Event c mt thng s n: i tng ContainerEvent. LpContainerEvent nh ngha hai phng thc thng dng sau:Component getChild()

    Tr v thnh phn c thm hay chuyn khi Container trong s kin ny.Container getContainer()

    Tar v Container sinh ra s kin ny. Vit mt Focus ListenerCc s kin Focus c pht ra khi mt thnh phn c hoc mt i s tp trung vo n.Cc phng thc, s kin ca FocusGaio din FocusListener v lp m phng tng ng, FocusAdapter, cha hai phng thc:void focusGained(FocusEvent)

    c gi sau khi thnh phn c s tp trung.void focusLost(FocusEvent)c gi sau khi thnh phn mt s tp trung.V d v Handling Focus Eventspublic class FocusEventDemo ... implements FocusListener ... {

    ...//where initialization occurs

    window = new FocusWindow(this);

    ...

    public void focusGained(FocusEvent e) {

    displayMessage("Focus gained", e);

    }

    public void focusLost(FocusEvent e) {

    displayMessage("Focus lost", e);}

    void displayMessage(String prefix, FocusEvent e) {display.append(prefix

    + ": "

    + e.getSource() //XXX

    + "\n");

    }

    ...

    }

    class FocusWindow extends Frame {

    ...public FocusWindow(FocusListener listener) {

    super("Focus Demo Window");

    this.addFocusListener(listener);

    ...

    Label label = new Label("A Label");label.addFocusListener(listener);

    ...

    Choice choice = new Choice();

    ...

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    24/49

    24

    choice.addFocusListener(listener);

    ...

    Button button = new Button("A Button");

    button.addFocusListener(listener);

    ...

    List list = new List();

    ...

    list.addFocusListener(listener);}

    }Lp FocusEventMi phng thc Focus Event c mt thng s n : i tng FocusEvent. Lp FocusEvent nhngha mt phng thc, isTemporary, tr v gi tr True khi s kin mt s tp trung l tm thi.Mi thng bo thng thng m bn gi ti i tng FocusEvent l getComponent (c nh nghatrong ComponentEvent), n tr v thnh phn gy ra s kin ny. Vit mt Item ListenerCc s kin ca Item c pht ra khi thc thi giao din ItemSelectable.Cc phng thc, s kin ca ItemGiao din ItemListener vh c mt phng thc, v vy n khng c lp m phng tng ng:void itemStateChanged(ItemEvent)

    c gi sau khi thay i trng thi ca thnh phn.V d v Handling Item Eventspublic void itemStateChanged(ItemEvent e) {

    if (e.getStateChange() == ItemEvent.SELECTED) {label.setVisible(true);

    } else {

    label.setVisible(false);

    }

    }

    Lp ItemEventMi phng thc ca Item event c mt thng s n: i tng ItemEvent. Lp ItemEvent nh nghacc phng thc sau:Object getItem()

    Tr v Item c tp trung trong s kin ny.ItemSelectable getItemSelectable()

    Tar v thnh phn pht ra s kin.int getStateChange()tr v trng thi mi ca Item. Lp ItemEvent nh ngha hai trng thi: SELECTED vDESELECTED.

    Vit mt Key Listeneroc pht ra khi ngi s dng nh phm. c bit Key events pht ra bi i tng m dang ctp trung khi ngi dng nhn hoc nh phm.Cc phng thc s kin ca KeyGiao din KeyListener v lp m phng tng ng, KeyAdapter, cha ba phng thc:void keyTyped(KeyEvent)oc gi sau khi phm oc nh.void keyPressed(KeyEvent)c go sau khi mt phm c n.void keyReleased(KeyEvent)

    c gi sau khi mt phm c nh.V d v Handling Key Eventspublic class KeyEventDemo ... implements KeyListener ... {

    ...//where initialization occurs:

    typingArea = new TextField(20);

    typingArea.addKeyListener(this);

    ...

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    25/49

    25

    /** Handle the key typed event from the text field. */

    public void keyTyped(KeyEvent e) {

    displayInfo(e, "KEY TYPED: ");

    }

    /** Handle the key pressed event from the text field. */

    public void keyPressed(KeyEvent e) {

    displayInfo(e, "KEY PRESSED: ");}

    /** Handle the key released event from the text field. */

    public void keyReleased(KeyEvent e) {

    displayInfo(e, "KEY RELEASED: ");

    }

    ...

    protected void displayInfo(KeyEvent e, String s){

    ...

    char c = e.getKeyChar();

    int keyCode = e.getKeyCode();

    int modifiers = e.getModifiers();

    ...tmpString = KeyEvent.getKeyModifiersText(modifiers);

    ...//display information about the KeyEvent...

    }

    }Lp KeyEventMi phng thc Key Event c mt thng s n: i tng KeyEvent. Lp KeyEvent nhnghanhng phng thc thng dng sau:int getKeyChar()void setKeyChar(char)Nhn hoc xc lp k t lin quan vi s kin ny.int getKeyCode()

    void setKeyCode(int)nhn hoc xc lp m ca phm lin quan vi s kin ny.void setModifiers(int)xc lp tng thi ca phm lin quan ti s kin nyint getModifiers()T v trng thi ca phm trong s kin ny. Vit mt Mouse ListenerCc s kin c pht ra khi ngi s dng dng chut tc ng n mt thnh phn.Cc phng thc, s kin ca MouseGiao din MouseListener v lp m phng tng ng, MouseAdapter, cha ba phng thc:void mouseClicked(MouseEvent)c gi sau nkhi ngi s dng kch hot chut vo mt thnh phn .void mouseEntered(MouseEvent)

    c gi sau khi con tr chut nm trong a phn ca thnh phn.void mouseExited(MouseEvent)c gi sau khi con tr chut ra khi a phn ca thnh phn.void mousePressed(MouseEvent)c gi sau khi con chut c n trn a phn ca thnh phn.void mouseReleased(MouseEvent)c gi sau khi con chut c nh trn a phn ca thnh phn.V d v Handling Mouse Eventspublic class MouseEventDemo ... implements MouseListener {

    ...//where initialization occurs:

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    26/49

    26

    //Register for mouse events on blankArea and applet (panel).

    blankArea.addMouseListener(this);

    addMouseListener(this);

    ...

    public void mousePressed(MouseEvent e) {

    saySomething("Mouse button press", e);

    }

    public void mouseReleased(MouseEvent e) {saySomething("Mouse button release", e);

    }

    public void mouseEntered(MouseEvent e) {

    saySomething("Cursor enter", e);

    }

    public void mouseExited(MouseEvent e) {

    saySomething("Cursor exit", e);

    }

    public void mouseClicked(MouseEvent e) {

    saySomething("Mouse button click", e);}

    void saySomething(String eventDescription, MouseEvent e) {

    textArea.append(eventDescription + " detected on "

    + e.getComponent().getClass().getName()

    + ".\n");

    textArea.setCaretPosition(maxInt); //scroll to bottom

    }

    }Lp MouseEvent

    Mi phng thc Mouse Event c mt thng s n: i tng MouseEvent. Lp MouseEvent nhngha cc phng thc thng dng sau:int getClickCount()

    tr v s ln nhn lin tip ca ngi s dng.int getX()int getY()

    Point getPoint()Tr v v tr ca con tr tr chut, v tr ny ph thuc vo thnh phn.boolean isPopupTrigger()

    tr v gi tr True khi s kin ny lm xut hin Popup Menu. Vit mt Mouse Motion ListenerCc s kin Mouse motion pht ra ki ngi s dng dng chut di chuyn trn mn hnh.Cc phng thc, s kin ca Mouse MotionGiao din MouseMotionListener v lp m phng tng ng, MouseMotionAdapter, cha hai phngthc:void mouseDragged(MouseEvent)c gi sau khi ngi s dng di chuyn chut trong khi chut ang c nhn.void mouseMoved(MouseEvent)

    c gi sau khi ngi s dng di chuyn chut khi con chut cha b nhn.V d v Handling Mouse Motion Events...//where initialization occurs:

    MyListener myListener = new MyListener();

    addMouseListener(myListener);

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    27/49

    27

    addMouseMotionListener(myListener);

    ...

    class MyListener extends MouseAdapter

    implements MouseMotionListener {

    public void mousePressed(MouseEvent e) {

    int x = e.getX();

    int y = e.getY();

    currentRect = new Rectangle(x, y, 0, 0);repaint();

    }

    public void mouseDragged(MouseEvent e) {

    updateSize(e);

    }

    public void mouseMoved(MouseEvent e) {

    //Do nothing.

    }

    public void mouseReleased(MouseEvent e) {

    updateSize(e);}

    void updateSize(MouseEvent e) {

    int x = e.getX();

    int y = e.getY();

    currentRect.setSize(x - currentRect.x,

    y - currentRect.y);

    repaint();

    }

    }

    Cc phng thc, s kin c s dng bi Mouse-Motion ListenersMi phng thc Mouse Motion Event c mt thng s n, v n khng c gi l

    MouseMotionEvent! Thay vo , phng thc Mouse Motion Event s dng i tng MouseEvent. Vit mt Text ListenerCc s kin Text tr v sau khi chui trong thnh phn Text c s thay i.Cc phng thc, s kin ca TextGiao din TextListener ch c mt phng thc nn khng c lp m phng tng ng:void textValueChanged(TextEvent)c gi sau khi chui trong thnh phn Text thay i.V d v Handling Text Eventspublic class TextEventDemo ... {

    TextField textField;TextArea textArea;

    TextArea displayArea;

    ...

    //where initialization occurs:textField = new TextField(20);

    ...

    textField.addTextListener(new MyTextListener("Text Field"));

    textArea = new TextArea(5, 20);

    textArea.addTextListener(new MyTextListener("Text Area"));

    ...

    }

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    28/49

    28

    class MyTextListener implements TextListener {

    String preface;

    public MyTextListener(String source) {

    preface = source

    + " text value changed.\n"

    + " First 10 characters: \"";

    }

    public void textValueChanged(TextEvent e) {TextComponent tc = (TextComponent)e.getSource();

    String s = tc.getText();

    ...//truncate s to 10 characters...

    displayArea.append(preface + s + "\"\n");

    ...

    }

    }

    ...

    }

    Lp TextEventMi phng thc Text Event c mt thng s n : i tng TextEvent. Lp TextEvent nh nghamt phng thc. Phng thc getSource m TextEvent tha k t EventObject, bn c th nhn cthnh phn Text lin quan n s kin ny v gi thng ip cho n. Vit mt Window ListenerCc s kin ca Window c pht ra sau khi Window m, ng, thu nh, phng to, hot ng vkhng hot ng.Cc phng thc, s kin ca WindowGiao din WindowListener v lp m phng tng ng, WindowAdapter, cha cc phng thc sau:void windowOpened(WindowEvent)

    c gi au khi Window c m ln u.void windowClosing(WindowEvent)c gi sau khi ngi s dng ng Window.void windowClosed(WindowEvent)c gi sau khi Window ng li.void windowIconified(WindowEvent)

    void windowDeiconified(WindowEvent)c gi sau khi Window phng to hay thu nh.void windowActivated(WindowEvent)void windowDeactivated(WindowEvent)c gi sau khi Window hot ng hay khng hot ng.V d v Handling Window Eventspublic class WindowEventDemo ... implements WindowListener {

    ...//where initialization occurs:

    //Create but don't show window.

    window = new Frame("Window Event Window");

    window.addWindowListener(this);window.add("Center",

    new Label("The applet listens to this window"

    " for window events."));

    window.pack();

    }

    public void windowClosing(WindowEvent e) {

    window.setVisible(false);

    displayMessage("Window closing", e);

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    29/49

    29

    }

    public void windowClosed(WindowEvent e) {

    displayMessage("Window closed", e);

    }

    public void windowOpened(WindowEvent e) {

    displayMessage("Window opened", e);}

    public void windowIconified(WindowEvent e) {

    displayMessage("Window iconified", e);

    }

    public void windowDeiconified(WindowEvent e) {

    displayMessage("Window deiconified", e);

    }

    public void windowActivated(WindowEvent e) {

    displayMessage("Window activated", e);

    }

    public void windowDeactivated(WindowEvent e) {displayMessage("Window deactivated", e);

    }

    void displayMessage(String prefix, WindowEvent e) {

    display.append(prefix

    + ": "

    + e.getWindow()

    + newline);

    }...

    }Lp WindowEventMi phng thc Window Event c mt thng s n: i tng WindowEvent. Lp WindowEventnh ngha mt phng thc, getWindow, tr v Window pht ra s kin ny.

    2. Thit k cc thnh phn trong mt Containera. S dng Layout Managers S dng BorderLayoutSau y l mt Applet cho thy BorderLayout lm vic nh th no.setLayout(new BorderLayout());

    setFont(new Font("Helvetica", Font.PLAIN, 14));

    add("North", new Button("North"));

    add("South", new Button("South"));add("East", new Button("East"));

    add("West", new Button("West"));

    add("Center", new Button("Center"));

    Quan trng: khi thm mt thnh phn vo mt Container s dng BorderLayout, bn nn dng phng thc add() hai thng s, v thng s th nht phi l "North", "South", "East","West", hoc "Center". Nu bn s dng phng thc add()mt thng s hay bn khng xc lpthng s th nht th thnh phn s khng hin th.Theo mc nh, BorderLayout khng t khong trng gia cc thnh. Mun vy, bn phi xc lp nbng cch dng cu trc sau:

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    30/49

    30

    public BorderLayout(int horizontalGap, int verticalGap)

    S dng CardLayoutSau y l mt Applet cho thy CardLayout lm vic nh th no.//Where instance variables are declared:

    Panel cards;

    final static String BUTTONPANEL = "Panel with Buttons";

    final static String TEXTPANEL = "Panel with TextField";

    //Where the container is initialized:

    cards = new Panel();

    cards.setLayout(new CardLayout());

    ...//Create a Panel named p1. Put buttons in it.

    ...//Create a Panel named p2. Put a text field in it.

    cards.add(BUTTONPANEL, p1);

    cards.add(TEXTPANEL, p2);

    Khibn thm mt thnh phn vo mt Container m c s dng CardLayout, bn phi s dng phngthc add() hai thng s: add(String name, Component comp). Thng s th nht c thbt k chui no nhn ra thnh phn c thm vo.

    Sau y l mt on m v d cho phng thc trn://Where the container is initialized:. . .

    //Put the Choice in a Panel to get a nicer look.

    Panel cp = new Panel();

    Choice c = new Choice();

    c.addItem(BUTTONPANEL);

    c.addItem(TEXTPANEL);

    cp.add(c);

    add("North", cp);

    . . .

    public boolean action(Event evt, Object arg) {if (evt.target instanceof Choice) {

    ((CardLayout)cards.getLayout()).show(cards,(String)arg);

    return true;

    }

    return false;

    }

    Nh on m trn, bn c th s dng phng thc show() ca CardLayout xc lp thnh phnhin th hin ti. Thng s th nht ca phng thc show() l Container m CardLayout iu khin.thng s th hai l chui xc nh thnh phn hin th. Chui ny ging nh chui ca thnh phnthm vo Container.Theo sau l tt c cc phng thc ca CardLayout m c th cho php chn mt thnh phn. cho miphng thc, thng s th nht Container cho CardLayout l mt Layout Manager.

    public void first(Container parent)public void next(Container parent)

    public void previous(Container parent)

    public void last(Container parent)

    public void show(Container parent, String name)

    S dng FlowLayoutSau y l mt Applet cho thy FlowLayout hot ng nh th no.setLayout(new FlowLayout());

    setFont(new Font("Helvetica", Font.PLAIN, 14));

    add(new Button("Button 1"));

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    31/49

    31

    add(new Button("2"));

    add(new Button("Button 3"));

    add(new Button("Long-Named Button 4"));

    add(new Button("Button 5"));

    Lp FlowLayout c ba cu trc:public FlowLayout()

    public FlowLayout(int alignment)

    public FlowLayout(int alignment,int horizontalGap, int verticalGap)

    thng s alignment phi l cc gi tr FlowLayout.LEFT, FlowLayout.CENTER, hocFlowLayout.RIGHT. Thng s horizontalGap v verticalGap xc nh s Pixel c giacc thnh phn. Nu bn khng xc lp gi tr ny, FlowLayout s mc nh gi tri 5 cho mi thng s. S dng GridLayoutSau y l mt Aplet cho thy GridLayout lm vic nh th no.//Construct a GridLayout with 2 columns and an unspecified number of

    rows.

    setLayout(new GridLayout(0,2));

    setFont(new Font("Helvetica", Font.PLAIN, 14));

    add(new Button("Button 1"));

    add(new Button("2"));add(new Button("Button 3"));

    add(new Button("Long-Named Button 4"));

    add(new Button("Button 5"));

    Cu trc trn cho thy lp GridLayout to mt i tng c hai ct v nhiu hng. y l mt trong haicu trc cho GridLayout. Sau y l cch khai bo cho c hai cu trc ny:public GridLayout(int rows, int columns)

    public GridLayout(int rows, int columns,

    int horizontalGap, int verticalGap)

    S dng GridBagLayoutTheo sau l mt vi on lnh tiu biu trong mt Container c s dng GridBagLayout.GridBagLayout gridbag = new GridBagLayout();

    GridBagConstraints c = new GridBagConstraints();

    setLayout(gridbag);

    //For each component to be added to this container:

    //...Create the component...

    //...Set instance variables in the GridBagConstraints instance...

    gridbag.setConstraints(theComponent, c);

    add(theComponent);

    Bn c th s dng li mt i tng ca GridBagConstraints cho nhiu thnh phn khc nhau, ngay ckhi cc thnh phn c s rng buc khc nhau. GridBagLayout rt ra mt gi tr rng buc v khngdng li GridBagConstraints. Bn phi cn thn, tuy nhin, khi to li gi tr ca mt i tngGridBagConstraints lm gi tr mc nh khi cn thit.Bn c th xc lp cc gi tr sau:gridx, gridy

    Xc nh hng v ct ti v tr trn bn ti ca thnh phn. Hu ht ct trn bn ti c c ch gridx=0,v hng trn cng c a ch gridy=0. S dng GridBagConstraints.RELATIVE (gi tr mcnh) xc nh rng thnh phn ch bn phi hay pha di.gridwidth, gridheight

    xc lp s ct hoc s hng trong vng hin th ca thnh phn. nhng gi tr ny xc nh s Cell mthnh phn s dng, khng phi s Pixel n s dng. Mc nh l 1. S dngGridBagConstraints.REMAINDER xc nh thnh phn ang hng cui cng hay ct cuicng. S dng GridBagConstraints.RELATIVE xc nh bc k tip ca thanh phn lhng cui hay ct cui cng.fill

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    32/49

    32

    c s dng khi vng hin th ca thnh phn ln hn kich thc thnh phn i hi quyt nhkhi no hoc thay i kch thc nh th no. cc gi tr thch hp l GridBagConstraints.NONE(mc nh), GridBagConstraints.HORIZONTAL, GridBagConstraints.VERTICAL vGridBagConstraints.BOTH.

    ipadx, ipady

    xc nh phn ph bn trong: bao nhiu thm vo kch thc ti thiu ca thnh phn. gi tr mcnh l 0. Chiu rng ca thnh phn ti thiu nht l bng chiu rng ti thiu ca n cng vi

    ipadx*2. Similarly, chiu cao ca thnh phn ti thiu nht l bng chiu cao ti thiu ca n cngvi ipady*2.insets

    xc nh phn ph bn ngoi ca thnh phn. mc nh, mi thnh phn khng c phn ph bn ngoi.anchor

    c s dng khi thnh phn nh hn vng hin th quyt nh khi no t thnh phn. gi tr thchhp l GridBagConstraints.CENTER (mc nh), GridBagConstraints.NORTH,GridBagConstraints.NORTHEAST, GridBagConstraints.EAST,

    GridBagConstraints.SOUTHEAST, GridBagConstraints.SOUTH,

    GridBagConstraints.SOUTHWEST, GridBagConstraints.WEST, vGridBagConstraints.NORTHWEST.

    V d :

    Sau y l mt Applet ch cho thy GridBagLayout hot ng nh th no.Sau y l mt on lnh to mt GridBagLayout v cc thnh phn n qun lprotected void makebutton(String name,

    GridBagLayout gridbag,

    GridBagConstraints c) {

    Button button = new Button(name);

    gridbag.setConstraints(button, c);

    add(button);

    }

    public GridBagWindow() {

    GridBagLayout gridbag = new GridBagLayout();

    GridBagConstraints c = new GridBagConstraints();

    setFont(new Font("Helvetica", Font.PLAIN, 14));

    setLayout(gridbag);

    c.fill = GridBagConstraints.BOTH;

    c.weightx = 1.0;

    makebutton("Button1", gridbag, c);

    makebutton("Button2", gridbag, c);

    makebutton("Button3", gridbag, c);

    c.gridwidth = GridBagConstraints.REMAINDER; //end of row

    makebutton("Button4", gridbag, c);

    c.weightx = 0.0; //reset to the default

    makebutton("Button5", gridbag, c); //another row

    c.gridwidth = GridBagConstraints.RELATIVE; //next to last in row

    makebutton("Button6", gridbag, c);

    c.gridwidth = GridBagConstraints.REMAINDER; //end of row

    makebutton("Button7", gridbag, c);

    c.gridwidth = 1; //reset to the default

    c.gridheight = 2;

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    33/49

    33

    c.weighty = 1.0;

    makebutton("Button8", gridbag, c);

    c.weighty = 0.0; //reset to the default

    c.gridwidth = GridBagConstraints.REMAINDER; //end of row

    c.gridheight = 1; //reset to the default

    makebutton("Button9", gridbag, c);

    makebutton("Button10", gridbag, c);}

    b. To mt Layout ManagerCh : Trc khi bt u thit k mt Layout Manager, chc chn rng khng tn ti mt LayoutManager s hot ng. C bit, GridBagLayout mm do lm vic trong nhiu trng hp khcnhau. to mt Layout Manager, bn phi to mt lp thc thi giao din LayoutManager.LayoutManager yu cu quan h cht ch vi n thc thi nm phng thc:public void addLayoutComponent(String name, Component comp)

    Ch c gi bng phng thc add(name, component) ca Container.public void removeLayoutComponent(Component comp)

    Gi bi nhng phng thc remove() v removeAll() ca Container.public Dimension preferredLayoutSize(Container parent)

    Gi bi phng thc preferredSize() ca Container, c th t gi di mi tnh hung.public Dimension minimumLayoutSize(Container parent)

    Gi bi phng thc minimumSize() ca Container, c th t gi di mi tnh hung.public void layoutContainer(Container parent)

    Gi khi Container hin th ln uis first displayed, v mi lc n tahy i kch thc.c. Lm vic thiu Layout ManagerMc d c th lm vic m khng cn Layout Manager, bn nn dng Layout Manager nu c th.Layout managers d thay i kch thc ca Container v iu chnh hnh dng ca cc thnh phn phthuc vo Platform. N cng c th c s dng l bi cc Container va cc chng trnh khc. nuCustom Container s khng ti s dng, khng th thay i kch thc, v hon ton c th iu khinc cc thng s ph thuc vo h thng nh Font v hnh dng cc thnh phn.V d:public class NoneWindow extends Frame {

    . . .private boolean laidOut = false;

    private Button b1, b2, b3;

    public NoneWindow() {

    super();

    setLayout(null);

    setFont(new Font("Helvetica", Font.PLAIN, 14));

    b1 = new Button("one");

    add(b1);

    b2 = new Button("two");

    add(b2);

    b3 = new Button("three");add(b3);

    }

    public void paint(Graphics g) {

    if (!laidOut) {

    Insets insets = insets();

    /*

    * We're guaranteed that insets() will return a valid

    Insets

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    34/49

    34

    * if called from paint() -- it isn't valid when called

    from

    * the constructor.

    *

    * We could perhaps cache this in an ivar, but insets can

    * change, and when they do, the AWT creates a whole new

    * Insets object; the old one is invalid.

    */b1.reshape(50 + insets.left, 5 + insets.top, 50, 20);

    b2.reshape(70 + insets.left, 35 + insets.top, 50, 20);

    b3.reshape(130 + insets.left, 15 + insets.top, 50, 30);

    laidOut = true;

    }

    }

    . . .

    }d. Cc bi ton v LayoutBi ton: Lm th no xc nh c chnh xc kch thc ca mt thnh phn?

    u tin, chc chn bn tht s mun xc lp kch thc chnh xc ca thnh phn. nhngthnh phn chun c kch thc khc nhau, ph thuc vao Platform m thnh phn ang chy vFont n s dng, v vy thwongf ch lm theo cm gic xc nh kch thc chnh xc ca cc thnhphn.i vi nhng Custom Component c kch thc xc nh, xc nh kch thc chnh xc ch l cmgic ch quan. Bn cn ghi ln cc phng thc minimumSize() v preferredSize() cathnh phn tr v mt kch thc ng cho thanh phn . thay i kch thc ca thnh phn khi thnh phn ang hin th, xem bi ton tip theo.Bi ton: Lm th no thay i kch thc ca mt thnh phn? Mt khi thnh phn hin th, bn c th tahy i kch thc ca n bng phng thcresize(). Ri bn gi phng thc validate() Container v li.Bi ton: Thnh phn ang c kch thc qu nh. Thnh phn c thc thi nhng phng thc preferredSize() v minimumSize()hay khng? Nu vy, n c tr v gi tr ng hay khng? Khi b dng Layout manager, bn c th dng khng gian sn c hay khhong?4. Lm vic vi hoa. Tng quan v h tr ho ca AWTKhi phng thc repaint()c gi, AWT gi ti phng thc update() ca yu cu thnhphn t v li. phng thc update() gi phng thc paint() ca thnh phn .i tng hoThng s duy nht cho cc phng thc paint() v update()l mt i tng ho(Graphics).i tng Graphics l cha kho cho tt c cc cng vic v ny.N cung cp hai kiu v c bn:kiu v n s(nh lines, rectangles, and text) v hnh nhBn cnh cc kiu v trn, i tng Graphics cung cp mt ng cnh v trng thi duy tr nh vngv hin ti v mu v hin ti. Bn c th gim bt vng v bng cch ct xn n, nhng bn khng baobao gi tng c vng v. Do , i tng Graphics chn chn mt thnh phn ch c th v ctrong vng qun l ca n.H thng to Mi thnh phn u c h thng to ring, t (0, 0) n (width - 1, height- 1), vi mi n v tnh lPixel.

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    35/49

    35

    Bn hnh thc ca phng thc repaint()public void repaint()

    Gi phng thc update()ngay lp tc.public void repaint(long time)

    Gi phng thc update() sau timemili giy na.public void repaint(int x, int y, int width, int height)

    Gi phng thc update()ngay lp tc v ch v li vng gii hn.public void repaint(long time, int x, int y, int width, int height)

    Gi phng thc update() sau timemili giy na v ch v li vng gii hnb. S dng cc mu gc ca hoV cc hnh dngLp Graphics nh ngha cc phng thc v cho cc loi hnh nh sau: ng thng (drawLine(), v ng thng vi mu hin ti ca i tng Graphics, muny c xc lp nh mu ch ca i tng) Hnh ch nht (drawRect(), fillRect(), vclearRect()) Hnh ch nht ni hoc chm (draw3DRect()vfill3DRect()) Round-edged rectangles (drawRoundRect()vfillRoundRect()) Hnh Oval (drawOval() and fillOval()) Ve cung (drawArc() and fillArc()) V cc a gic (drawPolygon() and fillPolygon())V d 1: v d n gin v v hnh ch nhtSau y ch l nhng on lnh phc v vic v hnh ch nht://In FramedArea (a Panel subclass):

    public void paint(Graphics g) {

    Dimension d = size();

    Color bg = getBackground();

    //Draw a fancy frame around the applet.

    g.setColor(bg);

    g.draw3DRect(0, 0, d.width - 1, d.height - 1, true);

    g.draw3DRect(3, 3, d.width - 7, d.height - 7, false);

    }

    //In CoordinateArea (a Canvas subclass):public void paint(Graphics g) {

    //If user has clicked, paint a tiny rectangle where click

    occurred

    if (point != null) {

    g.fillRect(point.x - 1, point.y - 1, 2, 2);

    }

    }

    Applet to (v cha) mt i tng FramedArea, ln lt to (v cha) mt i tng CoordinateArea.Lnh u gi ti phng thc draw3DRect() to mt hnh ch nht chim ht vng cho php v

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    36/49

    36

    ca FramedArea. Thng s true xc nh rng hnh ch nht phi ni. Lnh th hai gidraw3DRect()to hnh ch nht th hai nh hn, thng s falsexc nh hnh ch nht s xuthin chm xung. Bn cnh , hai lnh trn c tc dng vi FramedArea l cha i tngCoordinateArea.

    CoordinateArea s dng fillRect() t hai pixel mt ti v tr ngi s dng nhp chut.V d 2: s dng hnh ch nht ch ra vng c chny l mt Applet m bn c th s dng cc phng thc c bn thc thi vng c chn trong

    chng trnh v. Khi ngi s dng ko chut, Applet s hin th lin tc mt hnh ch nht. Hnh chnht bt u t im m ngi s dng n chut ln u v kt thc ti v tr con tr chut hin ti.Sau y l cc lnh mi quan trng nht cho Applet trn:class SelectionArea extends Canvas {

    . . .

    public boolean mouseDown(Event event, int x, int y) {

    currentRect = new Rectangle(x, y, 0, 0);

    repaint();

    return false;

    }

    public boolean mouseDrag(Event event, int x, int y) {

    currentRect.resize(x - currentRect.x, y - currentRect.y);repaint();

    return false;

    }

    public boolean mouseUp(Event event, int x, int y) {

    currentRect.resize(x - currentRect.x, y - currentRect.y);

    repaint();

    return false;

    }

    public void paint(Graphics g) {

    Dimension d = size();

    //If currentRect exists, paint a rectangle on top.

    if (currentRect != null) {

    Rectangle box = getDrawableRect(currentRect, d);

    controller.rectChanged(box);

    //Draw the box outline.

    g.drawRect(box.x, box.y, box.width - 1, box.height - 1);

    }

    }

    Rectangle getDrawableRect(Rectangle originalRect, Dimension

    drawingArea) {

    . . .//Make sure rectangle width and height are positive.

    . . .

    //The rectangle shouldn't extend past the drawing area.

    . . .

    }

    }

    Nh bn thy, vng c chn s gi c hnh ch nht hin ti ang chn, s dng i tngRectangle c gi bi currentRect. Khi c thc thi, currentRectgi nguyn to gc

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    37/49

    37

    (currentRect.x, currentRect.y) trong khi ngi s dng ko chut. iu ny c ngha lchiu cao v chiu rng ca hnh ch nht s khng quan trng.Tuy nhin, nhng phng thcdrawXxx()v fillXxx()khng v bt c th g nu chiu rnghoc chiu cao khng c. V l do ny, nn khi SelectionArea v mt hnh ch nht, n phi xc nhim gc ti bn trn hnh ch nht chiu rng v chiu cao wocj r rng hn . Lp SelectionAreanh ngha phng thc getDrawableRect() thc hin cc phep tnh ton cn thit cho victm ra im . Phng thc getDrawableRect() cng chn chn im khng vt ra khi

    vng c php vV d 3: v d v v cc hnh nhApplet demonstrates minh ho y cc hnh nh c v v c t nh th no.Tr khi Font mc nh ca Applet qu nh, chui s c hin th rt xu.Sau y ch l cc lnh v cc loi hnh hc c bn . Cc gi tr rectHeightv rectWidthxcnh kch thc mi vng cho vic v cc hnh nh . Cc gi tr xv yc thay i cho mi hnh,do cc hnh khng c v trn nhau.Color bg = getBackground();

    Color fg = getForeground();

    . . .

    // drawLine()

    g.drawLine(x, y+rectHeight-1, x + rectWidth, y); // x1, y1, x2, y2

    . . .

    // drawRect()

    g.drawRect(x, y, rectWidth, rectHeight); // x, y, width, height

    . . .

    // draw3DRect()

    g.setColor(bg);

    g.draw3DRect(x, y, rectWidth, rectHeight, true);

    g.setColor(fg);

    . . .

    // drawRoundRect()

    g.drawRoundRect(x, y, rectWidth, rectHeight, 10, 10); // x, y, w, h,arcw, arch

    . . .

    // drawOval()

    g.drawOval(x, y, rectWidth, rectHeight); // x, y, w, h

    . . .

    // drawArc()

    g.drawArc(x, y, rectWidth, rectHeight, 90, 135); // x, y, w, h

    . . .

    // drawPolygon()

    Polygon polygon = new Polygon();polygon.addPoint(x, y);

    polygon.addPoint(x+rectWidth, y+rectHeight);

    polygon.addPoint(x, y+rectHeight);

    polygon.addPoint(x+rectWidth, y);

    //polygon.addPoint(x, y); //don't complete; fill will, draw won't

    g.drawPolygon(polygon);

    . . .

    // fillRect()

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    38/49

    38

    g.fillRect(x, y, rectWidth, rectHeight); // x, y, width, height

    . . .

    // fill3DRect()

    g.setColor(bg);

    g.fill3DRect(x, y, rectWidth, rectHeight, true);

    g.setColor(fg);

    . . .

    // fillRoundRect()

    g.fillRoundRect(x, y, rectWidth, rectHeight, 10, 10); // x, y, w, h,

    arcw, arch

    . . .

    // fillOval()

    g.fillOval(x, y, rectWidth, rectHeight); // x, y, w, h

    . . .

    // fillArc()

    g.fillArc(x, y, rectWidth, rectHeight, 90, 135); // x, y, w, h

    . . .

    // fillPolygon()

    Polygon filledPolygon = new Polygon();

    filledPolygon.addPoint(x, y);

    filledPolygon.addPoint(x+rectWidth, y+rectHeight);

    filledPolygon.addPoint(x, y+rectHeight);

    filledPolygon.addPoint(x+rectWidth, y);

    //filledPolygon.addPoint(x, y);

    g.fillPolygon(filledPolygon);

    Lm vic vi chuiKhi vit lnh v chui, trc tin bn nn quan tm c s dng thnh phn c nh hng chui haykhng nh Label, TextField, hoc TextArea.Nu cc thnh phn ny khng thch hp, bn c th s

    dng cc phng thc drawBytes(), drawChars(), hoc drawString() ca i tngGraphics.Sau y l mt on lnh v d v mt chui ra mn hnh:g.drawString("Hello World!", x, y);

    x,yl to ni chui hin th.Nhn bit thng tin v Font: FontMetricsV d :boolean fontFits = false;

    Font font = g.getFont();

    FontMetrics fontMetrics = g.getFontMetrics();

    int size = font.getSize();

    String name = font.getName();

    int style = font.getStyle();

    while (!fontFits) {

    if ( (fontMetrics.getHeight()

  • 8/3/2019 Java UI - Smith.N Studio

    39/49

    39

    g.setFont(font = new Font(name,

    style,

    --size));

    fontMetrics = g.getFontMetrics();

    }

    }

    }

    on lnh trn s dng cc phng thc getFont(), setFont(), v getFontMetrics()cai tng Graphics d ly v xc lp gi tr cho font hin ti v ly i tng FontMetrics tng ngvi Font. T cc phng thc getHeight()vgetStringWidth()ca i tng FontMetrics,on lnh trn ly kch thwocs ngang v dc ca Font .Hnh nh sau minh ho vi thng tin v nhng thng tin v Font m i tng FontMetrics cung cp:

    Sau y l cc phng thc ca FontMetrics c th tr v thnh tin v kch thc dc ca Font:getAscent(), getMaxAscent()

    phng thc getAscent()tr v s Pixel nm gia ascender line v baseline.Ni chung, Ascenderline miu t chiu cao in hnh ca k t hoa. c bit, cc gi tr ascent v descent c chn bingi thit k Font miu t ng chui , hoc dy ca ch, v vy chui s xut hin ng vi tng thit k. Ascent cung cp y khong trng cho k t, ngoi tr khong trng cho cc du cacc k t hoa. Phng thc getMaxAscent()m chiu cao cho trng hp ny.getDescent(), getMaxDescent()

    phng thcgetDescent()tr v s Pixel nm gia baseline v descender line. Trong hu ht ccloi Font, mi k t u ko di xung Descender line ti im thp nht. Ch trong trng hp bn sdng phng thcgetMaxDescent() nhn khong khng gian chn cho k t c v ht.getHeight()

    Tr v s Pixel c tm thy gia Baseline ca hai dng chui k t.getLeading()

    Tr v khong trng gia hai dng.getMaxAdvance()

    Chiu rng nht ca k t trongbytesWidth(byte[], int, int)

    Chiu rng ca chui c khai bo bi mt mng cc k t. Thng s Int u tin xc nh v tr btu k t ca chui . Thng s Int th hai xc nh s k t ca chui .

    charWidth(int), charWidth(char)Chiu rng ca mt k t xc nh.charsWidth(char[], int, int)

    Chiu rng ca k t trong mng.stringWidth(String)

    Chiu rng ca chui string.getWidths()

    Chiu rng ca mi k t trong k t u tin.c. S dng hnh nhNp nh

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    40/49

    40

    S dng phng thc getImage()Lp Applet cung cp hai phng thc getImage(): public Image getImage(URL url) public Image getImage(URL url, String name)Ch c Applets mi c th s dng phng thc getImage(). Hn th na, phng thcgetImage()ca Applet khng lm vic cho n khi no Applet c mt ng cnh y . V l dony, nhng phng thc ny khng lm vic nu n c gi trong mt cu trc hoc cu lnh khai

    bo mt bin minh ho. Bn nn gi phng thc init() thay v gi phng thcgetImage().on lnh sau miu t vic s dng phng thcgetImage()ca Applet.//In a method in an Applet subclass:

    Image image1 = getImage(getCodeBase(), "imageFile.gif");

    Image image2 = getImage(getDocumentBase(), "anImageFile.jpeg");

    Image image3 = getImage(new

    URL("http://java.sun.com/graphics/people.gif"));

    Lp Toolkit khai bo hn hai phng thcgetImage(): public abstract Image getImage(URL url) public abstract Image getImage(String filename) bn c th nhn i tng Toolkit bng cch gi phng thc getDefaultToolkit()ca lpToolkit hoc gi phng thcgetToolkit()ca cc thnh phn. Phng thcgetToolkit()

    ca thnh phn tr v i tng Toolkit c s dng (hoc s c s dng) d thc thi mt thnhphn.Sau y l v d minh ho vic s dng phng thc getImage()ca Toolkit. Mi ng dng vApplet ca Java c th s dng cc phng thc ny, vi Applet thwongf hn ch vn v bo mt.Toolkit toolkit = Toolkit.getDefaultToolkit();

    Image image1 = toolkit.getImage("imageFile.gif");

    Image image2 = toolkit.getImage(new

    URL("http://java.sun.com/graphics/people.gif"));

    Yu cu v theo i qu trnh np nh: MediaTracker v ImageObserverAWT cung cp hai cch thc cho vic theo di qu trnh np nh: lp MediaTracker v giao dinImageObserver. Lp MediaTracker y cho mi chng trnh. Bn c th to mt MediaTracker, vlnh cho n theo di mt hoc nhiu nh, v ri yu cu n cho bit tnh trang cu cc nh ny khi cnthit.

    Giao din ImageObserver cho php bn theo di st nt hn qu trnh np nh so vi lp MediaTrackercho php. Lp tahnhf phn ny s dng n do cc thnh phn ny v li cc nh ngay sau khi nhc np. s dng giao din ImageObserver, bn thc thi phng thcimageUpdate() caImageObserver v chn chn rng cc i tng thc thi phng thc c ng k nh l mt giaodin ImageOserver. Thgn thng, s ng k xy ra khi bn xc nh mt ImageObserver chophngthcdrawImage. Phng thcimageUpdate()c gi bt c khi no c cc thng tin v nhy l mt v d thc thi phng thcimageUpdate()ca giao din Image Observer. V d ny sdng phng thcimageUpdate() xc nh v tr ca hai bc nh nagy sau khi bit kch thcca n, v c 100 milliseconds l v li n cho n khi n c np hon chnh.public boolean imageUpdate(Image theimg, int infoflags,

    int x, int y, int w, int h) {

    if ((infoflags & (ERROR)) != 0) {

    errored = true;

    }if ((infoflags & (WIDTH | HEIGHT)) != 0) {

    positionImages();

    }

    boolean done = ((infoflags & (ERROR | FRAMEBITS | ALLBITS)) !=

    0);

    // Repaint immediately if we are done, otherwise batch up

    // repaint requests every 100 milliseconds

    repaint(done ? 0 : 100);

    return !done; //If done, no further updates required.

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    41/49

    41

    }

    To nh vi MemoryImageSourceVi s tr gip ca lp MemoryImageSource, bn c th d dng to nh. on lnh v d sau v mtnh kch thc 100x100 hin th m i t mu en cho n mu xanh theo trc X v m i t en n theo trc Y.int w = 100;

    int h = 100;

    int[] pix = new int[w * h];int index = 0;

    for (int y = 0; y < h; y++) {

    int red = (y * 255) / (h - 1);

    for (int x = 0; x < w; x++) {

    int blue = (x * 255) / (w - 1);

    pix[index++] = (255

  • 8/3/2019 Java UI - Smith.N Studio

    42/49

    42

    Hnh nh trn minh ho d liu nh c to nh th no. Mt image producer-- mt i tong gncht vi giao din ImageProducer a ra mt d liu th cho i tng Image . Image producer cungcp d liu ny cho mt image consumer-- mt i tng gn cht vi giao din ImageConsumer. Trkhi bn cn thit phi ch tc hay to mt hnh nh cho mnh, nu khng bn khng cn bit v imageproducers v consumers. AWT tng s dng Image producers v consumers.AWT cung cp cng c ch tc nh bng cch cho php bn chn Image filters gia cc imageproducers v image consumers. Mt image filter l mt i tng ImageFilter c th nm gia

    producer v consumer, sa i d liu nh trvs khi consumer nhn n. ImageFilter thc thi mt giaodin ImageConsumer, t khi image filters ngn chn cc thng ip m producer gi ti consumer.Hnh sau minh ho image filter c t nh th no gia image producer v consumer.

    S dng Image FilterApplet sau s dng mt filter quay mt nh.public class ImageRotator extends Applet {

    . . .

    RotatorCanvas rotator;

    double radiansPerDegree = Math.PI / 180;

    public void init() {

    //Load the image.

    Image image = getImage(getCodeBase(),

    "../images/rocketship.gif");

    ...//Create the component that uses the image filter:

    rotator = new RotatorCanvas(image);

    . . .

    add(rotator);

    . . .

    }

    public boolean action(Event evt, Object arg) {

    int degrees;

    ...//Get the number of degrees to rotate the image by.

    //Convert to radians.

    rotator.rotateImage((double)degrees * radiansPerDegree);

    return true;

    }

    }

    class RotatorCanvas extends Canvas {

    Image sourceImage;

    Image resultImage;

    public RotatorCanvas(Image image) {

    sourceImage = image;

    resultImage = sourceImage;

    }

    public void rotateImage(double angle) {

    ImageFilter filter = new RotateFilter(angle);

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    43/49

    43

    ImageProducer producer = new FilteredImageSource(

    sourceImage.getSource(),

    filter);

    resultImage = createImage(producer);

    repaint();

    }

    public void paint(Graphics g) {Dimension d = size();

    int x = (d.width - resultImage.getWidth(this)) / 2;

    int y = (d.height - resultImage.getHeight(this)) / 2;

    g.drawImage(resultImage, x, y, this);

    }

    }

    on lnh trn lm vic nhth no1. nhn mt i tng Image (thng thng dng phng thc getImage()).2. S dng phng thc getSource(), ly d liu (ImageProducer) cho i tng Image3. to mt m t ca Image filter, khi to filter khi cn thit.4. To mt i tng FilteredImageSource, b qua cu trc ca d liu nh v i tng Filter.5. Vi phng thc createImage(), to mi mt i tng Image c mt FilteredImageSource nhl mt Image producer.Trong v d trn, phng thc rotateImage() ca RotatorCanvasmethod thc thi cc nhim v cquan h vi vic s dng Image filter. Tr bc u tin ra, ly i tng Image th, thc hin biphng thc init() ca Applet. i tng Image ny c chuyn ti RotatorCanvas, c cpti nh l sourceImage.Phong thc rotateImage() thuyt minh cho image filter bng cch gi cu trc ca Filter. Thngs cho cu trc ny l mt gcm nh quay.ImageFilter filter = new RotateFilter(angle);

    K tip, phng thc rotateImage() to mt minh ho FilteredImageSource ca. thng s th nhtcho cu trc FilteredImageSource l ngun nh, ly c qua phng thc getSource(). Thng sth hai l i tng Filter.ImageProducer producer = new FilteredImageSource(

    sourceImage.getSource(),

    filter);

    Cui cng, cu lnh to nh th hai, resultImage, bng vic s dng phng thccreateImage() ca thnh phn. Thng s duy nht createImage() l FilteredImageSourcec to bi bc trn.resultImage = createImage(producer);

    Vit mt Image FilterTt c cc Image Filter phi l cc lp con ca lp ImageFilter. Nu image filter sc sa i muhoc cc Pixel trong sut ca nh, th thay v phi to trc tip mt lp con ca ImageFilter, bn c thto mt lp con ca RGBImageFilter.To mt lp con ImageFilterNh cp phn trc, cc Image filter thc thi giao din ImageConsumer. ImageConsumer nh

    ngha cc phng thc sau:void setDimensions(int width, int height);void setProperties(Hashtable props);

    void setColorModel(ColorModel model);

    void setHints(int hintflags);

    void setPixels(int x, int y, int w, int h,

    ColorModel model, byte pixels[],

    int off, int scansize);

    void setPixels(int x, int y, int w, int h,

    ColorModel model, int pixels[],

    int off, int scansize);

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    44/49

    44

    void imageComplete(int status);

    Lp ImageFilter thc thi tt c cc phng thc trn. V d, ImageFilter thc thi phng thcsetDimensions() nh sau:public void setDimensions(int width, int height) {

    consumer.setDimensions(width, height);

    }

    Nh cc phng thc ca ImageFilter ny, lp con ca bn c th khng cn n vic phi thc thi mi

    phng thc ca ImageConsumer. bn ch cn thc thi mt phng thc chuyn giao d liu m bnmun thay i.V d, lp CropImageFilter thc thi bn phng thc: setDimensions(), setProperties(),v hai loi phng thc setPixels(). N cng thc thi mt cu trc vi thng s l hnh ch nhtxc nh cho vic ct xn. V d khc, lp RGBImageFilter thc thi vi phng thc tr gip, nhngha mt phong thc gip tru tng thc hin vic thay i mu tht ca mi pixel, v thcthi cc phng thc sau ca ImageConsumer: setColorModel() v hai loi phng thcsetPixels().

    Hu ht Most, cc filter thc thi nhng phng thc setPixels(). nhng phng thc ny xc nhchnh xc d liu nh c dng xy dng mt Image. mt hoc hai phng thc setPixels()c th c gi nhiu ln trong sut qu trnh xy dng mt Image. Mi ln gi u a tiImageConsumer thng tin vng bao hnh ch nht ca nh. Khi phng thc imageComplete()ca ImageConsumer c gi vi mi trng thi tr SINGLEFRAMEDONE, th ImageConsumer cth tha nhn l n c khng th nhn hn na phng thc setPixels(). Mt trng thiimageComplete() ca STATICIMAGEDONE xc nh rng khng ch hon ton nhn y d kiu nh, m cn xc nh rng khng c li no xy ra.Hnh nh minh ho v bng sau m t c c phng thcsetPixels() v cc thng s cho ccphng thc.

    x, y

    Xc nh v tr ca nh

    w, hXc nh chiu rng v chiu cao cho mi vng hnh ch nht.model

    Xc nh kiu mu c s dng cho cc Pixel.pixels[]

    Xc nh mt mng cc Pixel. Vng bao hnh ch nht ca nh nm trong mng cc Pixel ny , nhngmng phi cha hn gi tr w*hhin ti, ph thuc vo gi tr ca offsetv scansize. Sau y lcng thc tnh cho vic xc nh mng cc Pixel hin ti ca d liu ti (x+i, y+j), ni (0

  • 8/3/2019 Java UI - Smith.N Studio

    45/49

    45

    offset

    xc nh v tr (trong mng cc pixels) ca pixel u tin trong vng bao hnh ch nht.scansize

    xc nh chiu rng cho mi hng ca mng cc pixels..The RotateFilter Image FilterLp RotateFilter quay mt nh bi mt gc xc nh.N da vo cng thc hnh hc tnh v tr cho

    mi pixel:newX = oldX*cos(angle) - oldY*sin(angle)newY = oldX*sin(angle) + oldY*cos(angle)

    RotateFilter thc thi cc phng thc sau ca ImageConsumer:setDimensions()

    Ghi li chiu rng v chiu cao ca nh khng c lc trong phng thc setPixels() vimageComplete(). Tnh chiu cao cui cng nh c lc, ghi li dng cho vic s dng phngthcimageComplete()ca n, to mt b m cha d liu nh khi n lc c v gi phngthcsetDimensions() xc lp chiu cao v chiu rng mi.setColorModel()

    Ni cho bit cc Pixel s dng mu ca RGB.setHints()

    Xc nh nh c sp xp th t theo hng v ct.setPixels() (c hai loi ca phng thc ny)Chuyn i cc Pixel sang kiu RGB mc nh (nu cn thit) v sao chp cc Pixel sang b m.imageComplete()

    Quay nh ri gi phng thc consumer.setPixels()gi lin tc tng hng ca nh nConsumer. Sau khi gi ht,phng thc ny gi nconsumer.imageComplete().d. Thc hin cc hot cnhNhiu chng trnh thc hin hot cnh, hoc l hot hnh ca ch vt Duke ang tung tng bi li haych n gin l mt hnh nh chuyn ng trn mn hnh. Trong phn ny s ni v cch thc hin hnhnh ng, cch s dng i tng Timer thc hin hot cnh.To mt Animation LoopBc quan trng nht to mt chng trnh hot hnh chnh l khi to cc Framework mt cchchnh xc. Ngoi tr cc hot hnh thc hin trc tip cc p ng cho cc s kin m rng (v d nh

    vic ngi dng ko mt i tng trn mn hnh), mt chng trnh thc hin hot cnh cn c mtvng lp ca hot hnh.Minh ho cho mc ny c trong cc v d AnimatorAppletTimer.java vAnimatorApplicationTimer.java. Sau y l phn tm lc chung nht ca c hai v d. y cng lxn ca mt chng trnh hot cnh:public class AnimatorClass ... implements ActionListener {

    int frameNumber = -1;

    Timer timer;

    boolean frozen = false;

    JLabel label;

    //In initialization code:

    //From user-specified frames-per-second value, determine

    //how long to delay between frames....

    //Set up a timer that calls this object's action handler.

    timer = new Timer(delay, this);

    ...

    //Set up the components in the GUI.

    public synchronized void startAnimation() {

    ...

    timer.start();

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    46/49

    46

    ...

    }

    public synchronized void stopAnimation() {

    ...

    timer.stop();

    ...

    }

    public void actionPerformed(ActionEvent e) {

    //Advance the animation frame.

    frameNumber++;

    //Request that the frame be painted.

    label.setText("Frame " + frameNumber);

    }

    ...

    //When the application's GUI appears:

    startAnimation();

    ...

    }Hot hnhBn nn lu rng Graphics khng thc hin hot cnh mt cch tri chy ngha l i khi mt phnhay tt cc vng v b nhy.Loi tr nhy hnh

    S nhy hnh l kt qu ca hai s kin: Mc nh, nn ca hot cnh s b xo (n bao gm c vng nn v li) trc khi phng thcpaint()c gi. Thao tc ca phng thcpaint()lm cho my tnh khng th thc hin cc hot cnh vitn sut hin th cao. Kt qu l mt phn ca hot cnh c b qua.B qua phng thc update() loi tr s nhy hnh,bn nn b qua phng thc update(). L do l nm trong cch yu cu caAWT ti cc thnh phn t v li n (nh Applet, Canvas, hoc Frame) repaint itself.

    AWT yu cu v li bngz cch gi phng thcupdate()ca cc thnh phn. Mc nh phngthcupdate()x nn cc thnh phn trc khi gi phng thcpaint(). Bi v loi tr nhy hnhl loi tr cc thao tc v khng cn thit , nn bc u tin phi b qua phng thcupdate()vth n ch xo nn cc thnh phn khi cn thit. Khi lnh v c chuyn t phng thcpaint()n phng thcupdate(),bn nn cn sa i lnh v do n s khng ph thuc vo vic nnc b xo hay khngV d:

    public void paint(Graphics g) {

    update(g);}

    public void update(Graphics g) {

    Color bg = getBackground();Color fg = getForeground();

    ...//same as old paint() method until we draw the rectangle:

    if (fillSquare) {

    g.fillRect(x, y, w, h);

    fillSquare = false;

    } else {

    g.setColor(bg);g.fillRect(x, y, w, h);g.setColor(fg);

    Smith Nguyen Studio.

  • 8/3/2019 Java UI - Smith.N Studio

    47/49

    47

    fillSquare = true;

    }

    ...//same as old paint() method

    }

    Ct ta vng vMt k thut m bn c th s dng trong phng thcupdate()l clippingvng c v.Vic ct ta c thc hin bi phng thcclipRect() method.

    Chuyn ng nh qua mn hnhCch n gin nht to hot cnh l di chuyn mt hnh nh trn mn hnh. Trong th gii ca hotcnh truyn thng, iu ny c gi l cutout animation.C hai hnh m applet s dng.

    V y l giao din ca applet. Cn lu l khi ng hay dng applet th click chut ln applet.

    Lu : hnhrocketship c nh nn l transparent.

    on m thc hin hot cnh ny khng my phc tp. Ni chung, n cng ging nh xn a ra

    bn trn. Thay v s dng mt label thc hin hot cnh th n s dng mt thnh phn ty bin.Thnh phn ty bin y l lp con ca JPanel nhm thc thi vic v c hai hnh nh trn:...//Where the images are initialized:

    Image background = getImage(getCodeBase(),

    "images/rocketship.gif");

    Image foreground = getImage(getCodeBase(),

    "images/starfield.gif");

    ...

    public void paintComponent(Graphics g) {

    super.paintComponent(g); //paint any space not covered

    //by the background image

    int compWidth = getWidth();

    int compHeight = getHeight();

    //If we have a valid width and height for the

    //background image, paint it.

    imageWidth = background.getWidth(this);

    imageHeight = background.getHeight(this);

    if ((imageWidth > 0) && (imageHeight > 0)) {

    g.drawImage(background,

    (compWidth - im