unit-1-it-contains-breif-notes
unit-1-it-contains-breif-notes
Unit1
IntroductiontoWebDevelopmentStrategies
Therearemanydifferentstrategiesforwebdevelopment.Somecommonstrategies
include:
Thebestwebdevelopmentstrategyforaparticularprojectwilldependonthe specific
requirements of the project.
HistoryofWeband Internet
The history of the web begins with the development of the Internet, which began in
the 1960s as a way for scientists to communicate with each other. In 1989, Tim
Berners-Lee,aBritishcomputerscientist,proposedthecreationofaglobalhypertext
system. He called this system the World Wide Web.
ProtocolsGoverningWeb
The most important protocol for the web is the Hypertext Transfer Protocol (HTTP).
HTTPisasetofrulesthatdefinehowwebbrowsersandwebserverscommunicate.
Otherimportantprotocolsforthewebinclude:
TheHypertextMarkupLanguage(HTML):HTMLisamarkuplanguagethatis used
to create web pages.
TheCascadingStyleSheets(CSS):CSSisastylesheetlanguagethatis used
to control the appearance of web pages.
TheJavaScript:JavaScriptisaprogramminglanguagethatisusedtoadd
interactivity to web pages.
Theseprotocolsworktogethertoallowuserstoview,create,andinteractwithweb pages.
WritingWebProjects
Awebprojectisacollectionofwebpagesthat arerelatedtoeachotherandsharea common
purpose. Web projectscanbecreated fora variety ofpurposes, suchas to provide
information, sell products, or provide entertainment.
Towriteawebproject,youwillneedto:
ConnectingtoInternet
To connect to the internet, you will need to have a device that is capable of
connectingtotheinternet,suchasacomputer,smartphone,ortablet.Youwillalso
needtohaveaninternetserviceprovider(ISP).AnISPisacompanythatprovides access to
the internet.
Toconnecttotheinternet,youwillneedtodothefollowing:
IntroductiontoInternetServicesandTools
The internet provides a wide variety of services and tools that can be used for a
varietyofpurposes.Someofthemostcommoninternetservicesandtoolsinclude:
Email:Emailisaservicethatallowsyoutosendandreceivemessagesto other
people.
Webbrowsing:Webbrowsingisaservicethatallowsyoutoaccesswebsites.
Socialmedia:Socialmediaisaservicethatallowsyoutoconnectwithfriends and
family and share information with them.
Onlineshopping:Onlineshoppingisaservicethatallowsyoutopurchase goods
and services from businesses that are located all over the world.
Streamingmedia:Streamingmediaisaservicethatallowsyoutowatch
movies, listen to music, and watch TV shows online.
IntroductiontoClient-ServerComputing
Client-servercomputingisatypeofcomputingarchitectureinwhichclientcomputers
request services from server computers. The client computers are typically used for
tasks such as displaying information, entering data, and controlling applications. The
server computers are typically used for tasks such as storing data, processing data,
and providing services to the client computers.
Herearesomeofthebenefitsofclient-servercomputing:
Efficiency:Client-servercomputingcanhelpbusinessestoshareresources and
data more efficiently. This can lead to cost savings and improved
productivity.
Scalability: Client-server computing can help businesses to scale their
computinginfrastructuremoreeasily.Thiscanbeimportantforbusinesses that
are growing or that need to be able to handle sudden increases in
demand.
Security:Client-servercomputingcanhelpbusinessestoimprovethesecurity
oftheirdata.Thisisbecausethedata isstoredona centralserver,whichcan be
more easily secured than individual client computers.
Herearesomeofthechallengesofclient-servercomputing:
Complexity:Client-servercomputingcanbemorecomplextosetupand
manage than other computing architectures.
Cost:Client-servercomputingcanbemoreexpensivethanothercomputing
architectures.
Security:Client-servercomputingcanbemorevulnerabletosecuritythreats than
other computing architectures.
IntroductiontoCoreJava
CoreJavaisasetofbasicclassesandinterfacesthatprovidethefoundationfor Java
programming. These classes and interfaces are used to create objects, manipulate
data, and perform input and output operations.
CoreJavaisapowerfulandversatilelanguagethatcanbeusedtocreateawide variety of
applications, including:
Webapplications: CoreJavacanbeusedtocreatedynamicandinteractive web
applications.
Desktopapplications:CoreJavacanbeusedtocreatestand-alonedesktop
applications.
Mobileapplications: CoreJavacanbeusedtocreatemobileapplicationsfor
smartphones and tablets.
Serverapplications: CoreJavacanbeusedtocreateserver-sideapplications that
run on web servers.
CoreJavaisapopularchoiceforJavaprogrammingbecauseitis:
Efficient:CoreJavaisaveryefficientlanguagethatcanbeusedtocreate high-
performance applications.
Secure:CoreJavaisasecurelanguagethatcanbeusedtocreate
applications that are resistant to attack.
Portable:CoreJavaisaportablelanguagethatcanbeusedtocreate
applications that can run on a variety of platforms.
Operators
Operatorsareusedtoperformoperationsonvariablesandexpressions.Thereare many
different types of operators in Java, including:
Arithmeticoperators:Theseoperatorsareusedtoperformarithmetic
operations,suchasaddition,subtraction,multiplication,anddivision.
Relationaloperators:Theseoperatorsareusedtocomparetwovaluesand
determine if they are equal, greater than, less than, etc.
Logicaloperators:TheseoperatorsareusedtocombineBooleanexpressions and
determine if they are true or false.
Bitwiseoperators:Theseoperatorsareusedtomanipulatebitsinbinary
numbers.
Assignmentoperators:Theseoperatorsareusedtoassignvaluesto
variables.
Datatypes
Primitivedatatypes:Thesedatatypesarebuilt-intotheJavalanguageand
include byte, short, int, long, float, double, and char.
Referencedatatypes:Thesedatatypesareobjectsthatarecreatedusing
classes and interfaces.
Variables
Variables are used to store data. A variable is declared using the keyword
varfollowedbythevariablenameandthedatatype.Forexample,thefollowingcode
declares a variable named nameof type String:
Stringname;
Variables can be initialized with a value when they are declared, or they can be initialized
laterusingthe=operator.Forexample,thefollowingcodedeclaresandinitializesavariable named
ageof type int:
intage=25;
Arrays
Arrays are used to store a collection of data of the same type. An array is declared
using the keyword arrayfollowed by the array name, the data type, and the size of
thearray.Forexample,thefollowingcodedeclaresanarraynamed numbersoftype intand
size 5:
int[]numbers=newint[5];
Arrays can be initialized with values when they are declared, or they can be initialized later
using the =operator. For example, the following code declares and initializes an array
namednamesoftypeStringwiththevalues"John","Mary","Peter","Susan",and"David":
String[]names=newString[]{"John","Mary","Peter","Susan","David" };
Methods&Classes
Methodsareblocksofcodethatperformaspecifictask.Classesareblueprintsfor creating
objects. Objects are instances of classes.
Methodsaredefinedinsideclasses.Theycanbecalledbyothermethodsorbythe main()
method. Methods can take parameters and return values.
Inheritance
InheritanceisamechanisminJavathatallowsoneclasstoinheritthepropertiesand
methods of another class. The class that inherits the properties and methods is
called the subclass. The class that is being inherited from is called the superclass.
Whenasubclassinheritsfromasuperclass,itcanaccessallofthepublicand protected
members of the superclass. It can also override the methods of the superclass.
Package
Packagesaredefinedusingthepackagekeyword.Thenameofapackagemustbe unique.
Interface
Aninterfaceisablueprintforaclass.Itdefinesthemethodsthataclassmust implement.
Interfacesaredefinedusingtheinterfacekeyword.Thenameofaninterfacemust be
unique.
Interfacescannothavefieldsorconstructors.Theycanonlyhavemethods.
Methodsinaninterfaceareabstract,whichmeansthattheydonothaveabody.The body of
the method is implemented in the class that implements the interface.
Interfacesareusedtoachievepolymorphism.Polymorphismistheabilitytouse different
objects of different types in the same way.
Herearesomeofthebenefitsofusingmethods,classes,inheritance,packages,and interfaces:
Methods:Methodscanhelptomakecodemoremodularandreusable.
Classes:Classescanhelptoorganizecodeandtomakeiteasierto
understand.
Inheritance:Inheritancecanhelptoreducecodeduplicationandtomake code
more maintainable.
Packages:Packagescanhelptoorganizecodeandtopreventname
conflicts.
Interfaces:Interfacescanhelptoachievepolymorphismandtomakecode more
flexible.
Herearesomeofthechallengesofusingmethods,classes, inheritance,packages, and
interfaces:
Methods:Methodscanbedifficulttodebugiftheyarenotwell-written.
Classes:Classescanbedifficulttounderstandiftheyarenotwell-designed.
Inheritance:Inheritancecanbedifficulttounderstandifitisnotusedcorrectly.
Packages:Packagescanbedifficulttomanageiftheyarenotwell-organized.
Interfaces:Interfacescanbedifficulttoimplementiftheyarenotwell-
designed.
When an error occurs, Java will throw an exception. An exception is an object that
containsinformationabouttheerror,suchasthetypeoferror,thelineofcodewhere the error
occurred, and the message that describes the error.
You can handle exceptions using try-catch blocks. A try-catch block is a block of
codethatisexecutedwhenanexceptionisthrown.Thetryblockcontainsthecode that you
want to execute, and the catch block contains the code that you want to execute
when an exception is thrown.
Forexample,thefollowingcodeusesatry-catchblocktohandleanerrorthatoccurs when
you try to divide by zero:
try{
intresult=10/0;
}catch(ArithmeticExceptione){
System.out.println("Error:Divisionbyzero");
Inthisexample,thetryblockcontainsthecodethattriestodivide10by0.Thecatch block
contains the code that is executed when an exception is thrown. In this case, the
exception is an ArithmeticException, which is thrown when you try to divide by zero.
The catch block prints the message "Error: Division by zero".
You canalso use finally blocks to execute code after atry-catch block, regardlessof
whetherornotanexceptionisthrown.Forexample,thefollowingcodeusesafinally block to
close a file, even if an exception is thrown:
Filefile=newFile("myfile.txt");
try{
//Readfromfile
}catch(IOExceptione){
//Handleerror
}finally{
//Closefilefi
le.close();
In this example, the finally block will always be executed, even if an exception is
throwninthetryblock.Thisensuresthatthefileisalwaysclosed,evenifanerror occurs.
Exception handling is a powerful tool that can help you to write robust and reliable
Java code. By using try-catch and finally blocks, you can ensure that your code will
handleerrorsgracefullyandcontinuetorunevenwhenunexpectedproblemsoccur.
HerearesomeofthebenefitsofusingexceptionhandlinginJava:
Robustness:Exceptionhandlingcanhelptomakeyourcodemorerobustby
preventing errors from causing your program to crash.
Reliability:Exceptionhandlingcanhelptomakeyourcodemorereliableby
ensuring that your program can continue to run even when errors occur.
Readability:Exceptionhandlingcanhelptomakeyourcodemorereadableby
making it easier to understand how your program handles errors.
HerearesomeofthechallengesofusingexceptionhandlinginJava:
Complexity:Exceptionhandlingcanaddcomplexitytoyourcode.
Overhead:Exceptionhandlingcanaddoverheadtoyourcode.
Misuse:Exceptionhandlingcanbemisused,whichcanleadtoproblems.
Throw
Thethrowkeywordisusedtoexplicitlythrowanexception.Anexceptionisanobject that
represents an error that has occurred. When an exception is thrown, the execution of
the current method is stopped and control is transferred to the nearest catch block.
Thesyntaxforusingthethrowkeywordisasfollows:
throwexception;
Forexample,thefollowingcodethrowsanArithmeticExceptionexception:
intx=10;inty=
0;
try{
intz=x/y;
}catch(ArithmeticExceptione){
System.out.println("Error:Divisionbyzero");
Inthisexample,thevalueofyis0,whichisaninvalidvaluefordivision.Thetry
blocktriestodividexbyy,butanArithmeticExceptionexceptionisthrown. The catch
block prints the message "Error: Division by zero".
Throws
Thethrowskeywordisusedtodeclarethatamethodcanthrowanexception.When a
method declares that it can throw an exception, the caller of the method must be
prepared to handle the exception.
Thesyntaxforusingthethrowskeywordisasfollows:
publicvoidmethod()throwsException{
//...
WhereExceptionisthetypeofexceptionthatthemethodcanthrow.
Forexample,thefollowingmethoddeclaresthatitcanthrowanArithmeticException exception:
publicintdivide(intx,inty)throwsArithmeticException{
if(y==0){
thrownewArithmeticException("Divisionbyzero");
}
returnx/y;
}
The caller of the divide() method must be prepared to handle the
ArithmeticExceptionexception.Forexample,thefollowingcodecallsthedivide() method
and uses a try-catch block to handle the ArithmeticException exception:
intx=10;inty=
0;
try{
intz=divide(x,y);
}catch(ArithmeticExceptione){
System.out.println("Error:Divisionbyzero");
Finally
Thefinallyblockisablockofcodethatisexecutedregardlessofwhetherornotan exception
is thrown. The finally block is often used to clean up resources, such as closing files
or releasing memory.
Thesyntaxforusingthefinallyblockisasfollows:
try{
//...
}finally{
//...
Wherethecodeinthefinallyblockisexecutedregardlessofwhetherornotan exception is
thrown.
Forexample,thefollowingcodeusesafinallyblocktocloseafile,evenif an exception is
thrown:
Filefile=newFile("myfile.txt");try{
//Readfromfile
}catch(IOExceptione){
//Handleerror
}finally{
//Closefilefi
le.close();
In this example, the finally block will always be executed, even if an exception is
throwninthetryblock.Thisensuresthatthefileisalwaysclosed,evenifanerror occurs.
Exception handling isa powerful tool that can help youtowrite robust and reliable
Javacode.Byusingtry-catch,throws,andfinallyblocks,youcanensurethatyour code will
handle errors gracefully and continue to run even when unexpected problems occur.
Multithreadingisaprogrammingtechniquethatallowsmultipletasks to
run concurrently in a single program. This can be used to improve the performance
of a program by allowing multiple tasks to run at the same time, or to improve the
responsiveness of a program by allowing users to interact with the program while
other tasks are running in the background.
Threads are lightweight processes that can run concurrently in a single program.
Eachthreadhasitsownstack,registers,andprogramcounter.Thisallowsthreads to run
independently of each other, without interfering with each other.
Java supports multithreading through the use of threads and locks. Threads are
objectsthatrepresentasingleunitofexecution.Locksareobjectsthatcanbeused to
synchronize access to shared resources.
TocreateathreadinJava,youcanusetheThreadclass.TheThreadclassprovides a
number of methods that you can use to control the execution of a thread, such as the
start() method, which starts the thread, and the join() method, which waits for the
thread to finish.
TosynchronizeaccesstosharedresourcesinJava,youcanusethesynchronized keyword.
The synchronized keyword can be used to lock a block of code, which prevents other
threads from executing the code until the lock is released.
HerearesomeofthebenefitsofusingmultithreadinginJava:
Performance:Multithreadingcanbeusedtoimprovetheperformanceofa
program by allowing multiple tasks to run at the same time.
Responsiveness:Multithreadingcanbeusedtoimprovetheresponsiveness
ofaprogrambyallowinguserstointeractwiththeprogramwhileothertasks are
running in the background.
Scalability:Multithreadingcanbeusedtomakeaprogrammorescalableby
allowing it to handle more concurrent users.
HerearesomeofthechallengesofusingmultithreadinginJava:
Concurrency:Multithreadingcanintroduceconcurrencyproblems,suchas
race conditions and deadlocks.
Complexity:Multithreadingcanmakeaprogrammorecomplex,makingit
more difficult to understand and debug.
Threadsafety: Multithreadedprogramsmustbewrittentobethread-safe,
whichmeansthattheymustbedesignedtopreventconcurrentaccessto
shared resources from causing errors.
HerearesomeofthebestpracticesformultithreadinginJava:
Usethreadsonlywhennecessary:Notallprogramsneedtobemultithreaded. If a
program does not need to perform multiple tasks at the same time, then there
is no need to use threads.
Use the right number of threads: Using too many threads can actually slow
downaprogram.Theidealnumberofthreadsdependsonthespecificneeds of the
program.
Avoidusingsharedresources:Sharedresourcescanleadtoconcurrency
problems. If possible, avoid using shared resources in multithreaded
programs.
Uselockstosynchronizeaccesstosharedresources: Ifyoumustuseshared
resources, then use locks to synchronize access to them. This will prevent
concurrent access to the resources from causing errors.
Testyourmultithreadedprogramsthoroughly: Multithreadedprogramscanbe
moredifficulttotestthansingle-threadedprograms.Itisimportanttotestyour
multithreaded programs thoroughly to ensure that they are free of errors.
Byfollowingthesebestpractices,youcanwritemultithreadedJavaprogramsthat are
safe, efficient, and reliable.
Therearetwowaystocreateathreadin Java:
1. ByextendingtheThreadclass
Hereisanexampleofhowtocreateathreadbyextendingthe Threadclass:
Codesnippet
classMyThreadextendsThread{
@Override
publicvoidrun(){
System.out.println("Thisismythread!");
}
}
publicclassMain{
publicstaticvoidmain(String[]args){MyThreadthr
ead=newMyThread();thread.start();
}
}
2. ByimplementingtheRunnableinterface
Hereisanexampleofhowtocreateathreadbyimplementingthe Runnable
interface:
Codesnippet
classMyRunnableimplementsRunnable{
@Override
publicvoidrun(){
System.out.println("Thisismythread!");
}
}
publicclassMain{
publicstaticvoidmain(String[]args){
Threadthread=newThread(newMyRunnable());thread.start();
}
}
Once you have created a thread, you can start it by calling the start()method on
thethreadobject.Thestart()methodwillcausethethreadtobeginexecutingthe code in
the run()method.
Hereisanexampleofhowtostartathread:
Codesnippet
thread.start();
However,itisimportanttousethreadscarefully.Ifyouarenotcareful,threadscan cause
your program to become unstable or to crash.
Herearesometipsforusingthreadssafely:
Usesynchronizationwhenevermultiplethreadsaccessthesamedata.
Avoidusingblockingoperations,suchassleep()andwait(),inthreadsthat are
not supposed to block.
Usejoin()towaitforathreadtofinishbeforecontinuingexecution.
I/O inJava
I/OinJavaistheprocessofreadingandwritingdatatoandfromexternaldevices. Java
provides a comprehensive I/O API that allows developers to read and write data to
a variety of devices, including files, networks, and databases.
InputStream:Representsaninputstreamofbytes.
OutputStream:Representsanoutputstreamofbytes.
Reader:Representsaninputstreamofcharacters.
Writer:Representsanoutputstreamofcharacters.
TheJavaI/OAPIalsoprovidesavarietyofclassesforworkingwithfiles,networks, and
databases.
JavaApplets
AJavaappletisasmall,self-containedJavaprogramthatcanbeembeddedina web
page.Applets canbeusedtoaddinteractive content to webpages, suchas games,
calculators, and animations.
TocreateaJavaapplet,youmustextendthe java.applet.Appletclass.TheAppletclass
provides a number of methods that you can use to interact with the user, get
information about the browser environment, and draw graphics on the screen.
When a user views a web page that contains an applet, the applet code is
downloadedtotheuser'scomputerandexecutedbytheJavaVirtualMachine(JVM). The
applet then interacts with the user and the browser environment as specified by the
applet code.
HerearesomeofthebenefitsofusingJavaapplets:
Portability:JavaappletscanberunonanyplatformthathasaJVMinstalled.
Security:Javaappletscanbesandboxedtopreventthemfromaccessingthe user's
system files or network resources.
Interactivity:Javaappletscanbeusedtocreateinteractivewebpagesthat are
more engaging than static web pages.
HerearesomeofthelimitationsofusingJavaapplets:
Security:Javaappletscanbeusedtolaunchmaliciousattacksagainstusers'compu
ters.
Performance:Javaappletscanbeslowtoloadandrun,especiallyonolder
computers.
Support:NotallbrowserssupportJavaapplets.
Overall, Java applets can be a useful tool for creating interactive web pages.
However,itisimportanttobeawareofthesecurityandperformancelimitationsof Java
applets before using them.
StringsinJavaareobjects. Thismeansthattheyhavepropertiesand
methods that can be used to manipulate them.
Stringsareimmutable.Thismeansthatonceastringiscreated,itcannotbe
changed.
The Java String class provides a number of methods for
manipulatingstrings.Thesemethodsincludemethodsforfindingandreplacingcha
racters, converting strings to other data types, and formatting strings.
TheJavaStringBufferandStringBuilderclassesaremutable. Thismeansthat the
strings they represent can be changed after they are created.
TheStringBufferandStringBuilderclassesareoftenusedwhenstringsneed to be
changed frequently. This is because they are more efficient than the String
class when it comes to making changes to strings.
HerearesomeexamplesofhowtousetheJavaStringclasstomanipulatestrings: Code
snippet
//Findthefirstoccurrenceoftheletter"a"inthestring"Hello,world!"
intindex="Hello,world!".indexOf('a');
//Replacealloccurrencesoftheletter"o"withtheletter"x"inthestring"Hello,worl
d!"
StringnewString="Hello,world!".replace('o','x');
//Convertthestring"Hello,world!"toacharacterarray.char[]chars=
"Hello,world!".toCharArray();
HerearesomeexamplesofhowtousetheJavaStringBufferandStringBuilder classes to
manipulate strings:
Codesnippet
//CreateanewStringBufferobject.
StringBufferbuffer=newStringBuffer("Hello,world!");
//Appendthestring"Goodbye!"totheendofthebuffer.buffer.append("Goodbye!");
//Overwritethefirstoccurrenceoftheletter"o"inthebufferwiththeletter"x".
buffer.replace(0,1,"x");
//ConverttheStringBufferobjecttoastring.StringnewS
tring=buffer.toString();
EventHandlinginJava
Hereisanexampleofhowtohandleamouseclickevent: Code
snippet
//CreateanewJButtonobject.
JButtonbutton=newJButton("ClickMe!");
//CreateanewActionListenerobject.
ActionListenerlistener=newActionListener(){@Overri
de
publicvoidactionPerformed(ActionEvente){
//Dosomethingwhenthebuttonisclicked.
}
};
//Registerthelistenerwiththebutton.button.addActionListener(listen
er);
HerearesomeofthebenefitsofusingeventhandlinginJava:
Itmakescodemoremodularandreusable.
Itmakescodeeasiertomaintainandupdate.
Itallowsformorecomplexandsophisticateduserinterfaces.
Overall,eventhandlingisapowerfultoolthatcanbeusedtomakeJavaprograms more
user-friendly and responsive.
IntroductiontoAWT
The Abstract Window Toolkit (AWT) is a set of classes that provide a basic
foundationforcreatinggraphicaluserinterfaces(GUIs)inJava.AWTcomponents are
platform-dependent, which means that they look and behave differently on different
operating systems.
AWTControls
AWTprovidesavarietyofcontrolsthatcanbeusedtocreateGUIs.Someofthe most
common AWT controls include:
Labels:Labelsareusedtodisplaytext.
TextFields:Textfieldsareusedtoallowuserstoentertext.
Buttons:Buttonsareusedtoperformactions.
Listboxes:Listboxesareusedtodisplayalistofitems.
Scrollbars:Scrollbarsareusedtoscrollthroughlistsandotherdata.
LayoutManagers
LayoutmanagersareusedtocontrolthelayoutofcomponentsinaGUI.AWT provides a
variety of layout managers, including:
BorderLayout:TheBorderLayoutmanagerdividesacontainerintofive
regions: north, south, east, west, and center.
FlowLayout:TheFlowLayoutmanagerlaysoutcomponentsinasinglerowor
column, depending on the container's width.
GridLayout:TheGridLayoutmanagerlaysoutcomponentsinagrid,witha
specified number of rows and columns.
CardLayout:TheCardLayoutmanagerdisplaysonecomponentatatime,and
allows users to switch between components.
UsingAWTControlsandLayoutManagers
TouseAWTcontrolsandlayoutmanagers,youmustfirstcreateacontainerobject. A
container is an object that can hold other components. Once you have created a
container, you can add components to it by calling the add() method.
When you add a component to a container, you must also specify the layout
managerthatyouwanttouse.YoucandothisbycallingthesetLayout()method.
Thelayoutmanagerwillthendeterminehowthecomponentisdisplayed.For
example,ifyouusetheBorderLayoutlayoutmanager,thecomponent willbe
displayed in the center of the container.
Conclusion
AWT is a powerful tool that can be used to create GUIs in Java. AWT provides a
varietyofcontrolsandlayoutmanagersthatcanbeusedtocreateawidevarietyof GUIs.
HereisanexampleofasimpleGUIthatusesAWTcontrolsandlayoutmanagers:
importjava.awt.*;import
java.awt.event.*;
publicclassSimpleGUI{
publicstaticvoidmain(String[]args){
//Createaframe.
Frameframe=newFrame("SimpleGUI");
//Createalabel.
Labellabel=newLabel("Thisisalabel.");
//Createatextfield.
TextFieldtextField=newTextField("Entertexthere.");
//Createabutton.
Buttonbutton=newButton("Clickme!");
//Addthelabeltotheframe.frame.
add(label);
//Addthetextfieldtotheframe.frame.add(text
Field);
//Addthebuttontotheframe.frame
.add(button);
//Setthelayoutmanagerfortheframe.frame.set
Layout(newFlowLayout());
//Setthesizeoftheframe.frame.s
etSize(300,200);
//Maketheframevisible.frame.se
tVisible(true);
//Registeralistenerforthebutton.button.addActionListener(n
ewActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
//Dosomethingwhenthebuttonisclicked.System.out.println(textField.g
etText());
}
});
}
}