Uploaded by enienriketa

GUI Java Shqip

advertisement
UNIVERSITETI ALEKSANDËR MOISIU, DURRËS
Leksion 10,11
GUI(Graphical User Interface) Basics
Migert XHAJA, 2018-2019
Përmbajtja
Përmbajtja
8.1 Klasat Container ............................................................................................................................. 3
8.2 GUI Helper Classes ......................................................................................................................... 3
8.3 Kornizat Frames ............................................................................................................................ 4
8.3.1 Krijimi i nje kornize (Frame) ..................................................................................................... 4
Shembull: ............................................................................................................................................ 4
8.3.1 Shtimi i komponenteve ne nje kornize ..................................................................................... 7
Shembull ............................................................................................................................................. 7
8.4 Layout Managers............................................................................................................................ 8
8.4.1 FlowLayout .............................................................................................................................. 9
Shembull ............................................................................................................................................. 9
8.4.2 GridLayout ................................................................................................................................ 12
Shwmbull........................................................................................................................................... 13
8.4.3 BorderLayout......................................................................................................................... 14
Shembull ........................................................................................................................................... 15
8.4.4 Vetite e Layout Managers ...................................................................................................... 17
9.1 Using Panels as Subcontainers ...................................................................................................... 17
Shembull ........................................................................................................................................... 18
9.2 The Color Class ............................................................................................................................. 19
9.3 The Font Class .............................................................................................................................. 20
9.4 Tipare te perbashketa te komponenteve Swing GUI ..................................................................... 21
Shembull ........................................................................................................................................... 23
9.5 Image Icons .................................................................................................................................. 25
8.1 Klasat Container
Nje instance Container mund te mbaje instanca te Component. Klasat Container jane
komponente GUI qe jane perdorur per tw mbajtur komponente te tjere GUI. Window, Panel,
Applet, Frame, dhe
Dialog jane klasat container per komponentet AWT. Per te punuar me komponentet Swing
perdorim Container, JFrame, JDialog, JApplet, dhe JPanel, sit e pershkruara ne Tabelen 8.1.
TABLE 8.1 GUI Container Classes
Container Class
Description
java.awt.Container
is used to group components. Frames, panels, and applets are
its subclasses.
javax.swing.JFrame
is a window not contained inside another window. It is used
to hold other Swing
user-interface components in Java GUI applications.
javax.swing.JPanel
is an invisible container that holds user-interface components.
Panels can be nested. You can place panelsinside a container
that includes a panel. JPanel is also often used as a canvas to
draw graphics.
javax.swing.JApplet
is a subclass of Applet. You must extend JApplet to create a
Swing-based Java applet .
javax.swing.JDialog
is a popup window or message box generally used as a
temporary window to receive additional information from the
user or to provide notification that an event has occurred.
8.2 GUI Helper Classes
KLasat ndihmese, sic jane Graphics, Color, Font, FontMetrics, Dimension, dhe
LayoutManager, nuk jane nenklasa te Component. Ato jane perdorur per te pershkruar vetite e
komponenteve GUI, sic jane kontekstet grafike, ngjyrat, fonts, dhe madhesia (dimensioni) sic
eshte pershkruar ne Tabelen 8.2.
TABLE 8.2 GUI Helper Classes
Helper Class
Description
java.awt.Graphics
is an abstract class that provides the methods for drawing
java.awt.Color
java.awt.Font
java.awt.FontMetrics
java.awt.Dimension
java.awt.LayoutManager
strings, lines, and simple shapes.
deals with the colors of GUI components. For example, you can
specify background or foreground colors in components like
JFrame and JPanel, or you can specify colors of lines, shapes,
and strings in drawings.
specifies fonts for the text and drawings on GUI components.
For example, you can specify the font type (e.g., SansSerif),
style (e.g., bold), and size (e.g., 24 points) for the text on a
button.
is an abstract class used to get the properties of the fonts.
encapsulates the width and height of a component (in integer
precision) in a single object.
specifies how components are arranged in a container.
Shenim: Klasat ndihmese ndodhen ne paketen java.awt. Komponentet Swing nuk I zevendsojne
te gjitha klasat ne AWT, vetem klasat e komponenteve AWT GUI (p.sh., Button, TextField,
TextArea). Klasat ndihmese AWT jane akoma te perdorshme ne programimin GUI.
8.3 Kornizat Frames
Per te krijuar nje interface te perdoruesit, nevojitet te krijohet nje kornize ose nje applet per te
mbajtur komponentet e user-interface. PKrijimi i Java applets do te shpjegohet ne Kapitullin 18,
“Applet dhe Multimedia”
Ky paragraf do te paraqese kornizat ( frames)
8.3.1 Krijimi i nje kornize (Frame)
Per te krijuar nje kornize, perdorim klasen JFrame, sic eshte treguar ne Figuren 8.1.
Programi mw poshtwm krijon njw frame:
Shembull:
MyFrame.java
import javax.swing.JFrame;
public class MyFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrame"); // Create a frame
frame.setSize(400, 300); // Set the frame size
// Center a frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Display the frame
}
}
javax.swing.JFrame
+JFrame()
+JFrame(title: String)
+setSize(width: int, height: int):
void
+setLocation(x: int, y: int): void
+setVisible(visible: boolean):
void
+setDefaultCloseOperation(mode:
int): void
+setLocationRelativeTo(c:
Component):
+pack(): void
Creates a default frame with no title.
Creates a frame with the specified title.
Sets the size of the frame.
Sets the upper-left-corner location of the frame.
Sets true to display the frame.
Specifies the operation when the frame is
closed.
Sets the location of the frame relative to the
specified component.
If the component is null, the frame is centered
on the screen.
Automatically sets the frame size to hold the
components in the
frame.
FIGURE 8.1 JFrame is a top-level container to hold GUI components.
Korniza nuk shfaqet derisa thirret metoda frame.setVisible(true).
frame.setSize(400, 300) specifikonqe korniza eshte 400 pixels e gjere dhe 300 pixels e gjate. Ne
qofte se metoda setSize nuk eshte perdorur, korniza do te kete ate madhesi sat e paraqese titullin
(title bar).
Perderisa metodat setSize dhe setVisible jane te dyja te percaktuara ne klasen e Component, ato
jane te trasheguara nga klasa JFrame. Me vone ju do te shikoni qe metodat jane gjithashtu te
perdorshme ne shume nenklasa te tjera te Component. Kur ekzekuton programin MyFrame, ne
ekran do te shfaqet nje dritare (shiko Figuren 8.2(a)).
(a)
(b)
Title bar
Title bar
Content
pane
Content
pane
FIGURE 8.2 (a) The program creates and displays a frame with the title MyFrame. (b) An OK
button is added to the
frame.
Therrasim setLocationRelativeTo(null) (line 7) dhe qenderzohet korniza ne ekran.
Therrasim setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) (line 8) tregon qe program
do perfundoje kur korniza te mbyllet. Ne qofte se pohimi nuk perdoret, program nuk mbyllet kur
mbyllet korniza mbyllet. Ne kete rast ju duhet te ndaloni programin duke shtypur Ctrl+C tek
dritarja DOS promt ne Windows ose ndalo programin duke perdorur komanden “kill” ne Unix.
Nqs ju e ekzekutoni programin nga nje IDE sic eshte Eclipse ose NetBeans, ju duhet te klikoni
butonin e kuq Terminate ne Console pane per te ndaluar programin.
Shenim
Kujtojme qe nje pixel eshte me e vogli njesi hapesire i afte per te vizatuar ne nje ekran. Ju mund
ta mendoni qe nje pixel eshte si nje drejtkendesh i vogel dhe mendoni ekranin si nje hapesire me
pixel-s. Rezolucioni ( resolution) tregon numrin e pixel-s per inch ne katror. (The resolution
specifies the number of pixels per square inch). Sa me shume pixel-e te kete nje ekran, aq me e
larte eshte rezolucioni i ekranit. Sa me i larte rezolucioni, aq me mire shihen detajet.
Shenim
Ju duhet te therrisni metoden setSize(w, h) perpara se te therrasesh setLocationRelativeTo(null) per te qenderzuar kornizen.
8.3.1 Shtimi i komponenteve ne nje kornize
Korniza e treguar ne Figuren 8.2. (a) eshte bosh. Duke perdorur metoden add ju mund te shtoni
komponente ne kornize, si nwshwmbullin mw poshtw.
Shembull
MyFrameWithComponents.java
import javax.swing.*;
public class MyFrameWithComponents {
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrameWithComponents");
// Add a button into the frame
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // Center the frame
frame.setVisible(true);
}
}
Cdo JFrame permban nje content pane. NJe content pane eshte nje instance e
java.awt.Container.
Komponentet GUI si butonat jane te vendosur ne content pane si ne kornize. Ne versionet e para
te Java-s duhet te perdorje metoden getContentPane ne klasen JFrame per te kthyer content
pane te kornizes, pastaj thirret metoda add e content pane per te zevendesuar nje komponent ne
content pane, si me poshte:
java.awt.Container container = frame.getContentPane();
container.add(jbtOK);
Kjo ishte e panevojshme. Versioni i ri Java duke filluar qe me Java 5 i cili te lejon te
zevendesosh komponentet ne content pane duke thirrur nje metode add te kornizes, si me
poshte:
frame.add(jbtOK);
Tipari I ri eshte quajtur content-pane delegation. Duke folur qarte, nje komponent eshte shtuar ne
content pane e nje kornize. Per thjeshtesi ne themi qe nje komponent eshte shtuar ne content
pane e nje kornize.
Nje object JButton eshte krijuar duke perdorur new JButton("OK"), dhe ky objeckt eshte
shtuar ne content pane e nje kornize (line 9).
Metoda add(Component comp) e percaktuar ne klasen Container shton nje instance te nje
Component ne container. Perderisa JButton eshte nje nenklase e Component, nje instance e
JButton eshte gjithashtu nje instance e Component. Per te hequr nje komponent nga nje
container, perdorni metoden remove. Pohimi i meposhtem heq butonin nga container:
container.remove(jbtOK);
Kur ju ekzekutoni nje program MyFrameWithComponents, dritarja do te shfaqet si ne Figuren
8.2 (b). Butoni eshte gjithmone i qenderzuar ne kornize dhe ze te gjithe kornizen pavaresisht se
sa e masim ate. Kjo ndodh sepse komponentet jane te vendosur ne kornize nga content pane’s
layout manager dhe default layout manager per content pane qe vendos butonin ne qender. Ne
pjesen tjeter, do te shikoni layout managers te ndryshme ne vendodhjet e deshiruara.
8.4 Layout Managers
Ne shume sisteme te tjera dritare, komponentet user-interface jane vendosur duke perdorur
medhesi matese hardcoded pixel. Per shembull, vendos nje buton ne vendodhjen (10, 10) ne nje
dritare. Duke perdorur hard-coded pixel measurements, user interface mund te duket mire ne
system por i paperdorshem ne nje system tjeter. Layout managers e Java na japin nje nivel
abstraksioni qe automatikisht skicon user interface ne te gjitha sitemet e tjera dritare.
Komponentet Java GUI jane te vendosur ne containers, ku ato jane te pershtatura nga layout
manager te container. Ne programin ne vazhdim, nuk eshte specifikuar ku te vendosim butonin
OK ne kornize,por Java e di se ku ta vendose ate, sepse layout manager punon pas ekranit per te
vendosur komponentet ne vendodhjet e sakta. Nje kayout manager eshte krijuar duke pedorur nje
klase te layout manager.
Layout manager jane vendosur ne container duke perdorur metoden
setLayout(aLayoutManager). Per shembull, ju mund te perdorni pohimin e meposhtem per te
krijuar nje instance te XLayout dhe ta vendosni ate ne nje container:
LayoutManager layoutManager = new XLayout();
container.setLayout(layoutManager);
Ky paragrapf paraqet tre layout managers te rendesishem: FlowLayout, GridLayout, dhe
BorderLayout.
8.4.1 FlowLayout
FlowLayout eshte layout manager me i thjeshte. Komponentet jane rregulluar ne container nga e
majta ne te djathte ne te njejtin rregull sic jane shtuar. Kur mbushet nje rresht, fillon nje rresht i
ri.
Ju mund ta percaktoni menyren se si mund te renditen komponentet duke perdorur nje nga tre
konstantet: FlowLayout.RIGHT, FlowLayout.CENTER, ose FlowLayout.LEFT. Ju
gjithashtu mund te percaktoni boshllekun midis komponenteve ne pixels. Kalsa diagram per
FlowLayout tregohet si ne Figuren 8.3.
The get and set methods for these data
fields are provided in the class, but
omitted in the UML diagram for brevity.
java.awt.FlowLayout
-alignment: int
-hgap: int
-vgap: int
+FlowLayout()
+FlowLayout(alignment: int)
+FlowLayout(alignment: int, hgap:
int, vgap: int)
The alignment of this layout manager
(default: CENTER).
The horizontal gap of this layout manager
(default: 5 pixels).
The vertical gap of this layout manager
(default: 5 pixels).
Creates a default FlowLayout manager.
Creates a FlowLayout manager with a
specified alignment.
Creates a FlowLayout manager with a
specified alignment
horizontal gap, and vertical gap.
FIGURE 8.3 FlowLayout lays out components row by row.
Më poshtë jepet një program që demostron flow layout. Programi shton tre etiketa text fields ne
kornizën me një FlowLayout manager, sic tregohet në Figurën 8.4.
Shembull
ShowFlowLayout.java
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.FlowLayout;
public class ShowFlowLayout {
public ShowFlowLayout() {
// Set FlowLayout, aligned left with horizontal gap 10
// and vertical gap 20 between components
setLayout( );
// Add labels and text fields to the frame
add(new JLabel("First Name"));
add(new JTextField(8));
add(new JLabel("MI"));
add(new JTextField(1));
add(new JLabel("Last Name"));
add(new JTextField(8));
}
/** Main method */
public static void main(String[] args) {
ShowFlowLayout frame = new ShowFlowLayout();
frame.setTitle("ShowFlowLayout");
frame.setSize(200, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
new FlowLayout(FlowLayout.LEFT, 10, 20)
extends JFrame
(a)
(b)
FIGURE 8.4 The components are added by the FlowLayout manager to fill in the rows in
the container one after another.
Ky shembull krijon nje program duke perdorur nje stil ndryshe nga programet e meparshme, ku
kornizar ishin krijuar duke perdorur klasat JFrame. Ky shembull krijon nje klase te emeruar
ShowFlowLayout qe e zgjeron klasen JFrames (line 6). Metoda kryesore ne kete program
krijon nje instance te ShowFlowLayout (line 23). Ndertuesi i ShowFlowLayout nderton dhe
vendos komponentet ne nje kornize. Kjo eshte menyra me e preferuar e krijimit te aplikimeve
GUI –per tre arsye:
■ Krijimi I nje aplikimi GUI do te thote te krijosh nje kornize,keshtu qe eshte e natyrshme te
percatosh nje kornize qe te JFrame.
■ Korniza mund te zgjerohet me tej per te shtuar komponente te rinj ose funksione.
■ Klas mund te riperdoret lehtesisht. Per shembull, ju mund te krijoni shume korniza dhe krijuar
shume instance ten je klase. Duke perdorur nje stil ne menyre te vazhdueshme I ben programet te
lehte per tu lexuar. Nga tani e ne vazhdim, pjesa me e madhe e klasave GUI do te zgjeroje klasat
Jframe. Ndertuesi i klases kryesore do te ndertoje user interface.
Metoda kryesore main krijon nje instance te klases kryesore dhe pastaj shfaq kornizen.
Ne kete shembull, FlowLayout manager eshte perdorur per te vendosur komponente ne nje
kornize. Nqs ju e rimatni(resize) kornizen, komponentet jane automatikisht te rregulluar per tu
pershtatur. Ne figuren 8.4 (a), rreshti i pare ka 3 komponente, por ne Figuren 8.4 (a), rreshti i
pare ka kater elemnte sepse gjeresia eshte rritur.
Nqs ju do ta rivendosni pohimin setLayout (line 10) me setLayout(new FlowLayout(FlowLayout.RIGHT, 0, 0)), te gjithe rreshtat me butona do te shtrihen ne te djathte pa hapesira
boshe.
Nje object anonim FlowLayout eshte krijuar ne pohimib (line10):
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20) );
e cila eshte ekuivalente me :
FlowLayout layout = new FlowLayout(FlowLayout.LEFT, 10, 20);
setLayout(layout);
Ky kod krijon nje reference te qarte te objektit layout te klasese FlowLayout. Referenca e qarte
nuk eshte e nevojshme, sepse objekti nuk ka reference direjte ne klasen e ShowFlowLayout.
Supozojme qe ju shtuat te njejtin buton ne kornize dhjete here; a do te shfaren te dhjete butonat
ne kornize? Jo, nje component GUI sin je buton mund te shtohet ne vetem nje container dhe
vetem nje here ne container. Shtimi I nje butoni e container disa here eshte e njejta gje sikur ta
shtosh ate vetem nje here.
Kujdes
Mos harroni te vendosni operatorin e ri perpara nje klase manager kur vendosni nje layout style.
Per shembull, setLayout(new FlowLayout()).
Shenim
Ndertuesi i ShowFlowLayout() nuk e therret ne menyre te qarte ndertuesin JFrame(), por
ndertuesi JFrame() thirret ne menyre implicite. Shikoni§11.3.2, “Constructor Chaining.”
8.4.2 GridLayout
GridLayout manager I rregullon komponentet ne forme rrjeti (matrice) formation. Komponentet
jane vendosur nje rrjete nga e majta ne te djathten, duke filluar nga rreshti i pare, pastaj me te
dytin e keshtu me radhe, ne te njejten menyre sic jane shtuar. Klasa diagram per GridLayout
jepet ne Figuren 8.5
The get and set methods for these data
fields are provided in the class, but
omitted in the UML diagram for brevity.
java.awt.GridLayout
-rows: int
-columns: int
-hgap: int
-vgap: int
+GridLayout()
+GridLayout(rows: int, columns: int)
+GridLayout(rows: int, columns: int,
hgap: int, vgap: int)
The number of rows in this layout manager
(default: 1).
The number of columns in this layout
manager (default: 1).
The horizontal gap of this layout manager
(default: 0).
The vertical gap of this layout manager
(default: 0).
Creates a default GridLayout manager.
Creates a GridLayout with a specified
number of rows and columns.
Creates a GridLayout manager with a
specified number of rows and
columns, horizontal gap, and vertical gap.
FIGURE 8.5 GridLayout lays out components in equal-sized cells on a grid.
new FlowLayout(FlowLayout.LEFT, 10, 20)
java.awt.GridLayout
-rows: int
-columns: int
-hgap: int
-vgap: int
+GridLayout()
+GridLayout(rows: int, columns: int)
+GridLayout(rows: int, columns: int,
hgap: int, vgap: int)
Ju mund te specifikoni numrin e rreshtave dhe kolonave ne nje rrjet. Rregulli kryesor eshte si me
poshte:
■ Numri i rreshtave ose numri I kolonave mund te jete zero, por jot e dyja. Nese nje eshte zero
dhe tjetri eshte jozero, dimensioni jozero eshte i fiksuar, ndersa dimensioni zero eshte percaktuar
ne menyre dinamike nga layout manager. Per shembull, nqs ju specifikoni rreshta me zero dhe
trer kolona per nje rrjete qe ka dhjete komponente, GridLayout krijon tre kolona fikse per kater
rreshta, me rreshtin e fundit qe permban nje komponent. Nqs ju specifikoni 3 rreshta dhe zero
kolona per nje rrjet qe ka dhjete komponente, GridLayout krijon tre rreshta fikse me kater
kolona, me rreshtin e fundit qe permban dy komponente.
■ Nqs te dy edhe numri I rreshtave dhe numri I kolonave jane jozero, numri i rreshtave eshte
parametri dominant; numri i rreshtave eshte i fiksuar, dhe layout manager llogarit ne menyre
dinamike numrin e kolonave. Per shembull, nqs ju specifikoni tre rreshta dhe tre shtylla per nje
rrjet qe ka dhjete komponente, GridLayout krijon tre rreshta fikse te kater kolonave, me rreshtin
e fundit qe permban dy komponente.
Shwmbulli mw poshtw jep nje program qe demostron grid layout. Programi eshte i njejte me ate
te shwmbullit mw sipwr. Kjo shton tre etiketa dhe tre text fields ne kornizene GridLayout ne
vend te FlowLayout, sic tregohet ne Figuren 8.6.
Shwmbull
ShowGridLayout.java
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.GridLayout;
public class ShowGridLayout extends JFrame {
public ShowGridLayout() {
// Set GridLayout, 3 rows, 2 columns, and gaps 5 between
// components horizontally and vertically
setLayout(new GridLayout(3, 2, 5, 5));
// Add labels and text fields to the frame
add(new JLabel("First Name"));
add(new JTextField(8));
add(new JLabel("MI"));
add(new JTextField(1));
add(new JLabel("Last Name"));
add(new JTextField(8));
}
/** Main method */
public static void main(String[] args) {
ShowGridLayout frame = new ShowGridLayout();
frame.setTitle("ShowGridLayout");
frame.setSize(200, 125);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Nqs ju e rimasni kornizen, shfaqja e butonave mbetet e pandryshuar ( p.sh. numri i rreshtave dhe
kolonave nuk ndryshon, dhe hapesira nuk ndryshojne gjithashtu).
Te gjithe komponentet kane madhesi te njejten madhesi ne container GridLayout.
FIGURE 8.6 The GridLayout manager divides the container into grids; then the components
are added to fill in the cells row by row.
Duke zevendesuar pohimin setLayout (line 10) me setLayout(new GridLayout(3,
10)) akoma do te jape tre rreshta dhe dy kolona. Parametri I kolonave nuk merret parasysh sepse
parametri I rreshtave eshte jo zero. Numri actual I kolonave eshte I llogaritur nga layout
manager.
Cfare do te ndodhe nese pohimi setLayout (line 10) do te zevendesohet me
setLayout(new GridLayout(4, 2)) ose me setLayout(new GridLayout(2, 2))? Ju lutem
shikojeni vete.
Shenim
Ne FlowLayout dhe GridLayout, rregulli sipas te cilit komponentet jane shtuar ne container
eshte i rendesishem. Ai percakton vendodhjen e komponenteve ne container.
8.4.3 BorderLayout
BorderLayout manager ndan nje container ne pese zona: Lindje, Jug, Perendim, Veri dhe
Qender. Komponentet jane shtuar ne nje BorderLayout duke perdorur add(Component,index),
ku index eshte nje konstante BorderLayout.EAST,
BorderLayout.SOUTH,BorderLayout.WEST, BorderLayout.NORTH, ose
BorderLayout.CENTER. Diagrama klase per BorderLayout eshte paraqitur ne Figuren 8.7.
The get and set methods for these data
fields are provided in the class, but
omitted in the UML diagram for brevity.
java.awt.BorderLayout
-hgap: int
-vgap: int
+GridLayout()
+GridLayout(rows: int, columns: int)
+GridLayout(rows: int, columns: int,
hgap: int, vgap: int)
+BorderLayout()
+BorderLayout(hgap: int, vgap: int)
FIGURE 8.7 BorderLayout lays out components in five areas.
Komponentet jane hedhur duke iu akorduar madhesive te preferuara dhe vendosjes se tyre ne
container. Komponentet Veri dhe Jug mund te terhiqen horizontalisht; Komponentet Lindje dhe
Perendim mund te terhiqen vertikalisht; Komponenti Qender mudn te terhiqet edhe horizontalish
edhe vertikalisht per te mbushur hapesira boshe.
Shwmbulli mw poshtw jep nje program qe demostron border layout. Progami shton pese butona
te etiketuara East, South, West, North, dhe Center ne kornize me BorderLayout manager, si
ne Figuren 8.8.
Shembull
ShowBorderLayout.java
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.BorderLayout;
{
public ShowBorderLayout() {
// Set BorderLayout with horizontal gap 5 and vertical gap 10
setLayout( );
// Add buttons to the frame
add(new JButton("East"), BorderLayout.EAST);
add(new JButton("South"), BorderLayout.SOUTH);
add(new JButton("West"), BorderLayout.WEST);
add(new JButton("North"), BorderLayout.NORTH);
add(new JButton("Center"), BorderLayout.CENTER);
}
/** Main method */
public static void main(String[] args) {
ShowBorderLayout frame = new ShowBorderLayout();
rame.setTitle("ShowBorderLayout");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
new BorderLayout(5, 10)
public class ShowBorderLayout extends JFrame
FIGURE 8.8 BorderLayout divides the container into five areas, each of which can hold a
component.
Butonat jane shtuar ne kornize (lines 11–15). Duhet te keni parasysh qe metoda BorderLayout
eshte ndryshe nga metoda FlowLayout dhe GridLayout. Me
BorderLayout ju specifikoni se ku do ti vendosni komponentet.
Eshte e panevojshme te vendosesh komponentet per te zene te gjithe zonen. Nqs ju hiqni butonin
Lindje nga programi dhe e ekzekutoni perseri ate, ju do te shikoni qe qendra do te terhiqet ne
anen e djathte per te zene hapesiren Lindje.
Shenim
BorderLayout interpreton mungesen e specifikimit te nje indeksi si BorderLayout.CENTER.
Per shembull, add(component) eshte e njejte si add(Component, BorderLayout.CENTER).
Nqs ju shtoni dy komponente nje container
BorderLayout, si me poshte,
container.add(component1);
container.add(component2);
vetem komponenti I fundit do te shfaqet.
8.4.4 Vetite e Layout Managers
Layout managers kane veti qe mund te ndryshohen ne menyre dinamike.
FlowLayout ka vetite alignment, hgap, dhe vgap. Ju mund te perdorni metodat setAlignment,
setHgap, dhe setVgap methods per te specifikuar bashkimin horizontal dhe vertical te
hapesirave. GridLayout ka vetite rows, columns, hgap, dhe vgap. Ju mund te perdorni metodat
setHgap dhe setVgap per te specifikuar hapesirat horizontale dhe vertikale. Ne paragrafet
paraardhese jane perdorur anonymous layout manager sepse vetite e nje layout manager nuk
ndryshojne, nqs ai krijohet. Nqs ju duhet te ndryshoni ne menyre dinamike vetite e layout
manager, atehere layout manager duhet kete nje reference dallueshme nga nja variabel. Per
shembull, kodo I meposhtem krijon nje layout manager dhe vendos vetite e tij:
// Create a layout manager
FlowLayout flowLayout = new FlowLayout();
// Set layout properties
flowLayout.setAlignment(FlowLayout.RIGHT);
flowLayout.setHgap(10);
flowLayout.setVgap(20);
9.1 Using Panels as Subcontainers
Supozoni qe ju doni te zevendesoni dhjete butona dhe nje text field ne nje kornize. Butonat jane
vendosur nje nje forme rrjete, por text field eshte I vendosur ne nje rresht e vecante. Nqs esht e
veshtire per te arritur pamjen e deshiruar duke zevendesuar te gjithe komponentet ne nje
container. Me programimin ne Java GUI, ju mund te ndani nje dritare ne pannels. Pannels
veprojne si nen-container per te grupuar komponentet user-interface. Ju shtoni butonat ne nje
panel, pastaj shtoni panel ne nje kornize. Versioni Swing i panel eshte JPanel. Ju mund te
perdorni new JPanel() per te krijuar nje panel me default FlowLayout manager ose new
JPanel(LayoutManager) per te krijuar nje panel me layout manager te specifikuar. Perdorni
metoden add(Component) per te shtuar nje component ne nje panel. Per shembull, kodi i
meposhtem krijon nje panel dhe shton nje buton:
JPanel p = new JPanel();
p.add(new JButton("OK"));
Panels mund te vendosen Brenda kornizes ose Brenda nje panel-i tjeter. Pohimi I meposhtem
vendos panel p ne kornizen f:
f.add(p);
Shwmbulli mw poshtw jep nje shembull qe demostron perdorimin e panel-ve si subcontainer.
Programi krijon nje user interface per nje mikrovale, sic shihet ne figuren 8.9.
Shembull
TestPanels.java
import java.awt.*;
import javax.swing.*;
public class TestPanels extends JFrame {
public TestPanels() {
// Create panel p1 for the buttons and set GridLayout
p1.setLayout(new GridLayout(4, 3));
JPanel p1 = new JPanel(); panel p1
// Add buttons to the panel
for (int i = 1; i <= 9; i++) {
(new JButton("" + i));
}
p1.add(new JButton("" + 0));
p1.add(new JButton("Start"));
p1.add(new JButton("Stop"));
// Create panel p2 to hold a text field and p1
(new JTextField("Time to be displayed here"),
BorderLayout.NORTH);
(p1, BorderLayout.CENTER);
// add contents into the frame
add(p2, BorderLayout.EAST);
add(new JButton("Food to be placed here"),
BorderLayout.CENTER);
}
/** Main method */
public static void main(String[] args) {
TestPanels frame = new TestPanels();
frame.setTitle("The Front View of a Microwave Oven");
frame.setSize(400, 250);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
p2.add
p2.add
JPanel p2 = new JPanel(new BorderLayout());
p1.add
FIGURE 9.1 The program uses panels to organize components.
Metoda setLayout eshte percaktuar ne java.awt.Container. Perderisa JPanel eshte nje nenklase
e Container, ju mund te perdorni setLayout per te vendosur nje layout manager te ri ne panel
(line 8). Linjat 7–8 mund te zevendesohen me JPanel p1 = new JPanel(new GridLayout(4, 3)).
Per te marre pamjen(layout) e deshiruar, program perdor p1 te GridLayout per te grupuar
butonat numra, butonin Stop dhe butonin Start dhe panel p2 te BorderLayout per te mbajtur nje
text field ne very dhe p1 ne qender. Butoni qe paraqet ushqimin eshte vendosur ne qender te
kornizes dhe p2 eshte vendosur lindje te kornizes. Pohimi (lines 21–22)
p2.add(new JTextField("Time to be displayed here"),
BorderLayout.NORTH);
Krijon nje instance te JTextField dhe shton ate ne p2. JTextField qe eshte nje component GUI
qe mund te perdoret per user input as well as to display values.
Shenim
Ia vlen te shenojme qe klasa Container eshte nje superklase per klasat e komponenteve GUI, sic
jane JButton. Cdo component Gui eshte nje container. Ne teori , ju mund te perdorni metoden
setLayout per te vendosur layout ne nje buton dhe te shtoje komponente ne nje buton, sepse te
gjitha metodat publike ne klasen e Container jane trasheguara ne JButton, por per arsye
praktike ju nuk duhet ti perdorni butonat si containers.
9.2 The Color Class
Ju mund ti vendosni ngjyrat per koponentet GUI duke perdorur klasen java.awt.Color. Ngjyrat
jane te perbera nga komponentet e kuq, gjelber dhe blu, secili I perfaqesuar nga nje vlere int qe
pershkruan intensitetin e tij,qe shtrihet nga 0 (hija e erret) ne 255 (hijen e hapur). Ky njihet si
modeli RGB.
Ju mund te krijoni nje ngjyre duke perdorur konstruktorine meposhtem:
public Color(int r, int g, int b);
ne te cilin r, g dhe b specifikojne nje ngjyre nga komponentet e kuq, gjelber dhe blu. Per
shembull,
Color color = new Color(128, 100, 100);
Shenim
Argumentet r,g,b jane midis 0 dhe 255. Nqs nje vlere jashte ketij intervali eshte kaluar ne
argument atehere do te ndodhi nje IllegalArgumentException.
Ju mund te perdorni metodat setBackground(Color c) dhe setForeground(Color c) te
percaktuar ne java.awt.Component per te vendosur nje a component’s background and
foreground colors. Po japim nje shembull per vendosjen e background and foreground of a
button:
JButton jbtOK = new JButton("OK");
jbtOK.setBackground(color);
jbtOK.setForeground(new Color(100, 1, 1));
Ne menyre alternative, ju mund te perdorni nje nga 13 ngjyrat standarte (BLACK, BLUE,
CYAN, DARK_GRAY,
GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, dhe
YELLOW) te percaktuara si anstante ne java.awt.Color.
Kodi I meposhtem, per shembull, vednos foreground color of
a button to red:
jbtOK.setForeground(Color.RED);
9.3 The Font Class
Ju mund te krijoni nje Font duke perdorur klasen java.awt.Font dhe vendosni fonts per
komponentet duke perdorur metoden setFont ne klasen e komponenteve.
Konstruktori per Font eshte:
public Font(String name, int style, int size);
Ju mund te zgjidhni nje emer fint nga SansSerif, Serif, Monospaced, Dialog, or
DialogInput dhe te zgjidhni nje stil nga Font.PLAIN (0), Font.BOLD (1), Font.ITALIC (2),
Dhe
You can choose a font name from SansSerif, Serif, Monospaced, Dialog, or
DialogInput, choose a style from Font.PLAIN (0), Font.BOLD (1), Font.ITALIC (2),
Font.BOLD Font.ITALIC (3) dhe specifikoni nje madhesi font me nje numer te plote pozitiv.
Per shembull, pohimet e meposhtme krijojne dy fonts dhe vendosin nje font ne nje buton.
Font font1 = new Font("SansSerif", Font.BOLD, 16);
Font font2 = new Font("Serif", Font.BOLD + Font.ITALIC, 12);
JButton jbtOK = new JButton("OK");
jbtOK.setFont(font1);
Nqs sistemi juaj I mban edhe fonts te tjere, sic jane “Times New Roman,” ju mund ta perdorni
ate per te krijuar nje object Font, per te gjetur font-s te vlefshme ne sistemin tuaj ju duhet te
merrni nje instance te java.awt.GraphicsEnvironment duke perdorur nje metode statike
getLocalGraphicsEnvironment().GraphicsEnvironment eshnte nje klase abstract qe
pershrkuan mjedisin e grafikeve ne nje system te vecante. Ju mund te perdorni metoden
getAllFonts() per te marre te gjithe fontet e vlefshme ne system dhe metoden
getAvailableFontFamilyNames() per te marre emrat e te gjithe fonteve te vlefshme. Pohimet e
meposhtme japin te gjithe emrat e fonteve te vlefshme ne sistem:
GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();
for (int i = 0; i < fontnames.length; i++)
System.out.println(fontnames[i]);
System.out.println(fontnames[i]);
9.4 Tipare te perbashketa te komponenteve Swing GUI
Ne kete kapitull ju keni perdorur komponente te ndryshem GUI (p.sh., JFrame, Container,
JPanel,JButton, JLabel, JTextField). Me shume komponente GUI do t’ju prezantohen ne kete
liber. Eshte e rendesishme te kuptono tiparet e perbashketa te kopmonenteve GUI.
The get and set methods for these data
fields are provided in the class, but
omitted in the UML diagram for brevity.
java.awt.Component
-font: java.awt.Font
-background: java.awt.Color
-foreground: java.awt.Color
-preferredSize: java.awt.Dimension
-visible: boolean
+getWidth(): int
+getHeight(): int
+getX(): int
+getY(): int
The font of this component.
The background color of this component.
The foreground color of this component.
The preferred size of this component.
Indicates whether this component is visible.
Returns the width of this component.
Returns the height of this component.
getX() and getY() return the coordinate of
the
component’s upper-left corner within its
parent component
java.awt.Container
+add(comp: Component): Component
+add(comp: Component, index: int):
Component
+remove(comp: Component): void
+getLayout(): LayoutManager
+setLayout(l: LayoutManager): void
+paintComponents(g: Graphics): void
Adds a component to the container.
Adds a component to the container with the
specified index.
Removes the component from the
container.
Returns the layout manager for this
container.
Sets the layout manager for this container.
Paints each of the components in this
container.
The get and set methods for these data
fields are provided in the class, but
omitted in the UML diagram for brevity
javax.swing.JComponent
-toolTipText: String
-border: javax.swing.border.Border
The tool tip text for this component. Tool
tip text is displayed when
the mouse points on the component without
clicking.
The border for this component.
FIGURE 8.10 All the Swing GUI components inherit the public methods from Component,
Container, and JComponent.
Klasa e Component eshte rrenja per te gjithe komponentet dhe container GUI. Te gjithe
komponentet Swing GUI (pervec JFrame, JApplet, dhe JDialog) jane nenklasa te
JComponent, si te treguara ne figuren 8.10 . Figura 8.10 liston disa medota te perdorura ne
menyre frekuente ne Component, Container,
dhe JComponent per te manipuluar veti sic jane font, ngjyra, madhesi, tool tip text, dhe kufi. NJ
tool tip eshte nje tekst i shfaqur ne nje komponent kur ju levizni miun ne nje komponent. Shpesh
perdoret per te pershkruar funksionin e nje komponenti. Ju mund te vendosni nje kufi nje cdo
objekt te klases JComponent. Swing ka tipe te ndryshme kufinjsh. Per te krijuar nje kufi te
titulluar , perdorni new TitledBorder(String title). Per te krijuar nje vije kufi perdorni new
LineBorder(Color color, int width),ku gjeresia specifikon trashesine e vijes.
Mw poshta eshte nje shembull qe demonstron tiparet e perbashketa Swing.
Shembulli krijon nje panel p1 per te mbajtur tre butone (line8) dhe nje panel p2 per te mbajtur dy
etiketa (line 25) sic tregohet ne figuren 8.11. The background of the button jbtLeft is set to white
(line 12) and the foreground
of the button jbtCenter is set to green (line 13). The tool tip of the button jbtRight
is set in line 14. Titled borders are set on panels p1 and p2 (lines 18, 36) and line borders are set
on the labels (lines 32–33).
Titled border
Having the mouse cursor
over the Right button
displays the tool tip text
Titled border
Line border
FIGURE 9.2 The font, color, border, and tool tip text are set in the message panel.
Shembull
TestSwingCommonFeatures.java
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class TestSwingCommonFeatures extends JFrame {
public TestSwingCommonFeatures() {
// Create a panel to group three buttons
JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 2));
JButton jbtLeft = new JButton("Left");
JButton jbtCenter = new JButton("Center");
JButton jbtRight = new JButton("Right");
p1.add(jbtLeft);
p1.add(jbtCenter);
p1.add(jbtRight);
// Create a font and a line border
// Create a panel to group two labels
Border lineBorder = new LineBorder(Color.BLACK, 2);
Font largeFont = new Font("TimesRoman", Font.BOLD, 20);
p1.setBorder(new TitledBorder("Three Buttons"));
jbtRight.setToolTipText("This is the Right button");
jbtCenter.setForeground(Color.GREEN);
jbtLeft.setBackground(Color.WHITE); set background
set foreground
set tool tip text
set titled border
create
JPanel p2 = new JPanel(new GridLayout(1, 2, 5, 5));
JLabel jlblRed = new JLabel("Red");
JLabel jlblOrange = new JLabel("Orange");
jlblRed.setForeground(Color.RED);
jlblOrange.setFont(largeFont);
jlblOrange.setBorder(lineBorder);
p2.add(jlblRed);
p2.add(jlblOrange);
// Add two panels to the frame
setLayout(new GridLayout(2, 1, 5, 5));
add(p1);
add(p2);
}
public static void main(String[] args) {
// Create a frame and set its properties
JFrame frame = new TestSwingCommonFeatures();
frame.setTitle("TestSwingCommonFeatures");
frame.setSize(300, 150);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Shenim
E njejta veti mudn te kete vlera te ndryshme ne komponente te ndryshem. Per shembull, vetia
visible in J Frame eshte false by default, por esht eture in cdo instance te (p.sh., JButton dhe
JLabel) by default. Per te shfaqur nje JFrame, ju duhet te therrisni setVisible(true) per te
vendosur vetine visible true, por ju nuk duhet ta vendosni kete veti per JButton ose JLabel,
sepse eshte tashme true. Per te bere JButton ose JLabel te pa dukshem, ju duhet te therrisni
setVisible(false). Ju lutem egzekutoni programin dhe shikoni efektin pasi te shtoni dy pohimet e
meposhtme ne line 37:
jbtLeft.setVisible(false);
jlblRed.setVisible(false);
9.5 Image Icons
Nje ikone eshte nje fotografi me madhesi te fiksuar. Eshte e vogel dhe perdoret per te zbukuruar
komponentet. Imazhet jane zakonisht te ruajtura ne dosjet imazh.
Java suporton tre formate imazhesh: GIF (Graphics Interchange Format), JPEG (Joint
Photographic Experts Group), dhe PNG (Portable Network Graphics).
Emrat e dosjeve te ketyre imazheve per keto tipe mbarojne me .gif, .jpg, dhe .png. Nqs ju keni
nje bitmap file ose image file ne formate te tjera, ju mund t eperdorni iamge-processing per ti
konvertuar ato ne formate GIF, JPEG, or PNG per perdorim ne Java. Per te shfaqur nje ikone
imazhi, se pari krijoni nje object ImageIcon duke perdorur new
javax.swing.ImageIcon(filename). Per shembull, pohimi i meposhtem krijona nje ikone nga nje
dosje imazh us.gif ne direktorine image nen klasen:
ImageIcon icon = new ImageIcon("image/us.gif");
“image/us.gif” eshte I lokalizuar ne “c:\book\image\us.gif.” The back slash (\) is the Windows
file path notation. In Unix, the forward slash (/) should be used. In Java, the forward slash (/) is
used to denote a relative file path under the Java classpath (e.g., image/us.gif, as
in this example).
Tip
File names are not case sensitive in Windows but are case sensitive in Unix. To enable your
programs to run on all platforms, name all the image files consistently, using lowercase.
Nje ikone imazh mund te shfaqet nje nje etiketem ose nje buton duke perdorur new
JLabel(image- Icon) ose new JButton(imageIcon). Shwmbulli mw poshtwdemostron shfaqjen
e ikonave ne etiketa dhe butona. Shembulli krijon dy etiketa dhe dy butona me ikona, sic shihen
ne Figuren 8.12.
Shembull
TestImageIcon.java
import javax.swing.*;
import java.awt.*;
public class TestImageIcon extends JFrame {
private ImageIcon myIcon = new ImageIcon("image/my.jpg");
private ImageIcon frIcon = new ImageIcon("image/fr.gif");
private ImageIcon ukIcon = new ImageIcon("image/uk.gif");
public TestImageIcon() {
setLayout(new GridLayout(1, 4, 5, 5));
add(new JLabel(myIcon));
add(new JButton(ukIcon));
}
/** Main method */
public static void main(String[] args) {
TestImageIcon frame = new TestImageIcon();
frame.setTitle("TestImageIcon");
frame.setSize(200, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
add(new JButton(frIcon));
add(new JLabel(usIcon));
private ImageIcon usIcon = new ImageIcon("image/us.gif");
Shenim
Komponentet GUI nuk mund te ndahen ne containers, sepse nje component GUI mund te shfaqet
ne vetem nje container nje nje kohe. Keshtu qe, merredhenia midis nje component dhe nje
container eshte perberje e treguar nga nje diamante solid si ne Figuren 8.12.
FIGURE 9.3 The image icons are displayed in labels and buttons. Faqe 423
Shenim
Kufinjte dhe ikonat mund te ndahen. Keshtu qe ju mund te krijoni nje kufi ose nje ikone dhe te
perdorni ate per te vendosur vetine e nje kufiri ose ikone per komponentet GUI. Per shembull,
pohimi I meposhtem tregon nje kufi b per dy panele p1 dhe p2:
p1.setBorder(b);
p2.setBorder(b);
Pohimi i meposhtem tregon nje ikone ne dy butone jbt1 dhe jbt2:
jbt1.setIcon(icon);
jbt2.setIcon(icon);
Tip
A splash screen is an image that is displayed while the application is starting up. If your program
takes a long time to load, you may display a splash screen to alert the user. For example, the
following
command:
java –splash:image/us.gif TestImageIcon
displays an image while the program TestImageIcon is being loaded.
Download