interfa grafica

Upload: krugerr

Post on 09-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Interfa grafica

    1/19

    Interfata grafica

    INTERFA}A GRAFIC|

    Biblioteca de clase care ofer\ servicii grafice se nume[te JavaAWT (de laAbstract Window Toolkit) [i este pachetul care de

    clase care a suferit cele mai multe modific\ri n trecerea de lao versiune JDK la alta.

    Proiectarea graficii n JavaObiecte grafice :

    butoane : Button ferestre : Window meniuri : Menu liste : List

    text static : Label editare text : TextComponent pe o linie : TextField pe mai multe linii : TextArea

    combo : Choice butoane de marcare : CheckBox bare : ScrollBar ...

    Majoritatea obiectelor grafice sunt subclase ale claseiComponent. Singura excep]ie o constituie meniurile caredescind din clasa MenuComponent.

    In principal, interfa]a grafic\ serve[te interac]iunii cuutilizatorul. De cele mai multe ori programul trebuie s\ fac\ oanumit\ prelucrare n momentul n care utilizatorul a efectuato ac]iune. Deic, obiectele grafice trebuie s\ generezeevenimente n func]ie de ac]iunea pe care au suferit-o(ac]iune transmis\ de la tastatur\, mouse, etc.) Incepnd cu

    versiunea 1.1 evenimentele se implementeaz\ ca obiecteinstan]\ ale clasei java.awt.AWTEvent sau ale subclaselor ei.

    1

    Utilizator

    Obiectgrafic

    Listener

  • 8/7/2019 Interfa grafica

    2/19

    Un eveniment este produs de o ac]iune a utilizatoruluiasupra unui obiect grafic, deci evenimentele nu trebuiegenerate de programator. In schimb ntr-un program trebuiespecificat codul care se execut\ la apari]ia unui eveniment.

    Interceptarea evenimentelor se realizeaz\ prinintermediul unor clase de tip listener (ascult\tor, consumatorde evenimente). In Java, orice obiect poate consumaevenimentele generate de un anumit obiect grafic.

    Exemplu1 - afi[area obiectelor graficeimport java.applet.*;import java.awt.*;import java.awt.event.*;public class TestAWT extends Applet {

    Button cb_upper;TextField sle_text;public void init() {

    cb_buton = new Button("upper");sle_text = new TextField("Introduceti textul!");this.add(sle_text);this.add(cb_buton);

    }

    }

    Crearea obiectelor grafice nu realizeaz\ automat [iafi[area lor pe ecran. Mai nti ele trebuie a[ezate pe osuprafa]\, care poate fi o fereastr\ sau suprafa]\ unui applet,[i vor deveni vizibile n momentul n care suprafa]a pe caresunt afi[ate va fi vizibil\. O astfel de suprafa]\ pe care sea[eaz\ obiectele grafice reprezint\ o instan]\ a unei claseob]inut\ prin extensia clasei Container.

    2

    Panel

    Container

    Window

    Applet Frame Dialog

  • 8/7/2019 Interfa grafica

    3/19

    Interfata grafica

    Ad\ugarea unui obiect grafic pe suprafa]a unui container seface cu instruc]iunea add(). Intruct containerul Applet esteimplicit vizibil, n exemplul de mai sus cele dou\ obiecte vor fiafi[ate imediat dup\ ad\ugarea lor.

    Interceptarea evenimentelorIn exemplul de mai sus cele dou\ obiecte grafice erau

    func]ionale dar nu executau nimic. Pentru a specificasecven]a de cod care s\ se execute n momentul ap\s\rii

    butonului cb_upper vom introduce o clas\ special\ care vaintercepta evenimentul produs de ap\sarea butonului [i vaimplementa codul necesar.

    O clas\ care ascult\ evenimente de tip ac]iune(produse de un buton) trebuie s\ implementeze n modobligatoriu interfa]a ActionListener, unde trebuie specificat\metoda actionPerformed(Event e), care va fi apelat\ nmomentul n care sursa de evenimente va genera uneveniment ac]iune.

    De asemenea, pentru ca un obiect s\ poat\ interceptaevenimente produse de un obiect grafic al trebuie s\ se

    nregistreze drept consumator prin intermediul unei metodespecifice obiectului grafic. In cazul obiectelor caredeclan[eaz\ evenimente de tip ac]iune acest lucru se faceprin instruc]iunea : addActioListener(ActionListener obiect).

    Exemplu2 - interceptarea evenimentelor

    import java.applet.*;import java.awt.*;

    import java.awt.event.*;

    public class TestAWT extends Applet {Button cb_upper;TextField sle_text;public void init() {

    cb_upper = new Button("upper");sle_text = new TextField("Introduceti text !");this.add(sle_text);this.add(cb_upper);

    3

  • 8/7/2019 Interfa grafica

    4/19

    Ascultator a = new Ascultator(sle_text);cb_upper.addActionListener(a);

    }}

    class AscultatorActiuni implements ActionListener {private TextField sle_text;public Ascultator(TextField sle_text) {

    this.sle_text = sle_text;}public void actionPerformed (ActionEvent e) {

    String command = e.getActionCommand();if (command.equals("upper")) {

    String oldText = sle_text.getText();String upperText = oldText.toUpperCase();sle_text.setText(upperText);

    }}

    }

    Obs Pe lng\ evenimentele de tip ac]iune mai exist\ [ievenimente de tip modificare text. Interceptarea acestorase realizeaz\ similar cu cele de tip ac]iune dup\ cum sevede n urm\torul exemplu :AscultatorText at = new AscultatorText(sle_text)sle_text.setTextListener(at)//...class AscultatorText implements TextListener {

    private TextField sle_text;public AscultatorText(TextField sle_text) {

    this.sle_text = sle_text;}public void textValueChanged (TextEvent e) {

    //.........}

    }

    Toate tipurile de evenimente au la baz\ clasa Event. Acesteasunt : ActionEvent, TextEvent, WindowEvent, MouseEvent,KeyEvent, FocusEvent, ItemEvent, AdjustmentEvent,ContainerEvent, ComponentEvent.

    Interfe]ele pentru interceptarea evenimentelor mpreun\ cumetodele lor:

    ActionListener (ac]iuni asupra unui control) public void actionPerformed (ActionEvent e)

    TextListener (modificarea textului din control) textValueChanged (TextEvent e)

    4

  • 8/7/2019 Interfa grafica

    5/19

    Interfata grafica

    WindowListener (nchidere, minimizare,maximizare,etc.)

    windowOpened (WindowEvent e) windowClosing windowClosed

    windowIconified windowDeiconified windowActivated windowDeactivated

    MouseListener (ie[ire/intrare mouse, click, ap\sare,eliberare)

    mouseClicked (MouseEvent e) mousePressed mouseReleased mouseEntered mouseExited

    MouseMotionListener (mi[care, drag) mouseDragged (MouseEvent e) mouseMoved

    KeyListener (ap\sare, eliberare, tastare) keyTyped (KeyEvent e) keyPressed keyReleased

    FocusListener (preluare/pierdere focus) focusGained (FocusEvent e) focusLost

    ItemListener (selec]ie/deselec]ie obiect n lista,meniu, etc)

    itemStateChanged (ItemEvent e)

    AdjustmentListener (modificarea unei valori variindntre 2 limite, ex: ScrollBar)

    adjustmentValueChanged (AdjustmentEvent e)

    ContainerListener (ad\ugare, [tergere component\) componentAdded (ContainerEvent e) componentRemoved

    ComponentListener (redimension\ri, deplas\ri,

    ascunderi) componentResized (ComponentEvent e) componentMoved componentShown componentHidden

    Toate interfe]ele extind interfa]a java.util.EventListener

    5

  • 8/7/2019 Interfa grafica

    6/19

    Un obiect A care trebuie sa intercepteze evenimente de unanumit tip produse de un anumit obiect grafic B trebuie s\ se

    nregistreze (s\ se adauge la lista ascult\torilor) la acesta :B.addListener(A);buton.addActionListener( A );

    text.addTextListener ( A );...

    Pentru simplitate, de multe ori nu se mai declar\ o clas\separat\ care s\ asculte evenimentele generate de diferitelecomponente grafice, ci clasa respectiv\ va implementainterfe]ele necesare [i va prelucra evenimentelepublic class TestApplet extends Applet

    implements ActionListener, TextListener, ItemListener

    Dimensionarea [i pozi]ionarea controalelorDup\ execu]ia exemplelor de mai sus se poate observa c\elementele grafice au fost dimensionate [i aranjate automatde c\tre mediul Java.

    Orice component\ are asociate urm\toarele dimensiuni : curent\ : dat\ de getSize() minim\ : cel mai mic dreptunghi n care poate fi

    afi[at\ preferat\ : dimensiunea implicit\ (optim\)

    Metode :public void setSize(Dimension)public Dimension getSize()public Dimension getPreferredSize()public Dimension minDimension()

    Obs : Dimension este o clas\ care precizeaz\ n\l]imea [il\]imea unui anumit obiect :

    Dimension dim = new Dimension()dim.width = 10;dim.height = 20;

    .resize(dim);

    Pozi]ionarea automat\ a controalelor se face de lastnga la dreapta, n limita spa]iului disponibil, trecndu-sela urm\torul rnd cns spa]iul este insuficient. Aceasta

    6

  • 8/7/2019 Interfa grafica

    7/19

    Interfata grafica

    nseamn\ c\ redimensionarea ferestrei poate provocarearanjarea controalelor pe suprafa]a de afi[are.

    Modul de aranjare nu este o caracteristic\ a claseiContainer. Fiecare obiect de tip Container, sau o extensie a lui

    (Applet, Frame, Panel) are asociat un obiect care se ocup\ cudispunerea componentelor pe suprafa]a de afi[are [i care senume[te gestionar de pozi]ionare (Layout Manager). To]igestionarii de pozi]ionare implementeaz\ interfa]aLayoutManager. La instan]ierea unui container se creeaz\implicit un obiect dintr-o clas\ ce implementeaz\ interfa]aLayoutManager [i care realizeaz\ o dispunere foarte simpl\,conform\ cu descrierea anterioar\ (stngadreapta, susjos).Aceast\ clas\ se nume[te java.awt.FlowLayout.

    Pe lng\ FlowLayout, ierarhia AWT mai pune la dispozi]ie

    [i al]i gestionari de pozi]ionare. Unul dintre ace[tia esteBorderLayout, care [tie s\ dispun\ componentele n 5 pozi]iicorespunz\toare celor 4 puncte cardinale [i centrului :

    Nord

    West Center East

    South

    Exemplucb_upper = new Button(upper);cb_lower = new Button(upper);cb_reset = new Button(reset);sle_text = new TextFiled(Introduceti text:);

    LayoutManager gestionar = new BorderLayout();this.setLayout(gestionar);

    this.add(North, txt);this.add(Center, cb_reset);this.add(West, cb_upper);this.add(East, cb_lower); //.....

    Caracteristicile unei componente

    Caracteristic\ Ob]inere ModificareDimensiune Dimension getSize() void setSize(Dimension d)

    Pozi]ie Point getLocation() void setLocation (Point p)

    Dreptunghi de Rectangle getBounds() void setBounds(Rectangle r)

    7

  • 8/7/2019 Interfa grafica

    8/19

  • 8/7/2019 Interfa grafica

    9/19

    Interfata grafica

    butoane.add( cb_reset);

    this.add("North", sle_text);this.add("West", butoane);

    }}

    Controale de editareTextField - control de editare pe o singur\ linieTextArea - control de editare pe mai multe liniiAmbele sunt extensii ale clasei TextComponent.

    Clasa TextComponent

    MetodegetSelectedText ()

    Returns the selected text contained in this TextComponent.getSelectionEnd()

    Returns the selected text's end position.getSelectionStart()

    Returns the selected text's start position.

    getText()Returns the text contained in this TextComponent.isEditable()

    Returns the boolean indicating whether this TextComponent iseditable or not.

    paramString()Returns the String of parameters for this TextComponent.

    removeNotify()Removes the TextComponent's peer.

    select(int, int)Selects the text found between the specified start and endlocations.

    selectAll()Selects all the text in the TextComponent.

    setEditable(boolean)Sets the specified boolean to indicate whether or not thisTextComponent should be editable.

    setText(String)Sets the text of this TextComponent to the specified text.

    Clasa TextField

    Constructori

    9

    TextComponent

    TextField TextArea

  • 8/7/2019 Interfa grafica

    10/19

    TextField () Constructs a new TextField.TextField(int) Constructs a new TextField initialized with thespecified columns.TextField(String) Constructs a new TextField initialized with thespecified text.

    TextField(String, int) Constructs a new TextField initialized with thespecified text and columns.

    MetodeaddNotify () Creates the TextField's peer.echoCharIsSet() Returns true if this TextField has a character set forechoing.getColumns() Returns the number of columns in thisTextField.getEchoChar() Returns the character to be used for echoing.minimumSize(int)

    Returns the minimum size Dimensions needed for this TextFieldwith the specified amount of columns.

    minimumSize()Returns the minimum size Dimensions needed for this TextField.

    paramString()Returns the String of parameters for this TExtField.

    preferredSize(int)Returns the preferred size Dimensions needed for this TextFieldwith the specified amount of columns.

    preferredSize()Returns the preferred size Dimensions needed for this TextField.

    setEchoCharacter(char)Sets the echo character for this TextField.

    Obs: Sintagma echoCharreprezint\ caracterul de nlocuirefolosit pentru ascunderea datelor. De exemplu ntr-un controlde editare n care se introduce o parol\ acest caracter estede obicei asteriscul (*).

    TextField sle_text = new TextField(parola, 20)sle_text.setEchoCharacter(*);

    Clasa TextArea

    ConstructoriTextArea () Constructs a new TextArea.TextArea(int, int) Constructs a new TextArea with the specifiednumber of rows and columns.TextArea(String) Constructs a new TextArea with the specified textdisplayed.

    10

  • 8/7/2019 Interfa grafica

    11/19

    Interfata grafica

    TextArea(String, int, int) Constructs a new TextArea with the specifiedtext and number of rows and columns.TextArea(String text, int rows, int cols, int scrollbars)

    variabile scrollbars este una din variabilele statice ale claseiTextArea :

    SCROLLBARS_BOTH (implicit\) SCROLLBARS_VERTICAL_ONLY SCROLLBARS_HORIZONTAL_ONLY SCROLLBARS_NONE

    MetodeaddNotify ()

    Creates the TextArea's peer.appendText(String)

    Appends the given text to the end.getColumns()

    Returns the number of columns in the TextArea.getRows()Returns the number of rows in the TextArea.

    insertText(String, int)Inserts the specified text at the specified position.

    minimumSize(int, int)Returns the specified minimum size Dimensions of the TextArea.

    minimumSize()Returns the minimum size Dimensions of the TextArea.

    paramString()Returns the String of parameters for this TextArea.

    preferredSize(int, int)Returns the specified row and column Dimensions of theTextArea.preferredSize()

    Returns the preferred size Dimensions of the TextArea.replaceText(String, int, int)

    Replaces text from the indicated start to end position with thenew text specified.

    Clasa Button

    Este utilizat\ pentru afi[area unei componente de tip butonde ap\sare [i permite doar afi[area butoanelor cu etichete detip text.ConstructoriButton () Constructs a Button with no label.Button(String) Constructs a Button with a string label.

    11

  • 8/7/2019 Interfa grafica

    12/19

    MetodeaddNotify () Creates the peer of the button.getLabel() Gets the label of the button.paramString() Returns the parameter String of this button.setLabel(String) Sets the button with the specified label.

    12

  • 8/7/2019 Interfa grafica

    13/19

    Interfata grafica

    Fonturi [i culoriClasa Font

    BOLD The bold style constant.ITALIC The italicized style constant.

    PLAIN The plain style constant.name The logical name of this font.size The point size of this font.style The style of the font.

    ConstructorFont (String name, int style, int size)

    Creates a new font with the specified name, style and point size.

    Metodeequals (Object) Compares this object to the specifed object.

    getFamily() Gets the platform specific family name of the font.getFont(String) Gets a font from the system properties list.getFont(String, Font) Gets the specified font from the systemproperties list.getName() Gets the logical name of the font.getSize() Gets the point size of the font.getStyle() Gets the style of the font.hashCode() Returns a hashcode for this font.isBold() Returns true if the font is bold.isItalic() Returns true if the font is italic.isPlain() Returns true if the font is plain.

    toString() Converts this object to a String representation.

    Java furnizeaz\ 5 nume standard de fonturiindependente de platform\: Helvetica, TimesNewRoman,Courier, Dialog [i DialogInput. La acestea se adaug\ fontulZapfDingbat, care nu este ns\ disponibil pe o platform\ UNIXpe care ruleaz\ X Windows.Exemplu :public void paint(Graphics g) {

    Font un_font = new Font(TimesNewRoman, Font.ITALIC, 24);String un_sir = Times New Roman, italic, 24 puncte;

    g.setFont(un_font);g.drawString(un_sir, 5, height + 5);

    }

    Obs Constantele care codific\ stilul pot fi combinate prinadunare sau prin opera]ia sau logic:Font newFont = new Font(Courier, Font.BOLD | Font.ITALIC, 12);

    Numele fontului folosit ntr-o aplica]ie trebuie s\reprezinte un nume de font disponibil pe care ruleaz\

    13

  • 8/7/2019 Interfa grafica

    14/19

    aplica]ia. O list\ a tuturor fonturilor disponibile pe ma[inagazd\ se poate ob]ine astfel :

    String[] fontNames = comp.getToolkit().getFontList();

    unde comp este o component\ grafic\. Dac\ folosim metoda ncazul unui aplet comp poate fi this.public void paint(Graphics g) {

    String[] fontNames = this.getToolkit().getFontList();//Afiseaza lista tuturor fonturilor disponibilefor (int i=0; i

  • 8/7/2019 Interfa grafica

    15/19

    Interfata grafica

    getColor(String, int) Gets the specified Color property of the colorvalue.getGreen() Gets the green component.getHSBColor(float, float, float)

    A static Color factory for generating a Color object from HSB

    values.getRGB()Gets the RGB value representing the color in the default RGB

    ColorModel.getRed() Gets the red component.hashCode() Computes the hash code.toString() Returns the String representation of this Color's values.

    Exemplu:Color verde = new Color(0, 255, 0);g.setColor(Color.red);this.setBackground(verde.darker());

    Alte componente graficeClasa Checkbox

    ConstructoriCheckbox ()

    Constructs a Checkbox with no label, no Checkbox group, andinitialized to a false state.

    Checkbox(String)Constructs a Checkbox with the specified label, no Checkboxgroup, and initialized to a false state.

    Checkbox(String, CheckboxGroup, boolean)Constructs a Checkbox with the specified label, specifiedCheckbox group, and specified boolean state.

    MetodeaddNotify () Creates the peer of the Checkbox.getCheckboxGroup()

    Returns the checkbox group.getLabel()

    Gets the label of the button.getState()

    Returns the boolean state of the Checkbox.

    paramString()Returns the parameter String of this Checkbox.setCheckboxGroup(CheckboxGroup)

    Sets the CheckboxGroup to the specified group.setLabel(String)

    Sets the button with the specified label.setState(boolean)

    Sets the Checkbox to the specifed boolean state.

    15

  • 8/7/2019 Interfa grafica

    16/19

    Clasa CheckboxGroup

    ConstructorCheckboxGroup () Creates a new CheckboxGroup.

    Metode

    getCurrent () Gets the current choice.setCurrent(Checkbox) Sets the current choice to the specifiedCheckbox.toString() Returns the String representation of this CheckboxGroup'svalues.

    Clasa CheckboxGroup permite gruparea unor serii de casete devalidare corelate astfel nct numai una s\ poat\ fi selectat\ laun moment dat. Ea implementeaz\ o func]ionalitate similar\cu a butoanelor radio.

    Exemplu:CheckboxGroup grup = new CheckboxGroup();Checkbox c1 = new Checkbox(FM, grup, true);Checkbox c2 = new Checkbox(AM, grup, false);

    16

  • 8/7/2019 Interfa grafica

    17/19

    Interfata grafica

    Clasa List

    Creeaz\ liste derulante cuprinznd articole reprezentate ca[iruri de caractere din care utilizatorul poate alege unul saumai multe articole.

    ConstructoriList ()Creates a new scrolling list initialized with no visible Lines or

    multiple selections.List(int, boolean)

    Creates a new scrolling list initialized with the specified numberof visible lines and a boolean stating whether multiple selectionsare allowed or not.

    MetodeaddItem (String)

    Adauga la sfarsit

    addItem(String, int index)Adauga pe o anumit\ pozi]ie (index=0 nceput, index=-1sfr[it)addNotify()

    Creates the peer for the list.allowsMultipleSelections()

    Returns true if this list allows multiple selections.clear()

    Clears the list.countItems()

    Returns the number of items in the list.

    delItem(int)Delete an item from the list.delItems(int, int)

    Delete multiple items from the list.deselect(int)

    Deselects the item at the specified index.getItem(int)

    Gets the item associated with the specified index.getRows()

    Returns the number of visible lines in this list.getSelectedIndex()

    Get the selected item on the list or -1 if no item is selected.getSelectedIndexes()Returns the selected indexes on the list.

    getSelectedItem()Returns the selected item on the list or null if no item is

    selected.getSelectedItems()

    Returns the selected items on the list.

    17

  • 8/7/2019 Interfa grafica

    18/19

    getVisibleIndex()Gets the index of the item that was last made visible by the

    method makeVisible.isSelected(int)

    Returns true if the item at the specified index has been selected;

    false otherwise.makeVisible(int)Forces the item at the specified index to be visible.

    minimumSize(int)Returns the minimum dimensions needed for the amount of

    rows in the list.minimumSize()

    Returns the minimum dimensions needed for the list.paramString()

    Returns the parameter String of this list.preferredSize(int)

    Returns the preferred dimensions needed for the list with thespecified amount of rows.preferredSize()

    Returns the preferred dimensions needed for the list.removeNotify()

    Removes the peer for this list.replaceItem(String, int)

    Replaces the item at the given index.select(int)

    Selects the item at the specified index.setMultipleSelections(boolean)

    Sets whether this list should allow multiple selections or not.ExempluList lb_zile = new List(7, false);lb_zile.addItem(Luni);lb_zile.addItem(Marti, 1); //pozitia a 2-a//...

    Clasa Choice

    Ofer\ posibilitatea prezent\rii unei liste de op]iuni sub formaunui meniu pop-up. Unul dintre articole este selectat [i apare

    ca eticheta componentei Choice.ConstructorChoice () Constructs a new Choice.

    MetodeaddItem (String)

    Adds an item to this Choice.addNotify()

    Creates the Choice's peer.

    18

  • 8/7/2019 Interfa grafica

    19/19

    Interfata grafica

    countItems()Returns the number of items in this Choice.

    getItem(int)Returns the String at the specified index in the Choice.

    getSelectedIndex()

    Returns the index of the currently selected item.getSelectedItem()Returns a String representation of the current choice.

    paramString()Returns the parameter String of this Choice.

    select(int)Selects the item with the specified postion.

    select(String)Selects the item with the specified String.

    Clasa Label

    Permite crearea unei etichete de text.

    VariabileCENTER The center alignment.LEFT The left alignment.RIGHT The right alignment.

    ConstructoriLabel () Constructs an empty label.Label(String) Constructs a new label with the specified String oftext.Label(String, int)

    Constructs a new label with the specified String of text and thespecified alignment.

    MetodeaddNotify ()

    Creates the peer for this label.getAlignment()

    Gets the current alignment of this label.getText()

    Gets the text of this label.paramString()

    Returns the parameter String of this label.setAlignment(int)Sets the alignment for this label to the specified alignment.

    setText(String)Sets the text for this label to the specified text.

    19