Gestionare curs,java

download Gestionare curs,java

of 14

Transcript of Gestionare curs,java

  • 7/31/2019 Gestionare curs,java

    1/14

    Gestionarea pozi]ion\rii

    Crearea obiectelor grafice nu realizeaz\ automat [iafi[area lor pe ecran. Mai nti ele trebuie a[ezate pe o

    suprafa]\, care poate fi o fereastr\ sau suprafa]\ unui applet, [ivor deveni vizibile n momentul n care suprafa]a pe care suntafi[ate va fi vizibil\. O astfel de suprafa]\ pe care se a[eaz\obiectele grafice reprezint\ o instan]\ a unei clase ob]inut\ prinextensia clasei Container.

    Ad\ugarea unui obiect grafic pe suprafa]a unui containerse face cu instruc]iunea add().

    Pozi]ionarea automat\ a controalelor se face de la stngala dreapta, n limita spa]iului disponibil, trecndu-se la

    urm\torul rnd cns spa]iul este insuficient. Aceasta nseamn\c\ redimensionarea ferestrei poate provoca rearanjareacontroalelor 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 este

    Panel

    Container

    Window

    Applet Frame Dialog

  • 7/31/2019 Gestionare curs,java

    2/14

    BorderLayout, care [tie s\ dispun\ componentele n 5 pozi]iicorespunz\toare celor 4 puncte cardinale [i centrului.

    Gestionarul FlowLayout

    Acest gestionar a[eaz\ componentele pe suprafa]a deafi[are n flux liniar, mai precis, componentele sunt ad\ugateuna dup\ alta pe linii, n limita spa]iului disponibil. Inmomentul cnd o component\ nu mai ncape pe linia curent\se trece la urm\toarea linie, de sus n jos.

    Ad\ugarea componentelor se face de la stnga ladreapta pe linie iar alinierea poate fi de trei feluri :

    la stnga la drepata centrate

    Distan]a implicit\ ntre componente este de 5 unit\]i pevertical\ [i 5 pe orizontal\.

    Este gestionarul implicit al clasei Applet.Utilizarea cea mai frevent\ o are la amplasarea mai

    multor butoane ntr-un Panel.Dimeniunile componentelor afi[ate sunt preluate

    automat de c\tre gestionar prin intermediul metodeigetPreferredSize(), implementat\ de toate componentelestandard.

    Exemplu:.setLayout(new FlowLayout());.add(new Button(OK));

    Constructoripublic FlowLayout( )

    Construieste un gestionar cu aliniere pe centru, si cu distanta

    ntre componente de 5 unitati att pe orizontala, ct si peverticalapublic FlowLayout( int align )

    Parametrul align specifica alinierea si este una din variabilele :FlowLayout.LEFT, FlowLayout.RIGHT, or FlowLayout.CENTER.

    public FlowLayout( int align, int hgap, int vgap )hgap = distanta pe orizontala ntre componentevgap = distanta pe verticala ntre linii

  • 7/31/2019 Gestionare curs,java

    3/14

    Variabilepublic static final int LEFTpublic static final int CENTERpublic static final int RIGHT

    Metodeint getAlignment( )void setAlignment( int align )int getHgap( )void setHgap( int hgap )int getVgap( )void setVgap( int vgap )

    void addLayoutComponent(java.lang.String name, java.awt.Component comp )void layoutContainer( java.awt.Container target )java.awt.Dimension minimumLayoutSize( java.awt.Container target )java.awt.Dimension preferredLayoutSize( java.awt.Container target )void removeLayoutComponent( java.awt.Component comp )java.lang.String toString( )

    Gestionarul BorderLayout

    Gestionarul BorderLayout mparte suprafa]a de afi[are n5 regiuni, corespunz\toare celor 4 puncte cardinale [icentrului. O component\ poate fi plasat\ n oricare din acesteregiuni, dimeniunea componentei fiind calculat\ astfel nct s\ocupe ntreg spa]iul de afi[are oferit de regiunea respectiv\.Pentru a ad\uga mai multe obiecte grafice ntr-una din cele 5

    zone, ele trebuie grupate n prealabil ntr-un Panel, care va fiamplasat apoi n regiunea dorit\.

    North

    Wes

    t

    South

    EastCenter

  • 7/31/2019 Gestionare curs,java

    4/14

    A[adar la ad\ugarea unei componente pe o suprafa]agestionat\ de BorderLayout, metoda add() va mai primi pelng\ numele componentei [i zona n care aceasta va fiamplasat\, acesta fiind apecificat\ prin una din constantele

    North, South, West, East,sau Center.

    Exemplu:.setLayout(new BorderLayout());.add(South, new Button(OK));

    Constructoripublic BorderLayout( )

    Construieste un gestionar fara nici o disatnta ntre componentepublic BorderLayout( int hgap, int vgap )

    Construieste un gestionar cu distantele specificate ntrecomponente

    Variabilepublic static final java.lang.String NORTHpublic static final java.lang.String SOUTHpublic static final java.lang.String EASTpublic static final java.lang.String WESTpublic static final java.lang.String CENTER

    Metodeint getHgap( )void setHgap( int hgap )

    int getVgap( )void setVgap( int vgap )

    void addLayoutComponent(java.lang.String name, java.awt.Component comp )void addLayoutComponent( java.awt.Component comp,

    java.lang.Object constraints )float getLayoutAlignmentX( java.awt.Container parent )float getLayoutAlignmentY( java.awt.Container parent )void invalidateLayout( java.awt.Container target )void layoutContainer( java.awt.Container target )java.awt.Dimension maximumLayoutSize( java.awt.Container target )java.awt.Dimension minimumLayoutSize( java.awt.Container target )java.awt.Dimension preferredLayoutSize( java.awt.Container target )void removeLayoutComponent( java.awt.Component comp )java.lang.String toString( )

    Gestionarul CardLayout

    Acest gestionar trateaz\ componentele ad\ugate pe suprafa]antr-o manier\ asem\n\toare cu cea a dispunerii c\r]ilor de jocnntr-un pachet. Suprafa]a de afi[are poate fi asem\nat\ cu

  • 7/31/2019 Gestionare curs,java

    5/14

    pachetul de c\r]i iar fiecare component\ este o carte dinpachet. La un moment dat numai o singur\ component\ estevizibil\ (cea de deasupra). Clasa dispune de metode princare s\ poat\ fi afi[at\ o anumit\ component\ din pachet, sau s\

    se poat\ parcurge secven]ial pachetul, ordinea n carecomponentele se g\sesc n pachet fiind intern\ gestionaruluiAcest gestionar este util pentru implementarea unor cutii

    de dialog de tip tab, n care pentru o gestionare mai eficient\ aspa]iului, componentele sunt grupate n pachete, la unmoment dat utilizatorul interac]ionnd cu un singur pachet,celelate fiind ascunse.

    Ad\ugarea unei componente pe o suprafa]\ de afi[aregestionat\ de CardLayout se face prin metoda add, dar nurm\torul format :

    add(String id_componenta, Component componenta),unde id_componenta este un etichet\ prin care va fi identificat\componenta respectiv\ n interiorul pachetului.

    Constructoripublic CardLayout( )

    Creeaza un gestionar cu distanta ntre componente 0public CardLayout( int hgap, int vgap )

    Creeaza un gestionar cu distanta specificata ntre componente

    Metodeint getHgap( )void setHgap( int hgap )int getVgap( )void setVgap( int vgap )

    void addLayoutComponent(java.lang.String name, java.awt.Component comp )void addLayoutComponent( java.awt.Component comp,

    java.lang.Object constraints )void first( java.awt.Container parent )

    Face vizibila prima component\ a containerului parentfloat getLayoutAlignmentX( java.awt.Container parent )float getLayoutAlignmentY( java.awt.Container parent )void invalidateLayout( java.awt.Container target )

    void last( java.awt.Container parent )Face vizibila ultima component\ a containerului parent

    void layoutContainer( java.awt.Container parent )java.awt.Dimension maximumLayoutSize( java.awt.Container target )java.awt.Dimension minimumLayoutSize( java.awt.Container parent )void next( java.awt.Container parent )

    java.awt.Dimension preferredLayoutSize( java.awt.Container parent )void previous( java.awt.Container parent )

  • 7/31/2019 Gestionare curs,java

    6/14

    void removeLayoutComponent( java.awt.Component comp )void show( java.awt.Container parent, java.lang.String name )

    Specific\ noua component\ care se dore[te a fi la suprafa]\java.lang.String toString( )

    Exemplu:

    Afi[eaz\ dou\ butoane btn1, cu eticheta Text [i btn2, cueticheta Buton,[i un panel tab gestionat de CardLayout. La tabad\ugam dou\ componente (una pentru editare text [i unbuton). Selectarea butonului Text face vizibil\ componenta deeditare iar selectarea butonului Buton face vizibil butonul.

    import java.awt.*;import java.awt.event.*;

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

    Button btn1 = new Button("Text");Button btn2 = new Button("Buton");

    Panel butoane = new Panel();butoane.setLayout(new FlowLayout());butoane.add( btn1);butoane.add(btn2);

    Panel tab = new Panel();tab.setLayout(new CardLayout());

    TextField tf = new TextField("Text Field");Button btn = new Button("Button");

    tab.add("Text", tf);tab.add("Buton", btn);

    Fereastra f = new Fereastra("Test Card Layout", tab);f.setLayout(new BorderLayout());

    f.add("North", butoane);f.add("Center", tab);f.pack();f.show();

    btn1.addActionListener(f);btn2.addActionListener(f);

    }}

    class Fereastra extends Frame implements WindowListener, ActionListener{

    Panel tab;public Fereastra(String titlu, Panel tab) {

    super(titlu);this.addWindowListener(this);this.tab = tab;

  • 7/31/2019 Gestionare curs,java

    7/14

    }

    //metodele interfetei WindowListenerpublic void windowOpened(WindowEvent e) {}public void windowClosing(WindowEvent e) {System.exit(0);}public void windowClosed(WindowEvent e) {}public void windowDeiconified(WindowEvent e) {}public void windowIconified(WindowEvent e) {}public void windowActivated(WindowEvent e) {}public void windowDeactivated(WindowEvent e) {}

    public void actionPerformed(ActionEvent e) {String careTab = e.getActionCommand();System.out.println(e.toString());CardLayout gestionar = (CardLayout) tab.getLayout();gestionar.show(tab, careTab);

    }}

    Gestionarul GridLayout

    Acest gestionar, mai pu]in utilizat, organizeaz\ containerul caun tabel cu rnduri [i coloane, componentele fiind plasate nc\su]ele tabelului de la stnga la dreapta ncepnd cu primulrnd. C\su]ele tabelului au dimensiuni egale iar o component\poate ocupa doar o singur\ c\su]\. Num\rul de linii [i coloanepoate fi specificat n constructorul gestionarului dar poate fimodificat [i ulterior prin metodele setRows [i setCols. De

    asemenea, distan]a ntre componente pe orizontal\ [i distan]antre rndurile tabelului pot fi specificate n constructor saustabilite ulterior.

    Acest tip de gestionar poate fi util n implementarea unorcomponente de tip calculator, n care numerele [i opera]iilesunt afi[ate prin intermediul unor butoane dispuse sub formaunei grile.Constructoripublic GridLayout( )

    Creeaz\ un gestionar 1x1

    public GridLayout( int rows, int cols )Creeaz\ un gestionar cu dimensiunile specificate. Dac\ una din dimensiunieste 0, pe cealalt\ dimeniune pot fi plasate un num\r nelimitat decomponente.

    public GridLayout( int rows, int cols, int hgap, int vgap )

    Se specific\ [i distan]ele ntre componenteObs: Ultimii doi constructori pot genera o excep]ie de tipulIllegalArgumentException dac\ num\rul de linii sau coloane specificat este incorect.

  • 7/31/2019 Gestionare curs,java

    8/14

    Metodeint getColumns( )void setColumns( int cols )int getHgap( )void setHgap( int hgap )int getRows( )

    void setRows( int rows )int getVgap( )void setVgap( int vgap )

    void addLayoutComponent(java.lang.String name, java.awt.Component comp )void layoutContainer( java.awt.Container parent )java.awt.Dimension minimumLayoutSize( java.awt.Container parent )java.awt.Dimension preferredLayoutSize( java.awt.Container parent )void removeLayoutComponent( java.awt.Component comp )java.lang.String toString( )

    Exemplu:import java.awt.*;

    import java.applet.Applet;public class ButtonGrid extends Applet {

    public void init() {setLayout(new GridLayout(3,2));add(new Button("1"));add(new Button("2"));add(new Button("3"));add(new Button("4"));add(new Button("5"));add(new Button("6"));

    }}

    Gestionarul de pozi]ionare GridBagLayout

    Este cel mai comples [i flexibil gestionar de pozi]ionare dinJava.La fe ca n cazul gestionarului GridLayout, suprafa]a de afi[areeste considerat\ ca fiind un tabel, ns\, spre deosebire deacesta, num\rul de linii [i de coloane sunt determinateautomat, n func]ie de componentele amplasate pe suprafa]ade afi[are. De asemenea, n func]ie de componentele

    gestionate, dimensiunile c\su]elor pot fi diferite, cu singurelerestric]ii c\ pe aceea[i linie c\su]ele trebuie s\ aib\ aceea[in\l]ime, iar pe coloan\ trebuie s\ aib\ aceea[i l\]ime. Spredeosebire de GridLayout o component\ poate ocupa mai multecelule adiacente, chiar de dimensiuni diferite, zona ocupat\fiind referit\ prin regiunea de afi[are a componenteirespective.

  • 7/31/2019 Gestionare curs,java

    9/14

    Pentru a specifica modul de afi[are al unei componente,acesteia i poate fi asociat un obiect de tip GridBagConstraints,

    n care se specific\ diferite propriet\]i ale componenteireferitoare la regiunea sa de afi[are [i la modul n care va fi

    plasat\ n aceast\ regiune.Leg\tura dintre o component\ [i un obiectGridBagConstraints se realizeaz\ prin metode setConstraints :Ex:

    GridBagLayout gridBag = new GridBagLayout();setLayout(gridBag);GridBagConstraints c = new GridBagConstraints();

    //se specifica propriet\]ile rederitoare la afi[area componentei//...gridBag.add(, c);add.

    Clasa GridBagLayout

    Constructorpublic GridBagLayout( )

    Variabileprotected static final int MAXGRIDSIZEprotected static final int MINSIZEprotected static final int PREFERREDSIZEprotected java.util.Hashtable comptableprotected java.awt.GridBagConstraints defaultConstraintsprotected java.awt.GridBagLayoutInfo layoutInfo

    public int[] columnWidthspublic int[] rowHeightspublic double[] columnWeightspublic double[] rowWeights

    Metode

    int[][] getLayoutDimensions( )java.awt.Point getLayoutOrigin( )double[][] getLayoutWeights( )

    void addLayoutComponent(java.lang.String name, java.awt.Component comp )void addLayoutComponent( java.awt.Component comp,

    java.lang.Object constraints )java.awt.GridBagConstraints getConstraints( java.awt.Component comp )float getLayoutAlignmentX( java.awt.Container parent )float getLayoutAlignmentY( java.awt.Container parent )void invalidateLayout( java.awt.Container target )void layoutContainer( java.awt.Container parent )java.awt.Point location( int x, int y )java.awt.Dimension maximumLayoutSize( java.awt.Container target )java.awt.Dimension minimumLayoutSize( java.awt.Container parent )java.awt.Dimension preferredLayoutSize( java.awt.Container parent )

  • 7/31/2019 Gestionare curs,java

    10/14

    void removeLayoutComponent( java.awt.Component comp )void setConstraints( java.awt.Component comp,

    java.awt.GridBagConstraints constraints )java.lang.String toString( )

    Clasa GridBagConstraints

    Constructorpublic GridBagConstraints( )

    Variabile

    public static final int RELATIVESpecify that this component is the next-to-last component in itscolumn or row (gridwidth, gridheight), or that this component be

    placed next to the previously added component (gridx, gridy).public static final int REMAINDER

    Specify that this component is the last component in its columnor row.

    public static final int NONEDo not resize the component.

    public static final int BOTHResize the component both horizontally and vertically.

    public static final int HORIZONTALResize the component horizontally but not vertically.

    public static final int VERTICALResize the component vertically but not horizontally.

    public static final int CENTER

    Put the component in the center of its display area.public static final int NORTHPut the component at the top of its display area, centeredhorizontally.

    public static final int NORTHEASTPut the component at the top-right corner of its display area.

    public static final int EASTPut the component on the left side of its display area, centeredvertically.

    public static final int SOUTHEASTPut the component at the bottom-right corner of its display area.

    public static final int SOUTHPut the component at the bottom of its display area, centeredhorizontally.

    public static final int SOUTHWESTPut the component at the bottom-left corner of its display area.

    public static final int WESTPut the component on the left side of its display area, centeredvertically.

    public static final int NORTHWESTPut the component at the top-left corner of its display area.

  • 7/31/2019 Gestionare curs,java

    11/14

    public int gridx

    Specifies the cell at the left of the component's display area, wherethe leftmost cell has gridx = 0. The value RELATIVE specifies that thecomponent be placed just to the right of the component that was addedto the container just before this component was added.The default value is RELATIVE.

    public int gridy

    Specifies the cell at the top of the component's display area, wherethe topmost cell has gridy = 0. The value RELATIVE specifies that thecomponent be placed just below the component that was added to thecontainer just before this component was added.The default value is RELATIVE.

    public int gridwidth

    Specifies the number of cells in a row for the component's displayarea.Use REMAINDER to specify that the component be the last one in its row.Use RELATIVE to specify that the component be the next-to-last one inits row.

    The default value is 1.

    public int gridheight

    Specifies the number of cells in a column for the component's displayarea.Use REMAINDER to specify that the component be the last one in itscolumn. Use RELATIVE to specify that the component be the next-to-lastone in its column.The default value is 1.

    public double weightx

    Specifies how to distribute extra horizontal space.

    The grid bag layout manager calculates the weight of a column to be themaximum weighty of all the components in a row. If the resulting layoutis smaller horizontally than the area it needs to fill, the extra spaceis distributed to each column in proportion to its weight. A columnthat has a weight zero receives no extra space.If all the weights are zero, all the extra space appears between thegrids of the cell and the left and right edges.The default value of this field is 0.

    public double weighty

    Specifies how to distribute extra vertical space.The grid bag layout manager calculates the weight of a row to be themaximum weightx of all the components in a row. If the resulting layout

    is smaller vertically than the area it needs to fill, the extra spaceis distributed to each row in proportion to its weight. A row that hasa weight of zero receives no extra space.If all the weights are zero, all the extra space appears between thegrids of the cell and the top and bottom edges.The default value of this field is 0.

    public int anchor

  • 7/31/2019 Gestionare curs,java

    12/14

    This field is used when the component is smaller than its display area.It determines where, within the display area, to place the component.Possible values are CENTER, NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH,SOUTHWEST, WEST, and NORTHWEST. The default value is CENTER.

    public int fill

    This field is used when the component's display area is larger than thecomponent's requested size. It determines whether to resize thecomponent, and if so, how.The following values are valid for fill: NONE: Do not resize the component. HORIZONTAL: Make the component wide enough to fill its displayarea horizontally, but do not change its height. VERTICAL: Make the component tall enough to fill its displayarea vertically, but do not change its width. BOTH: Make the component fill its display area entirely.The default value is NONE.

    public java.awt.Insets insets

    This field specifies the external padding of the component, the minimum

    amount of space between the component and the edges of its displayarea.The default value is new Insets(0, 0, 0, 0).

    public int ipadx

    This field specifies the internal padding of the component, how muchspace to add to the minimum width of the component. The width of thecomponent is at least its minimum width plus (ipadx * 2) pixels.The default value is 0.

    public int ipady

    This field specifies the internal padding, that is, how much space toadd to the minimum height of the component. The height of the component

    is at least its minimum height plus (ipady * 2) pixels.The default value is 0.

    Exemplu: adaug\ la o fereastr\ componente astfel :

    import java.awt.*;import java.awt.event.*;public class TestGridBagLayout {

    public static void main(String args[]) {

  • 7/31/2019 Gestionare curs,java

    13/14

    Fereastra f = new Fereastra("Test GridBagLayout");GridBagLayout gridBag = new GridBagLayout();f.setLayout(gridBag);

    GridBagConstraints c = new GridBagConstraints();c.weightx = 1.0;c.weighty = 1.0;c.insets = new Insets(5, 5, 5, 5);

    Label l = new Label("Test GridBagLayout");l.setFont(new Font("Times New Roman", Font.BOLD | Font.ITALIC,

    24));c.gridx = 0;c.gridy = 0;c.gridwidth = 2;c.gridheight = 2;gridBag.setConstraints(l, c);f.add(l);

    Button btn1 = new Button("OK");

    c.gridx = 2;c.gridy = 0;c.gridwidth = 1;c.gridheight = 1;c.fill = GridBagConstraints.HORIZONTAL;gridBag.setConstraints(btn1, c);f.add(btn1);

    Button btn2 = new Button("Cancel");c.gridx = 2;c.gridy = 1;c.fill = GridBagConstraints.HORIZONTAL;gridBag.setConstraints(btn2, c);

    f.add(btn2);

    TextField tf = new TextField("", 20);c.gridx = 0;c.gridy = 2;c.anchor = GridBagConstraints.EAST;c.fill = GridBagConstraints.NONE;gridBag.setConstraints(tf, c);f.add(tf);

    Button btn3 = new Button("Send");c.gridx = 2;c.gridy = 2;

    c.anchor = GridBagConstraints.WEST;gridBag.setConstraints(btn3, c);f.add(btn3);

    Button btn4 = new Button("Exit");c.gridx = 0;c.gridy = 3;c.gridwidth = 3;c.fill = GridBagConstraints.BOTH;gridBag.setConstraints(btn4, c);

  • 7/31/2019 Gestionare curs,java

    14/14

    f.add(btn4);

    f.pack();f.show();}

    }class Fereastra extends Frame implements WindowListener {

    public Fereastra(String titlu) { ... }