Documente Academic
Documente Profesional
Documente Cultură
FACULTATEA DE INFORMATICA
PROIECTAREA INTERFEELOR
GRAFICE
Mironela Prnu
2015-2016
Acest material este destinat studentilor anului III, invatamant la distant,
specializarea Informatic.
1. Competene profesionale
Prezentarea notiunilor de baza pentru realizarea al unor interfee grafice
complexe folosind pachetul SWING din limbajul Java, precum i modul n care
Competene specifice
disciplinei
acestea pot fi utilizate n cadrul unor aplicaii de tip client-server.
Prezentarea n mod sintetic a conceptului de interfa grafic i a conceptelor
asociate acestuia, n diverse variante de implementare, ca i a diverselor
modaliti tehnice de elaborare a aplicaiilor dotate cu interfee grafice.
Intergrarea unei interfete grafice cu o baza de date.
Insusirea modului de realizare a appleturilor cat si functionarea acestor.
Deschidere catre importanta interfetei grafice in realizarea oricarui proiect.
Utilizarea de controale n Android (widget-uri)
2. Explicare i interpretare
Explicarea rolului interfetei grafice
nelegerea i explicarea functionarii unei interfete grafice
Capacitatea de realizare si implemetare a unei interfete grafice
3. Instrumental - aplicative
Corelarea cunotinelor teoretice cu abilitatea de a le aplica n practic
Posibilitatea de exemplificare a principalelor obiecte Swing
Capacitatea de implementarea a unei interfete grafice care comunica cu o baza de date
Tematica
1. https://netbeans.org/kb/docs/java/quickstart-gui.html
2. https://netbeans.org/kb/docs/java/gui-binding.html
3. https://netbeans.org/kb/docs/web/applets.html
4. https://netbeans.org/kb/docs/javaee/ecommerce/intro.html
5. https://netbeans.org/kb/trails/web.html
6. https://netbeans.org/kb/docs/web/security-webapps.html
7. https://netbeans.org/kb/docs/web/quickstart-webapps-
spring.html
8. https://netbeans.org/kb/docs/web/framework-adding-
support.html
9. https://netbeans.org/kb/docs/web/quickstart-webapps-
wicket.html
10. https://netbeans.org/kb/docs/web/jsf20-intro.html
11. https://netbeans.org/kb/docs/web/jsf20-support.html
Bibliografie
Java este fundamentul pentru aproape orice tip de aplicaie de reea i este standardul
global pentru dezvoltarea i livrarea de aplicaii mobile, jocuri, coninut Web-based, i software
pentru mediul enterprise. Cu mai mult de 9 milioane de dezvoltatori din intreaga lume, Java
permite s dezvoltm eficient i s implementm aplicaii i servicii stabile,care pot fi apoi
portabile n scopul de a rula pe o varietate larg de sisteme hardware.
Java Platform este numele pachetului de programe oferite de Oracle, care permit
dezvoltarea i rularea de programe scrise n limbajul de programare Java. Platforma nu este
specific pentru un procesor sau un sistem de operare si este format dintr-un motor de execuie
(numit main virtual) i un compilator cu un set de biblioteci care sunt puse n aplicare pentru
diverse sisteme de operare i hardware, astfel nct programele Java s poat rula identic pe
toate dintre acestea.
Platforma Java const din mai multe programe, fiecare dintre ele oferind o poriune din
capacitile sale generale. De exemplu, compilatorul Java, care convertete codul surs Java n
Java bytecode (un limbaj intermediar pentru JVM), este furnizat ca parte a Java Development
Kit (JDK).
Componentele eseniale ale platformei sunt compilatorul limbajului Java, bibliotecile
i mediul de execuie (maina virtual).
Java Card se refer la o tehnologie care permite aplicaiilor bazate pe Java (applet-uri), de a fi
rulate n siguran pe carduri inteligente i dispozitive similare. Java Card este cea mai mic
component a platformei Java vizate pentru dispozitivele integrate. Java Card ofer
utilizatorului posibilitatea de a programa micro dispozitive i a le crea aplicaii specifice.
Acesta este utilizat pe scar larg n cartele SIM (utilizate n telefoanele mobile GSM) i carduri
de ATM-uri. Principalele obiective de proiectare ale tehnologiei Java Card sunt portabilitatea
i securitatea.
Java ME (Micro Edition) reprezint este o platform Java proiectat pentru sisteme integrate
(dispozitivele mobile). Dispozitivele int variaz de la controalele industriale la telefoane
mobile i set-top boxuri. Java ME a fost cunoscut anterior ca platforma Java 2, Micro Edition
(J2ME). Java ME a fost conceput de Sun Microsystems, achiziionat de Oracle Corporation n
2010, ce a nlocuit o platforma de tehnologie similar cunoscut sub numele de PersonalJava.
Aceasta a fost iniial dezvoltat de Java Community Process ca JSR 68, de diferite platarome
Java ME care au evoluat n JSRs separate.
Exist mai mult de 2,1 miliarde de activri Java ME pe telefoane mobile i PDA-uri. Dei nu
este folosit pe unele dintre cele mai noi platforme mobile de azi (de exemplu, iPhone, Windows
Phone, BlackBerry 10, Android), aceasta continu s fie foarte popular pe dispozitive ieftine
(<200 dolari), cum ar fi Nokia Seria 40. De asemenea, este utilizat pe noul sistem de operare
Bada i pe sistemul de operare Symbian, mpreun cu software-ul nativ. Exista implementari
pentru Windows CE, Windows Mobile, Maemo, MeeGo si Android disponibil pentru
descrcare separat.
Java SE (Standard Edition): este o platform utilizat pe scar larg pentru dezvoltarea i
implementarea de aplicaii portabile pentru mediile tip desktop si server. Java SE foloseste
limbajul de programare orientat-obiect Java i definete o gam larg de API-uri de uz general,
cum ar fi API-uri pentru clasa Java.Library care include i Java Virtual Machine
Specification.Una dintre cele mai cunoscute implementari de Java SE este Java Development
Kit (JDK).
Java EE (Enterprise Edition) este platforma de calcul enterprise a lui Oracle. Platforma ofer
un API i mediu de rulare pentru dezvoltarea i rularea de software enterprise, inclusiv servicii
de reea i de Internet, precum i alte aplicaii de reea la scar larg, fiabile i sigure. Java EE
extinde Java Platform, Standard Edition (Java SE) i ofer un API pentru Object-relational
mapping ORM(software ce convertete datele intre tipuri de sisteme), arhitecturi multi-tier i
servicii web. Platforma include un design bazat n mare msur pe componente modulare care
ruleaz pe un server de aplicaii. Software-ul pentru Java EE este dezvoltat n primul rnd n
limbajul de programare Java.
Acest ghid ofer o introducere foarte simplu i rapid, pentru fluxul de lucru NetBeans IDE de
mers pe jos v prin crearea unui simplu "Hello World" Java Console cerere. Odat ce ai
terminat cu acest tutorial, veti avea o cunoatere general a modului de a crea i rula aplicaii
n IDE.
Dup ce terminai acest tutorial, putei trece la trasee de nvare, care sunt legate de la
documentare, Training & pagina de sprijin. Partii de nvare prevd tutoriale cuprinztoare
care evideniaz o gam mai larg de caracteristici IDE i tehnici de programare pentru o
varietate de tipuri de aplicare . Dac nu vrei s faci un "Hello World" aplicaie, putei sri
peste acest tutorial si sari direct la trasee de nvare.
Configurarea de proiect
Etapele urmtoare
Configurarea de proiect
2. n IDE, alegeti File> New Project (Ctrl-Shift-N), aa cum se arat n figura de mai
jos.
3. n expertul New Project, extindei categoria Java i selectai aplicaie Java aa cum se
arat n figura de mai jos. Apoi, facei clic pe Next.
Fereastra Navigator, pe care o putei utiliza pentru a naviga rapid ntre elemente din cadrul
clasei selectat.
Adugarea Cod la Sursa Generated File
cu linia:
System.out.println ( "Hello World!");
A memora modificarea prin alegerea Fiier> Salvare.
Fiierul ar trebui s arate ceva de genul mostra de cod de mai jos.
/*
* Pentru a schimba acest ablon, alegeti Tools | Template-uri
* i deschide ablon n editor.
*/
HelloWorldApp pachet;
Dac exist erori de compilare, acestea sunt marcate cu simbolurile rou n marginile din
stnga i din dreapta a Editor Source. Simbolurile, n marginea din stnga a indica erorile
pentru liniile corespunztoare. Simbolurile n marja de dreptul de a afia toate zonele din
dosar care au erori, inclusiv erori, n linii care nu sunt vizibile. Avei posibilitatea s cursorul
peste un semn de eroare pentru a obine o descriere a erorii. Avei posibilitatea s facei clic
pe un simbol n marja de dreptul de a sri la linia cu eroarea.
Dup ce ai scris i testa rula aplicaia dvs., putei utiliza comanda "curate" i Generare pentru
a construi cererea dumneavoastr, n vederea detarii. Cnd utilizai Clean i comanda
Construirea, IDE opereaza un construi script care ndeplinete urmtoarele atribuii:
Putei vedea construi iesiri prin deschiderea fereastra Fiiere i extinderea nodul
HelloWorldApp. Bytecode compilat fiier HelloWorldApp.class este n
build/classes/helloworldapp subnode build/classes/helloworldapp Dislocabile JAR Un fiier
care conine HelloWorldApp.class este n nodul dist
Aplicatia 2 .Proiectarea unei GUI n NetBeans IDE
Designing a Swing GUI in NetBeans IDE
This tutorial guides you through the process of creating the graphical user interface (GUI) for
an application called ContactEditor using the NetBeans IDE GUI Builder. In the process you
will layout a GUI front-end that enables you to view and edit contact information of
individuals included in an employee database.
In this tutorial you will learn how to: use the GUI Builder Interface, create a GUI Container,
add, resize, and align components, adjust component anchoring, set component auto-resizing
behavior, edit component properties.
Contents
Getting Started
o Creating a Project
o Creating a JFrame Container
Getting Familiar with the GUI Builder
Key Concepts
o Free Design
o Automatic Component Positioning (Snapping)
o Visual Feedback
First Things First
o Adding Components: The Basics
o Adding Individual Components to the Form
o Adding Multiple Components to the Form
o Inserting Components
Moving Forward
o Component Alignment
o Baseline Alignment
Reviewing What We've Learned
o Adding, Aligning, and Anchoring
o Component Sizing
o Indentation
Making the Final Adjustments
Previewing Your GUI
Deploying GUI Applications
See Also
To complete this tutorial, you need the following software and resources.
Software or Resource Version Required
NetBeans IDE version 6.9, 7.0, 7.1, 7.2, 7.3, or 7.4
Java Development Kit (JDK) version 6 or 7
Getting Started
The IDE's GUI Builder makes it possible to build professional-looking GUIs without an
intimate understanding of layout managers. You can lay out your forms by simply placing
components where you want them.
For descriptions of the GUI Builder's visual feedback, you can use the GUI Builder Visual
Feedback Legend.
Creating a Project
Because all Java development in the IDE takes place within projects, we first need to create a
new ContactEditor project within which to store sources and other project files. An IDE project
is a group of Java source files plus its associated meta data, including project-specific properties
files, an Ant build script that controls the build and run settings, and a project.xml file that maps
Ant targets to IDE commands. While Java applications often consist of several IDE projects,
for the purposes of this tutorial, we will build a simple application which is stored entirely in a
single project.
1. Choose File > New Project. Alternately, you can click the New Project icon
in the IDE toolbar.
2. In the Categories pane, select the Java node and in the Projects pane, choose
Java Application. Click Next.
3. Enter ContactEditor in the Project Name field and specify the project location.
4. Leave the Use Dedicated Folder for Storing Libraries checkbox unselected.
5. Ensure that the Set as Main Project checkbox is selected and clear the Create
Main Class field.
6. Click Finish.
The IDE creates the ContactEditor folder on your system in the designated
location. This folder contains all of the project's associated files, including its
Ant script, folders for storing sources and tests, and a folder for project-
specific metadata. To view the project structure, use the IDE's Files window.
Creating a JFrame Container
After creating the new application, you may have noticed that the Source Packages folder in
the Projects window contains an empty <default package> node. To proceed with building our
interface, we need to create a Java container within which we will place the other required
GUI components. In this step we'll create a container using the JFrame component and place
the container in a new package.
The IDE creates the ContactEditorUI form and the ContactEditorUI class within
the ContactEditorUI.java application and opens the ContactEditorUI form in the
GUI Builder. Notice that the my.contacteditor package replaces the default
package.
top
Getting Familiar with the GUI Builder
Now that we've set up a new project for our application, let's take a minute to familiarize
ourselves with the GUI Builder's interface.
Note: To explore the GUI Builder interface with an interactive demo, view the Exploring GUI
Builder (.swf) screencast.
When we added the JFrame container, the IDE opened the newly-created ContactEditorUI form
in an Editor tab with a toolbar containing several buttons, as shown in the preceding
illustration. The ContactEditor form opened in the GUI Builder's Design view and three
additional windows appeared automatically along the IDE's edges, enabling you to navigate,
organize, and edit GUI forms as you build them.
Design Area. The GUI Builder's primary window for creating and editing Java GUI
forms. The toolbar's Source button enables you to view a class's source code, the
Design button allows you to view a graphical view of the GUI components, the
History button allows you to access the local history of changes of the file. The
additional toolbar buttons provide convenient access to common commands, such as
choosing between Selection and Connection modes, aligning components, setting
component auto-resizing behavior, and previewing forms.
Navigator. Provides a representation of all the components, both visual and non-
visual, in your application as a tree hierarchy. The Navigator also provides visual
feedback about what component in the tree is currently being edited in the GUI
Builder as well as allows you to organize components in the available panels.
Palette. A customizable list of available components containing tabs for JFC/Swing,
AWT, and JavaBeans components, as well as layout managers. In addition, you can
create, remove, and rearrange the categories displayed in the Palette using the
customizer.
Properties Window. Displays the properties of the component currently selected in
the GUI Builder, Navigator window, Projects window, or Files window.
If you click the Source button, the IDE displays the application's Java source code in the
Editor with sections of code that are automatically generated by the GUI Builder indicated by
grey areas (they become blue when selected), called Guarded Blocks. Guarded blocks are
protected areas that are not editable in Source view. You can only edit code appearing in the
white areas of the Editor when in Source view. If you need to make changes to the code
within a Guarded Block, clicking the Design button returns the IDE's Editor to the GUI
Builder where you can make the necessary adjustments to the form. When you save your
changes, the IDE updates the file's sources.
Note: For advanced developers, the Palette Manager is available that enables you to add
custom components from JARs, libraries, or other projects to the Palette. To add custom
components through the Palette Manager, choose Tools > Palette > Swing/AWT Components.
top
Key Concepts
The IDE's GUI Builder solves the core problem of Java GUI creation by streamlining the
workflow of creating graphical interfaces, freeing developers from the complexities of Swing
layout managers. It does this by extending the current NetBeans IDE GUI Builder to support a
straightforward "Free Design" paradigm with simple layout rules that are easy to understand
and use. As you lay out your form, the GUI Builder provides visual guidelines suggesting
optimal spacing and alignment of components. In the background, the GUI Builder translates
your design decisions into a functional UI that is implemented using the new GroupLayout
layout manager and other Swing constructs. Because it uses a dynamic layout model, GUI's
built with the GUI Builder behave as you would expect at runtime, adjusting to accommodate
any changes you make without altering the defined relationships between components.
Whenever you resize the form, switch locales, or specify a different look and feel, your GUI
automatically adjusts to respect the target look and feel's insets and offsets.
Free Design
In the IDE's GUI Builder, you can build your forms by simply putting components where you
want them as though you were using absolute positioning. The GUI Builder figures out which
layout attributes are required and then generates the code for you automatically. You need not
concern yourself with insets, anchors, fills, and so forth.
Automatic Component Positioning (Snapping)
As you add components to a form, the GUI Builder provides visual feedback that assists in
positioning components based on your operating system's look and feel. The GUI Builder
provides helpful inline hints and other visual feedback regarding where components should be
placed on your form, automatically snapping components into position along guidelines. It
makes these suggestions based on the positions of the components that have already been
placed in the form, while allowing the padding to remain flexible such that different target
look and feels render properly at runtime.
Visual Feedback
The GUI Builder also provides visual feedback regarding component anchoring and chaining
relationships. These indicators enable you to quickly identify the various positioning
relationships and component pinning behavior that affect the way your GUI will both appear
and behave at runtime. This speeds the GUI design process, enabling you to quickly create
professional-looking visual interfaces that work.
top
First Things First
Now that you have familiarized yourself with the GUI builder's interface, it's time to begin
developing the UI of our ContactEditor application. In this section we'll take a look at using
the IDE's Palette to add the various GUI components that we need to our form.
Thanks to the IDE's Free Design paradigm, you no longer have to struggle with layout
managers to control the size and position of the components within your containers. All you
need to do is drag and drop the components you need to your GUI form as shown in the
illustrations that follow.
Note: Refer to the Adding individual and multiple components (.swf) screencast for an
interactive demo on the section below.
Adding Components: The Basics
Though the IDE's GUI Builder simplifies the process of creating Java GUIs, it is often helpful
to sketch out the way you want your interface to look before beginning to lay it out. Many
interface designers consider this a "best practice" technique, however, for the purposes of this
tutorial you can simply peek at how our completed form should look by jumping ahead to the
Previewing your GUI section.
Since we've already added a JFrame as our form's top-level container, the next step is to add a
couple of JPanels which will enable us to cluster the components of our UI using titled
borders. Refer to the following illustrations and notice the IDE's "drag and drop" behavior
when accomplishing this.
To add a JPanel:
1. In the Palette window, select the Panel component from the Swing
Containers category by clicking and releasing the mouse button.
2. Move the cursor to the upper left corner of the form in the GUI Builder.
When the component is located near the container's top and left edges,
horizontal and vertical alignment guidelines appear indicating the preferred
margins. Click in the form to place the JPanel in this location.
Next, we need to resize the JPanel to make room for the components we'll place within it a
little later, but let's take a minute to point out another of the GUI Builder's visualization
features first. In order to do this we need to deselect the JPanel we just added. Because we
haven't added a title border yet, the panel disappears. Notice, however, that when you pass the
cursor over the JPanel, its edges change to light gray so that its position can be clearly seen.
You need only to click anywhere within the component to reselect it and cause the resize
handles and anchoring indicators to reappear.
1. Select the JPanel you just added. The small square resize handles reappear
around the component's perimeter.
2. Click and hold the resize handle on the right edge of the JPanel and drag
until the dotted alignment guideline appears near the form's edge.
3. Release the resize handle to resize the component.
The JPanel component is extended to span between the container's left and
right margins in accordance with the recommended offset, as shown in the
following illustration.
Now that we've added a panel to contain our UI's Name information, we need to repeat the
process to add another directly below the first for the E-mail information. Referring to the
following illustrations, repeat the previous two tasks, paying attention to the GUI Builder's
suggested positioning. Notice that the suggested vertical spacing between the two JPanels is
much narrower than that at the edges. Once you have added the second JPanel, resize it such
that it fills the form's remaining vertical space.
Because we want to visually distinguish the functions in the upper and lower sections of our
GUI, we need to add a border and title to each JPanel. First we'll accomplish this using the
Properties window and then we'll try it using the pop-up menu.
Now we need to start adding the components that will present the actual contact information
in our contact list. In this task we'll add four JTextFields that will display the contact
information and the JLabels that will describe them. While accomplishing this, notice the
horizontal and vertical guidelines that the GUI Builder displays, suggesting the preferred
component spacing as defined by your operating system's look and feel. This ensures that
your GUI is automatically rendered respecting the target operating system's look and feel at
runtime.
1. In the Palette window, select the Label component from the Swing Controls
category.
2. Move the cursor over the Name JPanel we added earlier. When the guidelines
appear indicating that the JLabel is positioned in the top left corner of the
JPanel with a small margin at the top and left edges, click to place the label.
The JLabel is added to the form and a corresponding node representing the
component is added to the Inspector window.
Before going further, we need to edit the display text of the JLabel we just added. Though you
can edit component display text at any point, the easiest way is to do this as you add them.
Now we'll add a JTextField so we can get a glimpse of the GUI Builder's baseline alignment
feature.
1. In the Palette window, select the Text Field component from the Swing
Controls category.
2. Move the cursor immediately to the right of the First Name: JLabel we just
added. When the horizontal guideline appears indicating that the JTextField's
baseline is aligned with that of the JLabel and the spacing between the two
components is suggested with a vertical guideline, click to position the
JTextField.
The JTextField snaps into position in the form aligned with the JLabel's
baseline, as shown in the following illustration. Notice that the JLabel shifted
downward slightly in order to align with the taller text field's baseline. As
usual, a node representing the component is added to the Navigator window.
Before proceeding further, we need to add an additional JLabel and JTextField immediately to
the right of those we just added, as shown in the following illustration. This time enter Last
Name: as the JLabel's display text and leave the JTextFields' placeholder text as it is for now.
To resize a JTextField:
1. Select the JTextField we just added to the right of the Last Name: JLabel.
2. Drag the JTextField's right edge resize handle toward the right edge of the
enclosing JPanel.
3. When the vertical alignment guidelines appear suggesting the margin
between the text field and right edge of the JPanel, release the mouse button
to resize the JTextField.
The JTextField's right edge snaps into alignment with the JPanel's
recommended edge margin, as shown in the following illustration.
Now we'll add the Title: and Nickname: JLabels that describe two JTextFields that we're going
to add in a minute. We'll drag and drop the components while pressing the Shift key, to
quickly add them to the form. While accomplishing this, again notice that the GUI Builder
displays horizontal and vertical guidelines suggesting the preferred component spacing.
1. In the Palette window, select the Label component from the Swing Controls
category by clicking and releasing the mouse button.
2. Move the cursor over the form directly below the First Name: JLabel we added
earlier. When the guidelines appear indicating that the new JLabel's left edge
is aligned with that of the JLabel above and a small margin exists between
them, shift-click to place the first JLabel.
3. While still pressing the Shift key, place another JLabel immediately to the
right of the first. Make certain to release the Shift key prior to positioning the
second JLabel. If you forget to release the Shift key prior to positioning the
last JLabel, simply press the Escape key.
The JLabels are added to the form creating a second row, as shown in the
following illustration. Nodes representing each component are added to the
Navigator window.
Before moving on, we need to edit the JLabels' name so that we'll be able to see the effect of
the alignments we'll set later.
The JLabels' new names are displayed in the form and are shifted as a result
of their edited widths, as shown in the following illustration.
Inserting Components
Note: Refer to the Inserting components (.swf) screencast for an interactive demo on the
section below.
Often it is necessary to add a component between components that are already placed in a
form. Whenever you add a component between two existing components, the GUI Builder
automatically shifts them to make room for the new component. To demonstrate this, we'll
insert a JTextField between the JLabels we added previously, as shown in the following two
illustrations.
1. In the Palette window, select the Text Field component from the Swing
Controls category.
2. Move the cursor over the Title: and Nickname: JLabels on the second row such
that the JTextField overlaps both and is aligned to their baselines. If you
encounter difficulty positioning the new text field, you can snap it to the left
guideline of the Nickname JLabel as shown in the first image below.
3. Click to place the JTextField between the Title: and Nickname: JLabels.
The JTextField snaps into position between the two JLabels. The rightmost
JLabel shifts toward the right of the JTextField to accommodate the
suggested horizontal offset.
We still need to add one additional JTextField to the form that will display each contact's
nickname on the right side of the form.
To add a JTextField:
1. In the Palette window, select the Text Field component from the Swing
category.
2. Move the cursor to the right of the Nickname label and click to place the text
field.
The JTextField snaps into position next to the JLabel on its left.
To resize a JTextField:
1. Drag the resize handles of the Nickname: label's JTextField you added in the
previous task toward the right of the enclosing JPanel.
2. When the vertical alignment guidelines appear suggesting the margin
between the text field and JPanel edges, release the mouse button to resize
the JTextField.
The JTextField's right edge snaps into alignment with the JPanel's
recommended edge margin and the GUI Builder infers the appropriate
resizing behavior.
top
Moving Forward
Component Alignment
Note: Refer to the Aligning and anchoring components (.swf) screencast for an interactive
demo on the sections below.
Every time you add a component to a form, the GUI Builder effectively aligns them, as
evidenced by the alignment guidelines that appear. It is sometimes necessary, however, to
specify different relationships between groups of components as well. Earlier we added four
JLabels that we need for our ContactEditor GUI, but we didn't align them. Now we'll align the
two columns of JLabels so that their right edges line up.
To align components:
1. Hold down the Ctrl key and click to select the First Name: and Title: JLabels on
the left side of the form.
2. Click the Align Right in Column button ( ) in the toolbar. Alternately, you
can right-click either one and choose Align > Right in Column from the pop-
up menu.
3. Repeat this for the Last Name: and Nickname: JLabels as well.
The JLabels' positions shift such that the right edges of their display text are
aligned. The anchoring relationships are updated, indicating that the
components have been grouped.
Before we're finished with the JTextFields we added earlier, we need to make sure that the
two JTextFields we inserted between the JLabels are set to resize correctly. Unlike the two
JTextFields that we stretched to the right edge of our form, inserted components' resizeability
behavior isn't automatically set.
The JTextFields are all set to the same width and indicators are added to the
top edge of each, providing visual feedback of the component relationships.
Now we need to add another JLabel describing the JComboBox that will enable users to select
the format of the information our ContactEditor application will display.
1. In the Palette window, select the Label component from the Swing category.
2. Move the cursor below the First Name and Title JLabels on the left side of the
JPanel. When the guideline appears indicating that the new JLabel's right
edge is aligned with the right edges of the component group above (the two
JLabels), click to position the component.
The JLabel snaps into a right-aligned position with the column of JLabels
above, as shown in the following illustration. The GUI Builder updates the
alignment status lines indicating the component's spacing and anchoring
relationships.
As in the previous examples, double-click the JLabel to select its display text and then enter
Display Format: for the display name. Notice that when the JLabel snaps into position, the other
components shift to accommodate the longer display text.
Baseline Alignment
Whenever you add or move components that include text (JLabels, JTextFields, and so forth),
the IDE suggests alignments which are based on the baselines of the text in the components.
When we inserted the JTextField earlier, for example, its baseline was automatically aligned
to the adjacent JLabels.
Now we'll add the combo box that will enable users to select the format of the information
that our ContactEditor application will display. As we add the JComboBox, we'll align its
baseline to that of the JLabel's text. Notice once again the baseline alignment guidelines that
appear to assist us with the positioning.
1. In the Palette window, select the Combo Box component from the Swing
Controls category.
2. Move the cursor immediately to the right of the JLabel we just added. When
the horizontal guideline appears indicating that the JComboBox's baseline is
aligned with the baseline of the text in the JLabel and the spacing between
the two components is suggested with a vertical guideline, click to position
the combo box.
The component snaps into a position aligned with the baseline of the text in
the JLabel to its left, as shown in the following illustration. The GUI Builder
displays status lines indicating the component's spacing and anchoring
relationships.
Editing component models is beyond the scope of this tutorial, so for the time being we'll
leave the JComboBox's placeholder item list as it is.
top
Reviewing What We've Learned
We've got off to a good start building our ContactEditor GUI, but let's take a minute to recap
what we've learned while we add a few more of the components our interface requires.
Until now we've concentrated on adding components to our ContactEditor GUI using the
IDE's alignment guidelines to help us with positioning. It is important to understand, however,
that another integral part of component placement is anchoring. Though we haven't discussed
it yet, you've already taken advantage of this feature without realizing it. As mentioned
previously, whenever you add a component to a form, the IDE suggests the target look and
feel's preferred positioning with guidelines. Once placed, new components are also anchored
to the nearest container edge or component to ensure that component relationships are
maintained at runtime. In this section, we'll concentrate on accomplishing the tasks in a more
streamlined fashion while pointing out the work the GUI builder is doing behind the scenes.
The GUI Builder enables you to lay out your forms quickly and easily by streamlining typical
workflow gestures. Whenever you add a component to a form, the GUI Builder automatically
snaps them into the preferred positions and sets the necessary chaining relationships so you
can concentrate on designing your forms rather than struggling with complicated
implementation details.
1. In the Palette window, select the Label component from the Swing Controls
category.
2. Move the cursor over the form immediately below the bottom JPanel's E-
mail title. When the guidelines appear indicating that it's positioned in the
top left corner of the JPanel with a small margin at the top and left edges,
click to place the JLabel.
3. Double-click the JLabel to select its display text. Then type E-mail Address:
and press Enter.
The JLabel snaps into the preferred position in the form, anchored to the top
and left edges of the enclosing JPanel. Just as before, a corresponding node
representing the component is added to the Navigator window.
To add a JTextField:
1. In the Palette window, select the Text Field component from the Swing
Controls category.
2. Move the cursor immediately to the right of the E-mail Address label we just
added. When the guidelines appear indicating that the JTextField's baseline
is aligned with the baseline of the text in the JLabel and the margin between
the two components is suggested with a vertical guideline, click to position
the text field.
The JTextField snaps into position on the right of the E-mail Address: JLabel
and is chained to the JLabel. Its corresponding node is also added to the
Inspector window.
3. Drag the resize handle of the JTextField toward the right of the enclosing
JPanel until the alignment guidelines appear suggesting the offset between
the JTextField and JPanel edges.
The JTextField's right edge snaps to the alignment guideline indicating the
preferred margins.
Now we need to add the JList that will display our ContactEditor's entire contact list.
1. In the Palette window, select the List component from the Swing Controls
category.
2. Move the cursor immediately below the E-mail Address JLabel we added
earlier. When the guidelines appear indicating that the JList's top and left
edges are aligned with the preferred margins along the JPanel's left edge and
the JLabel above, click to position the JList.
3. Drag the JList's right resize handle toward the right of the enclosing JPanel
until the alignment guidelines appear indicating that it is the same width as
the JTextField above.
The JList snaps into the position designated by the alignment guidelines and
its corresponding node is displayed in the Inspector window. Notice also that
the form expands to accommodate the newly added JList.
Since JLists are used to display long lists of data, they typically require the addition of a
JScrollPane. Whenever you add a component which requires a JScrollPane, the GUI Builder
automatically adds it for you. Because JScrollPanes are non-visual components, you have to
use the Inspector window in order to view or edit any JScrollPanes that the GUI Builder
created.
Component Sizing
Note: Refer to the Resizing and indenting components (.swf) screencast for an interactive
demo on the sections below.
It is often beneficial to set several related components, such as buttons in modal dialogues, to
be the same size for visual consistency. To demonstrate this we'll add four JButtons to our
ContactEditor form that will allow us to add, edit, and remove individual entries from our
contact list, as shown in the following illustrations. Afterwards, we'll set the four buttons to be
the same size so they can be easily recognized as offering related functionality.
1. In the Palette window, select the Button component from the Swing Controls
category.
2. Move the JButton over the right edge of the E-mail Address JTextField in the lower
JPanel. When the guidelines appear indicating that the JButton's baseline and right
edge are aligned with that of the JTextField, shift-click to place the first button along
the JFrame's right edge. The JTextField's width shrinks to accommodate the JButton
when you release the mouse button.
3. Move the cursor over the top right corner of the JList in the lower JPanel. When the
guidelines appear indicating that the JButton's top and right edges are aligned with
that of the JList, shift-click to place the second button along the JFrame's right edge.
4. Add two additional JButtons below the two we already added to create a column.
Make certain to position the JButtons such that the suggested spacing is respected and
consistent. If you forget to release the Shift key prior to positioning the last JButton,
simply press the Escape key.
5. Set the display text for each JButton. (You can edit a button's text by right-clicking
the button and choosing Edit Text. Or you can click the button, pause, and then click
again.) Enter Add for the top button, Edit for the second, Remove for the third, and As
Default for the fourth.
The JButton components snap into the positions designated by the alignment
guidelines. The width of the buttons changes to accommodate the new names.
Now that the buttons are positioned where we want them, we'll set the four buttons to be the
same size for visual consistency as well as to clarify that they are related functionally.
1. Select all four JButtons by pressing the Control key while making your
selection.
2. Right-click one of them and choose Same Size > Same Width from the pop-
up menu.
The JButtons are set to the same size as the button with the longest name.
Indentation
Often it is necessary to cluster multiple components under another component such that it is
clear they belong to a group of related functions. One typical case, for example, is placing
several related checkboxes below a common label. The GUI Builder enables you to
accomplish indenting easily by providing special guidelines suggesting the preferred offset for
your operating system's look and feel.
In this section we'll add a few JRadioButtons below a JLabel that will allow users to
customize the way the application displays data. Refer to the following illustrations while
accomplishing this or click the View Demo link following the procedure to view an
interactive demonstration.
1. Add a JLabel named Mail Format to the form below the JList. Make certain the
label is left aligned with the JList above.
2. In the Palette window, select the Radio Button component from the Swing
category.
3. Move the cursor below the JLabel that we just added. When the guidelines
appear indicating that the JRadioButton's left edge is aligned with that of the
JLabel, move the JRadioButton slightly to the right until secondary
indentation guidelines appear. Shift-click to place the first radio button.
4. Move the cursor to the right of the first JRadioButton. Shift-click to place the
second and third JRadioButtons, being careful to respect the suggested
component spacing. Make certain to release the Shift key prior to positioning
the last JRadioButton.
5. Set the display text for each JRadioButton. (You can edit a button's text by
right-clicking the button and choosing Edit Text. Or you can click the button,
pause, and then click again.) Enter HTML for the left radio button, Plain Text
for the second, and Custom for the third.
Three JRadioButtons are added to the form and indented below the Mail
Format JLabel.
Now we need to add the three JRadioButtons to a ButtonGroup to enable the expected toggle
behavior in which only one radio button can be selected at a time. This will, in turn, ensure
that our ContactEditor application's contact information will be displayed in the mail format
of our choosing.
1. In the Palette window, select the Button Group component from the Swing Controls
category.
2. Click anywhere in the GUI Builder design area to add the ButtonGroup component to
the form. Notice that the ButtonGroup does not appear in the form itself, however, it
is visible in the Navigator's Other Components area.
3. Select all three of the JRadioButtons in the form.
4. In the Properties window, choose buttonGroup1 from the buttonGroup property
combo box.
top
Making the Final Adjustments
We've managed to rough out our ContactEditor application's GUI, but there are still a few
things remaining to do. In this section, we'll take a look at a couple of other typical layout
tasks that the GUI Builder streamlines.
Finishing Up
Now we need to add the buttons that will enable users to confirm the information they enter
for an individual contact and add it to the contact list or cancel, leaving the database
unchanged. In this step, we'll add the two required buttons and then edit them so that they
appear the same size in our form even though their display text are different lengths.
1. If the lower JPanel is extended to the bottom edge of the JFrame form, drag
the bottom edge of the JFrame down. This gives you space between the edge
of the JFrame and the edge of the JPanel for your OK and Cancel buttons.
2. In the Palette window, select the Button component from the Swing Controls
category.
3. Move the cursor over the form below the E-mail JPanel. When the guidelines
appear indicating that the JButton's right edge is aligned with the lower right
corner of the JFrame, click to place the button.
4. Add another JButton to the left of the first, making certain to place it using
the suggested spacing along the JFrame's bottom edge.
5. Set the display text for each JButton. Enter OK for the left button and Cancel
for right one. Notice that the width of the buttons changes to accommodate
the new names.
6. Set the two JButtons to be the same size by selecting both, right-clicking
either, and choosing Same Size > Same Width from the pop-up menu.
The JButton components appear in the form and their corresponding nodes are
displayed in the Navigator window. The JButton components' code is also
added to the form's source file which is visible in the Editor's Source view.
Each of the JButtons are set to the same size as the button with the longest
name.
The last thing we need to do is delete the placeholder text in the various components. Note
that while removing placeholder text after roughing out a form can be a helpful technique in
avoiding problems with component alignments and anchoring relationships, most developers
typically remove this text in the process of laying out their forms. As you go through the
form, select and delete the placeholder text for each of the JTextFields. We'll leave the
placeholder items in both the JComboBox and JList for a later tutorial.
top
Previewing Your GUI
Now that you have successfully built the ContactEditor GUI, you can try your interface to see
the results. You can preview your form as you work by clicking the Preview Form button ( )
in the GUI Builder's toolbar. The form opens in its own window, allowing you to test it prior
to building and running.
top
Deploying GUI Applications
In order for the interfaces you create with the GUI Builder to work outside of the IDE, the
application must be compiled against classes for the GroupLayout layout manager and also
have those classes available at runtime. These classes are included in Java SE 6, but not in
Java SE 5. If you develop the application to run on Java SE 5, your application needs to use
the Swing Layout Extensions library.
If you are running the IDE on JDK 5, the IDE automatically generates your application code
to use the Swing Layout Extensions library. When you deploy the application, you need to
include the Swing Layout Extensions library with the application. When you build the
application (Build > Build Main Project), the IDE automatically provides a copy of the
library's JAR file in the application's dist/lib folder. The IDE also adds each of the JAR files
that are in the dist folder to the Class-Path element in the application JAR file's manifest.mf file.
If you are running the IDE on JDK 6, the IDE generates your application code to use the
GroupLayout classes that are in Java SE 6. This means that you can deploy the application to
run on systems with Java SE 6 installed and you do not need to package your application with
the Swing Layout Extensions library.
Note: If you create your application using JDK 6 but you need the application to also run on
Java SE 5, you can have the IDE generate its code to use the Swing Layout Extensions library
instead of the classes in Java SE 6. Open the ContactEditorUI class in the GUI Editor. In the
Navigator, right-click the Form ContactEditorUI node and choose Properties in the popup
menu. In the Properties dialog box, change the value of the Layout Generation Style property
to Swing Layout Extensions Library.
Distributing and Running Standalone GUI Applications
Zip the project's dist folder into a ZIP archive. (The dist folder might also contain a lib
folder, which you would also need to include.)
To run your application, right-click the project name and select Run in the context menu. In
the Run Project dialog select the main class name (my.contacteditor.ContactEditorUI if speaking
about the project you have just created) and click OK. Your application is up and running.
Aplicatii.
Sa se creeze interfata conform tutorialului de mai sus.
Exist mai multe tipuri de aplicaii Java cum ar fi: stand-alone- aplicaii java sine
stttoare: appleturi- aplicaii java care se execut pe partea de client; servleturi-
aplicaii java care se execut pe partea de server etc.
b. Aplicatii grafice (interfata grafica de tip fereastra). Aceste interfete folosesc GUI
(Graphic User Interface). Interfaa grafic cu utilizatorul (GUI), se refer la toate tipurile de
comunicare vizual ntre un program i utilizatorii si. Aceasta este o particularizare a interfeei cu
utilizatorul (UI), prin care vom nelege conceptul generic de interaciune ntre un program i utilizatorii
si.
Aplicaiile bazate pe GUI sunt programele Java care ruleaz de sine stttoare i pot s accepte
date introduse de utilizator prin intermediul unuei ferestre bazate pe o interfa grafic(GUI).
Aplicaii Web
Acestea sunt aplicaii care sunt bazate pe web i necesit un browser web pentru
execuie. Aplicaiile web fac uz de un server pentru a stoca date i de fiecare dat cnd un
utilizator solicit s execute cererea, cererea este trecut pe la server pentru ateptarea unui
rspuns adecvat. Alicaiile ce se execut pe partea de client sunt cele ncrcate de pe un server
i apoi executate de programe speciale, cum ar fi browserul web. Un applet este un program
java ce ruleaz n cadrul unui browser web i ncorporeaz o main virtual Java. Tehnologia
appleturilor este similar, ntr-un anumit sens, cu a subprogramelor JavaScript. Fiierul cu
extensia .class al unui applet este stocat pe un server web i poate fi accesat de ctre un client
prin intermediul unei pagini care conine acel applet. La ncrcarea paginii, codul appletului
este transferat pe maina-client i va fi executat cu ajutorul mainii virtuale incluse in browser.
De la apariia sa, java a fost mbuntit mereu, transferndu-se ntr-un mediu de
dezvoltare pentru o larg varietate de aplicaii, cum ar fi aplicaii de tip client/server, aplicaii
internet sau aplicaiile standard independente.
TEHNOLOGIA JFC (SWING)
Swing nu a existat n primele versiuni de Java. Tehnologia JFC (Java
Foundation Classes) grupeaz un asamblu de faciliti pentru construirea de
interfee grafice i interactivitate n cadrul aplicaiilor Java. Prima versiune a
bibliotecilor de clase a fost lansat n cadrul conferinei JavaOne, n anul 1997.
Abstract Window Toolkit AWT definete un set de controale de baza,
ferestre si dialog boxes ce suporta o interfaa grafica utilizabila dar extrem de
limitata. Un motiv pentru natura limitata a AWT este ca traduce diferitele
componente vizuale n corespondentele specifice platformei utilizate sau legturi.
Acest lucru nseamn ca look-and-feel ul componentei este definit de platforma
si nu de Java. Deoarece componentele AWT folosesc resurse de cod nativ sunt
definite ca heavyweigh (de categorie grea).
Principalele pachete ce se folosesc n proiectarea i dezvoltarea interfeelor
grafice sunt java.awt, java.awt.event, javax.swing. Acestea sunt incluse n
pachetul JDK (Java Development Kit) care conine clase fr de care nu se pot
dezvolta aplicaiile java.
De la lansarea aplicaiei, Java AWT-ul (Abstract Window Toolkit) a fcut
parte din JDK dar nu a fost suficient pentru a suporta interfee grafice complexe,
totui putea suporta majoritatea operaiilor valabile ntr-un formular HTML.
Componentele Swing
Componente
In general componentele Swing sunt derivate din clasa JComponent.
Singura excepie la aceasta sunt cele 4 containere top-level descrise n urmtoarea
seciune. JComponent furnizeaz funcionalitate comuna pentru toate
componentele. Ca de exemplu, JComponent suporta aspectul bazat pe plug in.
JComponent motenete din clasa AWT Container si Component. Rezulta ca o
componenta swing este construita si compatibila cu componenta AWT.
Toate componentele Swing sunt reprezentate de clase si definite n pachetul
javax.swing. Urmtorul tabel arata numele claselor pentru componentele Swing
(inclusiv cele folosite ca si container).
Containere
Swing definete doua tipuri de containere. Primele sunt containere top-
level1: JFrame, JApplet, JWindow, and JDialog. Aceste containere nu motenesc
JComponent. Dar n schimb motenesc din AWT clasele Component si Container.
Spre deosebire de celelalte componente Swing care sunt lightweight containerele
1
Nivel nalt.
top-level sunt containere heavyweight. Aceasta face containerele top level un caz
special pentru librria de componente Swing.
Dup cum si numele precizeaz un container top-level trebuie sa fie la baza
ierarhiei de componente. O componenta top-level nu este coninut n nici un alt
container. De asemenea orice ierarhie de componente trebuie sa nceap cu un
container top-level. Cel mai folosit n aplicaii este JFrame iar cel mai folosit
pentru Applet este JApplet.
Al doilea tip de containere suportat de Swing sunt containerele lightweight.
Containerele lightweiht motenesc JComponent. Un exemplu de containere de
categorie uoar este JPanel, care este un container general. Containerele de
categorie uoar sunt de obicei folosite n organizarea si gestionarea grupurilor
asemntoare de componente pentru ca un container uor poate fi coninut de alt
containere. Prin urmare se folosete Containerele lightweight ca JPanel pentru a
crea subgrupuri de controale asemntoarea ce sunt coninute ntr-un alt container.
Pachetul principal este javax.swing. Acest pachet trebuie s fie importat n orice
program care utilizeaz Swing. Acesta conine clasele care implementeaz
componentele Swing de baz, cum ar fi butoane, check boxes si etichetele.
Container c = win.getContentPane();
Pentru a obtine inchiderea automata a aplicatiei atunci cand se apasa butonul de
Close, se va utiliza metoda:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
APLICAIE 1
===
APLICAIE 2
import javax.swing.*;
public class Aplic {
public static void main(String args[]) {
JFrame win = new JFrame("Aplicatia mea");
win.setSize(200, 200);
win.setLocation(30,100);
win.setResizable(false);
win.getContentPane().add(new JLabel("text pt
eticheta"));
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setVisible(true);
}}
Stabilirea principalelor trsturi pentru ferestrele tip frame se realizeaz pe baza
urmtoarelor metode:
setSize(lime, lungime) pentru stabilirea dimesiunilor;
setResizeable(true|flase) pentru a activa sau dezactiva posibilitatea
redimesionrii ferestrei de ctre utilizator;
setTitle(text) pentru desemna un titlu afiat n bara superioar a
ferestrei;
setLocation(x,y) pentru a desemna originea colului stnga-sus al
ferestrei, de remarcat faptul c originea (0, 0) de la care sunt considerai
factorii x i y este colul stnga sus al cadrului superior i nu cel din
stnga-jos;
setVisible(true|flase) pentru a afia sau ascunde fereastra, echivalent cu
metodele show() i hide(), recomandate a fi nlocuite cu aceast metod.
Pentru a obine un obiect JLabel care afieaz un text simplu putem construi o
astfel de etichet ca n exemplul urmtor:
import java.awt.*;
import javax.swing.*;
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLook
AndFeel");
new ExempluJLabel().show();
}
}
Iat rezultatul:
Constructor Aciune
JTextField () Creeaz un nou cmp gol
JTextField (int columns) Creeaz un nou obiect JTextField fr coninut
de lungimea indicat (n coloane)
JTextField(String text) Creeaz un nou obiect JTextField coninnd
textul specificat
JTextField(String text, int Creeaz un nou obiect JTextField coninnd
columns) textul specificat i avnd (afind) lungimea
indicat (n coloane)
are
Container
JComponent
Cel mai simplu container este JPanel. Un JPanel este folosit n general ca o
regiune simpl n care sunt aduse i grupate o colecie de alte componente.
Componentele sunt adugate unui container prin metoda add(). De exemplu setul
urmtor de instruciuni creeaz un JPanel i adaug dou butoane:
setLayout(null);
n acest fel obiectele (butoane, csue de text, grupuri de opiuni
etc.) vor fi afiate ntotdeauna la coordonatele stabilite de
programator. Spre exemplu poziionarea i dimensionarea unui
buton de comand (din clasa java.swing.JButton din Swing) se
realizeaz prin metoda:
var_JButton.setBounds(x, y, lime, lungime);
Componenta Descriere
FlowLayout Dispune sau aeaz componentele de la
stnga spre dreapta, de sus n jos. Este
layout manager-ul implicit(default) pentru
JPanel
BorderLayout Afieaz pn la cinci componente,
poziionate ca north nord, south
sud, east est, west vest i center
centru. Este layout manager-ul implicit
pentru panoul de componente al JFrame.
GridLayout Aeaz componentele ntr-un grid
bidimensional.
CardLayout Componentele sunt afiate pe rnd, dispuse
fiind prin suprapunere (parial).
GridBagLayout Afieaz componentele vertical i orizontal
funcie de un set re restricii specifice. Este
cel mai complex i mai flexibil layout
manager.
BoxLayout Afieaz componentele fie o singur linie
orizontal fie pe o singur coloan
vertical. Este layout-managerul implicit
pentru containerul Box din biblioteca
Swing.
OverlayLayout Afieaz componentele aa nct referinele
de aliniere ale lor indic acelai loc. Prin
urmare sunt dispuse sub forma unei stive:
unele deasupra celorlalte.
Butoanele sunt elemente de control care, prin apasare, pot genera o actiune.
Butoanele deriva din clasa JButton. In costructor primesc textul afisat pe
buton. Prin metoda setMnemonic se pot asocia taste de apelare rapida
(shortcut).
Pentru a adauga un cuvant de comanda asociat butonului (cuvant ce va fi
testat pentru efectuarea actiunii asociate) se foloseste metoda
addActionCommand().
Exemplu de definire a unui buton
import javax.swing.*;
import java.awt.*;
Rezultatul:
Rezultatul:
Rezultat:
CheckBox
Butoanele de marcaj sunt elemente de control care retin o anumita stare. In plus
fata de butoanele simple, pentru ele se pot apela metodele setSelected (boolen
marcat) pentru a stabili marcajul prin program, respectiv getSelected() pentru a
testa starea marcajului.
cb1 = new JCheckBox(Optiune1");
cb2 = new JCheckBox(Optiune2");
cb1.setSelected(true);
JPanel checkPanel = new JPanel();
checkPanel.setLayout(new GridLayout(0, 1));
//GridLayout documentare parametrii
Aeaz componentele ntr-un grid bidimensional.
checkPanel.add(cb1);
checkPanel.add(cb2);
RadioButton -- JRadioButton
Butoanele radio sunt elemente de control care retin o anumita stare, la fel cu cele
de marcaj. Deosebirea principala consta in faptul ca toate butoanele radio incluse
in acelasi grup logic sunt mutual exclusive. Pentru gestionarea grupurilor de
butoane radio se va folosi clasa ButtonGroup, respectiv metoda add() care
adauga un buton la grup.
Si pentru butoanele radio se pot apela metodele setSelected(boolen marcat)
pentru a stabili marcajul prin program, respectiv getSelected() pentru a afla starea
marcajului.
// creare buton radio
JRadioButton primulbuton = new JRadioButton(BUTON 1);
primulbuton setActionCommand(BUTON 1);
//setActionCommand pentru a atasa actiuni butonului
primulbuton.setSelected(true);
JRadioButton alt_doilea_buton = new JRadioButton(BUTON 2);
alt_doilea_buton.setActionCommand(BOTON 2);
ListBox
ListBox-urile afiseaza liste de optiuni. Ele se compun dintr-un element care se
ocupa de vizualizare (derivat din clasa JList), respectiv dintr-un element care se
ocupa cu gestionarea continutului (derivat din ListModel).
Crearea meniurilor
Modelul orientat obiect al meniurilor n Swing are urmtoarele caracteristici:
- bar principal reprezint o instan a clasei JMenuBar, sau, pentru
meniurile contextuale, JPopUpMenu;
- meniurile accesebile din bara principal sunt obinute din clasa JMenu;
- elementele individuale ale unui menu (instan JMenu) sunt construite pe
baza clasei JMenuItem care are urmtoarele subclase:
JCheckBoxMenuItem, JRadioButtonMenuItem i JMenu. Prin urmare un
element individual dintr-un meniu poate fi, la rndul su, un al submenu
(instan JMenu);
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
Varianta 2
import java.awt.*; import java.awt.event.*;
import javax.swing.*; class MainMenuBar_1 extends JMenuBar{
JFrame frmParent; add(fileMenu);
public MainMenuBar_1() { add(editMenu);
JMenu fileMenu = new add(quitMenu);
JMenu("File"); }}
JMenu editMenu = new public class Meniuri extends JFrame{
JMenu("Edit"); public Meniuri() {
JMenu quitMenu = new this.setJMenuBar(new
JMenu("Quit"); MainMenuBar_1());
// Meniul File: Open, Save, Close this.setDefaultCloseOperation(JFrame.EXI
JMenuItem openItem = new T_ON_CLOSE);
JMenuItem("Open"); this.setSize(500, 500);
JMenuItem saveItem = new this.setVisible(true);
JMenuItem("Save"); }
JMenuItem closeItem = new public static void main(String[] args) {
JMenuItem("Close"); new Meniuri();
//Meniul Edit: Cut, Copy, Paste, Find }}
(Find, Replace)
JMenuItem cutItem = new
JMenuItem("Cut");
JMenuItem copyItem = new
JMenuItem("Copy");
JMenuItem pasteItem = new
JMenuItem("Paste");
JSeparator separator1 = new
JSeparator();
JMenu findMenu = new
JMenu("Find");
JMenuItem findItem = new
JMenuItem("Find");
JMenuItem replaceItem = new
JMenuItem("Replace");
//Meniul Quit
JMenuItem exitItem = new
JMenuItem("Exit");
JMenuItem aboutItem = new
JMenuItem("About");
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(closeItem);
editMenu.add(cutItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);
editMenu.add(separator1);
findMenu.add(findItem);
findMenu.add(replaceItem);
editMenu.add(findMenu);
editMenu.add(new
JCheckBox("Bifa"));
quitMenu.add(exitItem);
quitMenu.add(aboutItem);
Gestionarea evenimentelor (listenere)
Aplicatiile cu interfete grafice sunt aplicatii orientate pe evenimente.
Anumite evenimente sunt de nivel sczut cum ar fi apsarea i eliberarea unei
taste, mutarea cursorului mouse-lui sau apsarea unui buton al acestuia, iar altele
sunt de nivel nalt, cum ar fi selectarea unei opiuni dintr-un meniu, apsarea unui
buton sau introducere de text ntr-un cmp.
Evenimentele de nivel nalt implic de fapt mai multe evenimente de nivel
mai sczut. De exemplu introducerea de text ntr-un cmp implic mutarea
cursorului mouse-ului, apsarea butonului mouse-ului sau apsarea i eliberarea
mai multor taste.
In gestionarea evenimentelor intervin obiecte de tip Listener si Event.
Pentru a trata evenimentele ce apar intr-o aplicatie trebuie respectati pasii:
Implementarea unei clase derivata dintr-o clasa Listener:
public class MyClass implements xxxListener {
public void eveniment(xxxEvent e) { ...//tratarea
evenimentului... }
oComponenta.addActionListener(instanceOfMyClass);
Categoriile de evenimente:
Categoria de Descriere
evenimente
Key Event Apsarea i eliberarea tastelor
Mouse Event Apsarea i eliberarea butoanelor mouse-ului
Drag & drop
Component Event Ascunderea, afiarea, redimensionarea sau
mutarea unei componente
Container Event Adugarea sau ndeprtarea unei componente
dintr-un container
Window Event Deschiderea, nchiderea, minimizarea
(iconificarea), reconstituirea (deiconificarea),
activarea, dezactivarea unei ferestre
Focus Event Preluarea sau pierderea focus-ului de ctre o
component
Action Event Eveniment de nivel nalt indicnd o aciune
definit la nivelul componentei (de exemplu un
buton poate fi apsat, un checkbox poate fi
selectat, apsarea tastei ENTER/RETURN
pentru un cmp de text)
Item Event Eveniment de nivel nalt care are loc atunci
cnd un utilizator selecteaz un checkbox,
buton radio sau opiune dintr-o list
DocumentEvent Generat de ctre un obiect TextComponent
atunci cnd i este modificat coninutul
Actiuni buton
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Exemplu4 extends JFrame
{
private JButton button1;
private JButton button2;
private JButton button3;
private JTextField textField;
public Exemplu4()
{
MyButtonListener listener = new MyButtonListener();
button1 = new JButton("1");
button1.setActionCommand("Ati pasat Button 1");
button1.addActionListener(listener);
getContentPane().add(button1, BorderLayout.WEST);
button2 = new JButton("2");
button2.setActionCommand("Ati pasat Button 2");
button2.addActionListener(listener);
getContentPane().add(button2, BorderLayout.CENTER);
button3 = new JButton("3");
button3.setActionCommand("Ati pasat Button 3");
button3.addActionListener(listener);
getContentPane().add(button3, BorderLayout.EAST);
textField = new JTextField(20);
textField.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String text = ((JTextField)e.getSource()).getText();
button1.setText(text);
button2.setText(text);
button3.setText(text);
} });
getContentPane().add(textField, BorderLayout.NORTH);
} public class MyButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
textField.setText(actionCommand);
}
} public static void main(String[] args)
{Exemplu4 frame = new Exemplu4();
frame.pack();
frame.setVisible(true);
}}
Exemplu de cod pentru ListBox, TextArea si Listener:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class ListBox1 extends JScrollPane {
private JList list;
public JList getList() {
return list; }
public ListBox1() {
DefaultListModel listModel = new DefaultListModel();
listModel.addElement("Randul 1");
listModel.addElement("Randul 2");
listModel.addElement("Randul 3");
list = new JList(listModel);
list.setVisibleRowCount(3);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
setViewportView(list);
}}
class SelectieLista implements ListSelectionListener {
private JTextArea consola;
ListModel listModel;
APLICATII
}
3. Aplicatie de convertire grade Celsius in Fahrenheight
4. Scrieti setul de comenzi pentru realizarea unei ferestre de dimensiune 300, 100 care
va arata ca in figura alaturata.
import javax.swing.*;
import java.awt.*;
public class a1 {
public static void main(String[] args) {
JFrame f = new JFrame("Implementarea Inteferetelor Grafice");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
Container cp = f.getContentPane();
cp.setLayout(new FlowLayout());
cp.add(b1);
cp.add(b2);
cp.add(b3);
cp.add(b4);
cp.add(b5);
f.setSize(300, 100);
f.setVisible(true);
} }
5. Scriei setul de comenzi pentru realizarea unei aplicaii Java care va creea o
fereastr ca cea din figura alturat. Explicai instruciunile folosite pentru definirea
elementelor JButton i JRadioButton
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Butoane extends JPanel {
public Butoane() {
JButton b1 = new JButton("Seria A");
JButton b2 = new JButton("Seria B");
this.setLayout(new GridLayout(1,0));
add(b1);
add(b2);
}}
class ButoaneRadio extends JPanel {
public ButoaneRadio() {
// Creare radio butoane
JRadioButton butonAlb = new JRadioButton("Sambata 10-18");
// butonAlb.setSelected(true);
JRadioButton butonRosu = new JRadioButton("Duminica 10-18");
// Gruparea butoanelor
ButtonGroup group = new ButtonGroup();
group.add(butonAlb);
group.add(butonRosu);
// Adaugarea butoanelor
add(butonAlb);
add(butonRosu);
}
}
public class Desen_Aplicatie extends JFrame {
public static void main(String args[]) {
Desen_Aplicatie app = new Desen_Aplicatie();
Butoane panouButoane = new Butoane();
ButoaneRadio panouButoaneRadio = new ButoaneRadio();
JPanel panou = new JPanel();
panou.add(panouButoane);
panou.add(panouButoaneRadio);
app.getContentPane().add(panou);
app.pack();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.show();
}}
Accesul la o baza de date - Se face prin intermediul unui driver specific tipului
respectiv de baz de date. Acesta este responsabil cu accesul efectiv la datele
stocate,
fiind legatura ntre aplicaie i baza de date.
Inchide Connection
Exemplu 1
Connection con=DriverManager.getConnection(jdbc:odbc:myMessages,
Utilizator,Parola);
Exemplu 2
String url = "jdbc:derby://localhost:1527/student1;create=true";
Connection con =DriverManager.getConnection(url,"root","123");
4. Executia instructiunii
stmt.executeUpdate(createString);
5. Inchide Connection
stmt.close();
Aplicatie:
Sa se creeze baza de date Student, iar in aceasta tabela Examen cu structura:
Structura tabele va fi creata cu ajutorul unui program Java. Comensiune ala baza
de date se va face pe baza de user si parola.
Rezolvare:
Se creaza baza de date
Connection dB=null;
String s1= jTextField1.getText();
String s2= jTextField2.getText();
String s3= jTextField3.getText();
String s4= jTextField4.getText();
int int1=Integer.parseInt(s1);
//int int3=Integer.parseInt(s3);
String dbURL =
"jdbc:derby://localhost:1527/test45;create=true;user=me;password=mine";
String tableName = "credite";
// jdbc Connection
Connection conn = null;
Statement stmt = null;
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
conn = DriverManager.getConnection(dbURL);
}
catch (Exception except)
{ except.printStackTrace(); }
try
{ stmt = conn.createStatement();
stmt.execute("insert into " + tableName + " values (" +
int1 + ",'" + s2 + "','" + s3 +"','" + s4 +"')");
jLabel6.setText(" Inregistrarea a fost adaugata cu succes");
stmt.close(); }
catch (SQLException sqlExcept)
{ sqlExcept.printStackTrace(); }
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
Fisare date introduce
String url =
"jdbc:derby://localhost:1527/test45;create=true;user=me;password=mine";
String tableName = "studenti";
// jdbc Connection
Connection conn = null;
Statement stmt = null;
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
conn = DriverManager.getConnection(url);
}
catch (Exception except)
{
except.printStackTrace();
}
try{
int int1=0;
String s1=new String();
s1=this.jTextField1.getText();
int1=Integer.parseInt(s1);
conn = DriverManager.getConnection(url);
while(rs.next())
{jTextField2.setText(rs.getString("nume_st"));
jTextField3.setText(rs.getString("an_st"));
jTextField4.setText(rs.getString("grupa"));
jTextField5.setText(rs.getString("telefon"));
}
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class StructuraApplet extends Applet
{ public void init()
{
}
public void start()
{
}
public void stop()
{
}
public void destroy()
{
}
public void paint(Graphics g)
{
}
}
import java.applet.*;
import java.awt.*;
public class imagini extends Applet {
private Image imagine;
public void init() {
imagine =getImage(getDocumentBase(), i.jpg);
}
public void paint(Graphics g)
{boolean b=g.drawImage(imagine, 200,20,200,100,this);
this.setBackground(Color.CYAN);
g.drawString(Aplicatie Applet,200, 140);
}
}
n urma operaiei de compilare rezult fiierul cu extensia .class care este ncarcat n
pagina i interpretat de browser. Vezi figura 5.1 i 5.2.
Figura 5.1 Applet rulat n Netbeans
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>
<!--
*** GENERATED applet HTML launcher - DO NOT EDIT IN 'BUILD' FOLDER ***
If you need to modify this HTML launcher file (e.g., to add applet parameters),
copy it to where your applet class is found in the SRC folder. If you do this,
the IDE will use it when you run or debug the applet.
Tip: To exclude an HTML launcher from the JAR file, use exclusion filters in
the Packaging page in the Project Properties dialog.
For more information see the online help.
-->
<H3><HR WIDTH=100%>Applet HTML Page<HR WIDTH=100%></H3>
<P>
<APPLET codebase=classes code=aa/imagini.class width=350
height=200></APPLET>
</P>
<HR WIDTH=100%><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>
</HTML>
n figura 5.1 se poate observa pricipalele metode specifice unui Applet. Un applet nu
poate s:
citeasc sau scrie documente pe calculatorul client;
deschid conexiuni cu alte maini , dect pe cea de pe care provine host;
porneasc programe ncrcate pe maina client
citeasca diverse proprietati ale sistemului de operare al clientului
import java.applet.*;
import java.awt.*;
public class GetParam extends Applet {
String a,b,c;
public void init(){
if((a=getParameter(arg1))==null)
a=nu exista aceste parametru a in documentul testat;
if((b=getParameter(arg2))==null)
b=nu exista aceste parametru b in documentul testat;
if((c=getParameter(arg3))==null)
c=nu exista aceste parametru c in documentul testat;
if((a=getParameter(arg1))==null)
a=nu exista aceste parametru a in documentul testat;
}
public void paint(Graphics g) {
g.drawString(a=+a,20,20);
g.drawString(b=+b,20,40);
g.drawString(c=+c,20,60);
}}
Prin ncarcarea n browser a fiierului .class rezult imaginea din figura 5.3
Cosul surs a fiierului HTML n care se transmit valorile paramentrilor este:
<HTML>
<HEAD>
</HEAD>
<BODY>
<APPLET codebase=classes code=GetParam.class width=50% height=50%>
<param name=arg1 value=primul parametru>
<param name=arg2 value=valoare 2>
<param name=arg3 value=valoare 3>
</APPLET>
</BODY>
</HTML>
Aplicatii
Exemplu 2
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
Exemplu 3
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
public class panza extends Applet
{
private Canvasnou canvas=new Canvasnou();
Exemplu 4
import java.applet.Applet;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.*;
}
if(e.getSource()==afisare){
String texttot=mesaj.getText();
String sir="sirul este"+texttot;
showStatus(sir);
}
}
Unitatea de invatare 6 - REALIZAREA
INTERFETELOR PENTRU APLICATII ANDROID
Fiier APK
JAR nearhivat
Componente
Fiier .dex http://source.android.com/devices/tech/dalvik/dex-
format.html
Resurse
Imagini
Fiiere XML
Atentie:
One of the most remarkable features of the Dalvik Virtual Machine (the
workhorse under the Android system) is that it does not use Java bytecode.
Instead, a homegrown format called DEX was introduced and not even the
bytecode instructions are the same as Java bytecode instructions.
Android programs are compiled into .dex (Dalvik Executable) files, which
are in turn zipped into a single .apk file on the device. .dex files can be
created by automatically translating compiled applications written in the
Java programming language.
1. File Header
2. String Table
3. Class List
4. Field Table
5. Method Table
6. Class Definition Table
7. Field List
8. Method List
9. Code Header
10. Local Variable List
.dex file is like same as the java class file but it seems to run under DVM.
You can decompile .dex using dexdump tool which is provided in android-
sdk.
ADT
https://dl-ssl.google.com/android/eclipse
Pentru a crea o aplicatie Android vom deschide Eclipse si vom selecta File-
>New->Project, dupa care vom selecta Android Application
Project.
In campurile Application Name si Project Name se va introduce numele
aplicatiei, iar in campul Package Name se va introduce numele pachetului care
va contine aplicatia noastra.
In campul Target SDK se va selecta versiunea de Android pentru care se
creeaza proiectul, iar in campul Minimum Required SDK se va selecta cea
mai veche versiune de Android pe care poate rula aplicatia noastra.
Structura unei aplicatii se poate observa in fereastra de Package Explorer.
In directorul src se gaseste intregul cod sursa; In directorul gen se afla un fisier
Java cu ID-uri catre resurse; In bin vom gasi programul compilat. Directorul
res contine mai multe directoare drawable in care se salveaza imaginile folosite
de aplicatie.
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ATRIBUT DESCRIERE
layout_width latimea obiectului
layout_height inaltimea obiectului
layout_marginTop spatiu suplimentar ce trebuie alocat in partea de sus a obiectului
layout_marginBottom spatiu suplimentar ce trebuie alocat in partea de jos a obiectului
layout_marginLeft spatiu suplimentar ce trebuie alocat in partea din stanga a obiectului
layout_marginRight
spatiu suplimentar ce trebuie alocat in partea din dreapta a
obiectului
layout_gravity
modul de pozitionare a elementelor componente in cadrul unui
container
layout_weight
proportia pe care o are controlul, raportata la intregul continut al
containerului
layout_x pozitia pe coordonata x
layout_y pozitia pe coordonata y
px = dp * (resolution_category) / 160
1. TextView
Controlul de tip TextView este utilizat pentru afisarea unui text catre utilizator,
fara ca acesta sa aiba posibilitatea de a-l modifica. Deci ca o componenta de acest
tip nu implementeaza doar functionalitatea unei etichete, ea putand fi utilizata si
pentru a realiza anumite actiuni, in cazul in care continutul pe care il afiseaza are
un format cunoscut ca de exemplu:
http://www.technotalkative.com/android-textview-autolink-attribute/
android:autoLink=web ; android:autoLink=email ;
android:autoLink=phone android:autoLink=map
2. EditText
3. AutoCompleteTextView
AutoCompleteTextView autoCompleteTextView1 =
(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
Sugestia este oferita pentru intregul continut al componentei, astfel incat daca se
doreste specificarea mai multor cuvinte, nu se va lua in calcul fiecare dintre
acestea.
In Android pot fi utilizate mai multe tipuri de butoane, intre care Button
(buton ce are atasat un text), ImageButton (buton ce are atasata o imagine),
ToggleButton si CheckBox (controale ce pot avea doua stari - selectat sau
nu), RadioButton / RadioGroup (grupuri de butoane ce pot avea doua stari
- selectat sau nu, asigurandu-se totodata excluziunea mutuala intre acestea).
5. Button
6. ImageButton
7. ToggleButton
8. CheckBox
Desi este definit un tip de eveniment asociat selectiei sau deselectiei acestei
componente (specificat de interfata
CompoundButton.OnCheckedChangeListener pentru care trebuie
implementata metoda onCheckedChange), de cele mai multe ori nu i se
asociaza o clasa ascultator, verificandu-se starea sa prin intermediul metodei
isChecked la producerea unui alt eveniment.
9. RadioButton / RadioGroup
Un obiect de tip RadioButton se poate afla si in afara unui grup la fel cum un
obiect de tip RadioGroup poate contine si alte controale decat butoane.
11.ImageView
Controlul de tip ImageView este utilizat pentru afisarea unei imagini, aceasta
putand proveni:
12.VideoView
Controlul de tip VideoView este utilizat pentru redarea de continut video, intr-
unul din formatele H.263, H.264 AVC, MPEG-4 SP sau VP8. Continutul
acestui control poate fi specificat prin una din metodele
setVideoPath(String) sau setVideoUri(Uri), prin care se indica
locatia unui fisier stocat pe dispozitiv sau aflat la distanta, pe un server.
14.DatePicker
16.AnalogClock
17.DigitalClock
Controalele Android fac parte din cadrul unui grup (obiect de tip
android.view.ViewGroup) care defineste si modul in care acestea sunt
dispuse in cadrul interfetei grafice precum si dimensiunile pe care le pot lua, motiv
pentru care o astfel de componenta este referita si sub denumirea de layout. Acest
element nu vizeaza insa tratarea evenimentelor legate de interactiunea cu
utilizatorul.
LinearLayout
AbsoluteLayout
RelativeLayout
FrameLayout
ScrollLayout
TableLayout
GridLayout.
Elementele de tip layout pot fi imbricate (continute) unele intr-altele, astfel incat
se pot proiecta interfete grafice in care modul de dispunere al controalelor sa fie
foarte complex, prin combinarea functionalitatilor pe care le ofera fiecare dintre
componentele de tip ViewGroup.
Exemplul 1:
Exemplul 2:
DDMS
Utilizare
Cele mai importrante functii pe care DDMS le poate indeplini sunt: Afisarea
log-urilor dispozitivelor, afisarea informatiilor despre procesele curente si
controlul simulatoarelor
Hierachy Viewer
Codul corespunzator fisierului xml este in figura de mai jos, in care se observa
ca la evenimentul onClick de pe button se va apela functia apasa_pe_buton(),
functie care va fi definite in programul principal MainActivity
In urma executie programului, efectul este cel din figura de mai jos.
Aplicatia 2
Activity_mail.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dip"
android:text="@string/titlu_aplicatie"
android:textSize="16dip" />
<Button
android:id="@+id/afiseaza_mesaj"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/notificare"
android:layout_marginTop="56dp"
android:text="@string/text_afiseaza_notificare" />
<EditText
android:id="@+id/notificare"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="42dp"
android:ems="10"
android:hint="@string/hint_notificare" />
</RelativeLayout>
Fisierul string.xml
MainActivity.java
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnNotificare =
(Button)findViewById(R.id.afiseaza_mesaj);
btnNotificare.setOnClickListener(this);
}
@Override
public void onClick(View v) {
EditText textNotificare =
(EditText)findViewById(R.id.notificare);
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dip"
android:text="@string/titlu_aplicatie"
android:textSize="16dip" />
<Button
android:id="@+id/afiseaza_mesaj"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/notificare"
android:layout_marginTop="56dp"
android:text="@string/text_afiseaza_notificare" />
<EditText
android:id="@+id/notificare"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="42dp"
android:ems="10"
android:hint="@string/hint_notificare" />
</RelativeLayout>
Un control care va fi referit ulterior (fie in codul sursa, fie in fisierul XML) trebuie
sa aiba asociat un identificator, indicat prin proprietatea android:id.
Exemplu:
@Override
public void addTelephone(){
//form
TableLayout table = (TableLayout)findViewById(R.id.table);
//new row
TableRow tr = new TableRow(NewRequestActivity.this);
LayoutParams ltr = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
ltr.setMargins(0, 0, 0, 2500);
tr.setLayoutParams(ltr);
//new field
EditText et = new EditText(NewRequestActivity.this);
et.setHint("telephone");
et.setInputType(InputType.TYPE_CLASS_NUMBER);
et.requestFocus();
Resources res = getResources();
float fontSize = res.getDimension(R.dimen.input_form) /
getResources().getDisplayMetrics().density;
et.setTextSize(fontSize);
6. Definii noiunea de Clasa (class) n Java i explicai elementele care apar n cadrul
acesteia (0,5 pct).
7. Definii noiunea de Interfa (interface) n Java i explicai elementele care apar
n cadrul acesteia (0,5 pct).
8. Presupunnd ca am proiectat o interfa ca n figura alturat, scriei setul de
comenzi corespunzatoare butoanelor din figura, tiind ca a, b i c sunt de tip real.
Butonul Clear va avea rolul de a anula valorile din casetele de text, iar butonul
Exit va inchide fereastra(3 pct).
9.
Nr 2
6.
7. Presupunnd ca am proiectat o interfa ca n figura alturat, scriei setul de
comenzi corespunzatoare butoanelor din figura, tiind ca l1,l2,l3 i nr 4 sunt de tip
real. Butonul clear va avea rolul de a anula valorile din casetele de text, iar butonul
close va inchide fereastra(3 pct).
n dorina de ridicare continu a standardelor desfurrii activitatilor dumneavoastra, va
rugm s completai acest chestionar i s-l transmitei indrumatorului de an.
Disciplina: ________________________
Unitatea de invatare/modulul:__________________
Anul/grupa:__________________________
Tutore:_________________________
Partea I . Coninut
1. Care dintre subiectele tratate in aceasta unitate/modul considerai c este cel mai util i
eficient? Argumentati raspunsul.
4. La care aplicatii practice ati intampinat dificultati in realizare? Care credeti ca este motivul
dificultatilor intalnite?