Sunteți pe pagina 1din 45

Create Login Window in Swing

Creating a login page, if login is successful, then proceed to the next frame. This is the most given homework i think so, because many people have been asking this since time. Fine, now i've done it. This program that i've written don't just look big and not just limited to the specified homework authentication!, instead there are many things to learn from it.

What else is coded? What still can i know?


". #sing $T%& tags in 'wing, here i've used the (a) tag. *. The next one was adding components other than menus! to +%enu,ar. -. 'haring a common adapter class among the components .. Catching an enter key and doing the action what the users do most without clicking on the button to login!. /. 0isposing a frame, instead of making it invisible or terminating the entire program.

Begin the code!

#ser&ogin

1elcome Frame

import javax.swing.23 import java.awt.23 import java.awt.event.23 class #ser&ogin extends +Frame 4 +,utton login,cancel3 +TextField uname3 +5asswordField pass3 +&abel u,p3 public #ser&ogin ! 4 setTitle 6&ogin6!3 set&ayout new 7rid&ayout -,*!!3 set0efaultClose8peration 9:;T<8=<C&8'9!3 set>isible true!3 u?new +&abel 6#sername6!3 p?new +&abel 65assword6!3 uname?new +TextField *@!3 pass?new +5asswordField *@!3 login?new +,utton 6&ogin6!3 cancel?new +,utton 6Cancel6!3 add u!3 add uname!3 add p!3 add pass!3 add login!3 add cancel!3 uname.reAuestFocus !3 cancel.addBction&istener new Bction&istener !4 public void action5erformed Bction9vent ae! 4 'ystem.exit @!3 C C!3 login.addBction&istener new Bction&istener !4 public void action5erformed Bction9vent ae!

4 'tring un?uname.getText !3 'tring pa?new 'tring pass.get5assword !!3 if un.eAuals 6myuser6!!DD pa.eAuals 6mypass6!!! 4 dispose !3 new 1elcomeFrame !3 C C C!3 EeyBdapter k?new EeyBdapter !4 public void key5ressed Eey9vent ke! 4 if ke.getEeyCode !??Eey9vent.>E<9=T9F! login.doClick !3 C C3 pass.addEey&istener k!3 uname.addEey&istener k!3 pack !3 set&ocationFelativeTo null!3 C class 1elcomeFrame extends +Frame 4 +&abel exit3 +%enu,ar mbar3 +&abel label3 public 1elcomeFrame ! 4 setTitle 61elcome6!3 set'iGe .@@,.@@!3 set>isible true!3 set0efaultClose8peration 9:;T<8=<C&8'9!3 mbar?new +%enu,ar !3 mbar.set&ayout new Flow&ayout !!3 label?new +&abel 6Hou are logged in.6!3 mbar.add label!3 exit?new +&abel 6(html)(a href?'')9xit(Ia)(Ihtml)6!3

exit.setCursor new Cursor Cursor.$B=0<C#F'8F!!3 exit.setFont new Font 6Tahoma6,Font.5&B;=,"-!!3 exit.add%ouse&istener new %ouseBdapter !4 public void mouseClicked %ouse9vent ae! 4 'ystem.exit @!3 C C!3 mbar.add exit!3 set+%enu,ar mbar!3 set9xtended'tate %B:;%;J90<,8T$!3 C C public static void main 'tring argsKL! 4 new #ser&ogin !3 C C

Explanation
javax.swing.*: +Frame, +&abel, +TextField, +5asswordField, +%enu,ar, +,utton used here. java.awt.*: 7rid&ayout, Flow&ayout, Cursor, Font used here. java.awt.event.*: Bction9vent, Bction&istener, Eey&istener, Eey9vent used here. na!e.re" est#oc s$%: This method makes the component uname here! focused when the frame appears. cancel.add&ctionListener$....%'S(ste!.exit$)%*+: 1hen cancel is clicked exit the program. n, na!e.get-ext$%: 7et what the user types in the field uname pa,new String$pass.get.assword$%%: get5assword ! in +5asswordField returns char[] so using the constructor of the java.lang.String class String(char[] c), i've used it.

e" als$%: Compares strings whether they are eAual or not. $ere, un, pa are compared with myuser, mypass respectively. dispose$%: ;f they username,password! become true, dispose the #ser&ogin frame. new Welco!e#ra!e$%: Create WelcomeFrame object.

What i/ ser presses enter?


k,new 0e(&dapter$%'+: 5rovide the body for the interface by providing body for the method s! in it. $ere only keyPressed( ey!vent) is used since this is an adapter class and not directly listener interface, so it's anonymous inner class is written and it's reference is stored in k ke.get0e(Code$%: Feturns the code of what key user presses. 0e(Event.102E3-E4: This is a static int variable containing the code for !"#!$ login.doClick$%: 0oes a click on the button login therefore, it's action event is generated and things will be done. !port javax.swing.** i!port java.awt.** i!port java.awt.event.** p 5lic class Log extends 6#ra!e ' p 5lic static void !ain$String78 args% ' Log /ra!e-a5el , new Log$%* + 6B tton 5login , new 6B tton$9Login9%* 6.anel panel , new 6.anel$%* 6-ext#ield tx ser , new 6-ext#ield$:;%* 6.assword#ield pass , new 6.assword#ield$:;%* Log$%' s per$9Login & tenti/ication9%* setSi<e$=))>?))%* setLocation$;))>?@)%* panel.setLa(o t $n ll%* tx ser.setBo nds$A)>=)>:;)>?)%* pass.setBo nds$A)>B;>:;)>?)%*

5login.setBo nds$::)>:))>@)>?)%* panel.add$5login%* panel.add$tx ser%* panel.add$pass%* getContent.ane$%.add$panel%* setCe/a ltCloseDperation$6#ra!e.EEF-2D32CLDSE%* set1isi5le$tr e%* actionlogin$%* + p 5lic void actionlogin$%' 5login.add&ctionListener$new &ctionListener$% ' p 5lic void action.er/or!ed$&ctionEvent ae% ' String p na!e , tx ser.get-ext$%* String ppaswd , pass.get-ext$%* i/$p na!e.e" als$9test9% GG ppaswd.e" als$9:?=H;9%% ' new/ra!e reg#ace ,new new/ra!e$%* reg#ace.set1isi5le$tr e%* dispose$%* + else ' 6Dption.ane.showIessageCialog$n ll>9Wrong .assword J Kserna!e9%* tx ser.set-ext$99%* pass.set-ext$99%* tx ser.re" est#oc s$%* + + +%* + + and you must save this source below with name 9new/ra!e.java9 i!port javax.swing.** i!port java.awt.** i!port java.awt.event.** p 5lic class new/ra!e extends 6#ra!e ' p 5lic static void !ain$String78 args% ' new/ra!e /ra!e-a5el , new new/ra!e$%*

+ 6La5el welco!e , new 6La5el$9Welco!e to a 3ew #ra!e9%* 6.anel panel , new 6.anel$%* new/ra!e$%' s per$9Welco!e9%* setSi<e$=))>?))%* setLocation$;))>?@)%* panel.setLa(o t $n ll%* welco!e.setBo nds$A)>;)>:;)>B)%* panel.add$welco!e%* getContent.ane$%.add$panel%* setCe/a ltCloseDperation$6#ra!e.EEF-2D32CLDSE%* set1isi5le$tr e%* + + ,oth of sources will give you a frame like this M

if you click login button, you will redirect to a new frame like this M

pack$%: 5ack everything. 'how only the components and not the extra space. setLocation4elative-o$n ll%: Center the +Frame.

Swing Cata Binding Exa!ple


Supported for JDK 1.5 and above only As an example of how the the data binding tools can be used, consider the following Phone Book example. The phone book manages a set of phone groups. Each phone group in turn holds onto one or more persons. For each person, various e-mail and phone contact information is maintained. Editing a person's description should update the same data shown in the list. The final code for the Phone Book pro ect is available here.

". #se 0esigner to create the skeleton of the 6.honeBook.java class

*. Create the following model classesM


Class .erson with propertiesM na!e, e!ail, phone, !o5ile.hone:, !o5ile.hone? Class .honeLro p with propertiesM na!e, persons Class .honeLro ps with propertiesM gro ps

-. Bdd the following to the 6.honeBook classM


private PhoneGroups m_groups = new PhoneGroups();

Bnd add some initial dataM


PhoneGroup group1 = new PhoneGroup("Developer Team"); m_groups.addGroup(group1); group1.addPerson(new Person("Konstantin Scheglov", "kosta@nospam.com", "1234567890", "", "")); group1.addPerson(new Person("Alexander Mitin", "mitin@nospam.com", "", "0987654321", "")); group1.addPerson(new Person("Alexander Lobas", "lobas@nospam.com", "", "", "111-222-333-00"));

.. 'et the content for the group viewer. Click the Bindings tab in the editor. 'elect !2gro pList in the -argets $Widgets% list, MSel/ D5jectN in the -arget .roperties list, select !2gro ps in the Iodel $Beans% list, and gro ps in the Iodel .roperties list.

/. Click the Bind button to open the Create Cata Binding dialog. !2gro ps.gro p contains elements of type .honeLro p, so select the type .honeLro p and its MEL ExpressionN property. ;n the 9& 9xpression field, type 6N4nameC 4NpersonCountC!6. =ote that selecting the na!e property would result in just the name of the group being displayed. Hou can use 9& 9xpressions to create more complex results. ;n this case, we

can show the name plus the number of people in the group.

O. Click D0 to see !2gro ps.gro ps bound to !2gro psList in the table. Hou can also see that the detail binding between !2gro psList and the EL Expression has also been created.

P. Fun the application to see that the list of phone groups is populated and that each group shows its person count.

Q. =ext we would like selecting a group to show all of its contained persons. 'witch back to the Bindings tab. 'elect the MSel/ D5jectN of the !2person-a5le in the -arget Widget list and !2gro pList and selectedEle!entJpersons in the Iodel Widget list and click the Bind button to open the Create Cata Binding dialog.

R. 1e need to show the properties of a .erson object in !2person-a5le, so click the &dd button to add a table column binding for each property na!e, e!ail, phone, !o5ile.hone: and !o5ile.hone?!. Hou can order the .erson properties using the MM and NN buttons

"@. Click D0 twice and run the application. 'ee that selecting a group now updates the .ersons list.

"". 'witch back to the Bindings tab. =ext we need to bind selectedEle!ent of the !2person-a5le a 5erson object! into the various text editors.

"*. 'elect the first -ext widget !2na!e-ext#ield! and its text property and the !2person-a5le and its selectedEle!entJna!e property. Click the Bind button to open the Create Cata Binding dialog. &eave everything set to the defaults and click the D0 button.

"-. ,ind each selectedEle!ent property to its associated -ext field.

".. Fun the application. 'ee that selecting a group updates the .ersons list and selecting a .erson now updates each of the -ext fields.

"/. Blso note that changing any of the data in the text fields immediately updates the data in the table. -he !agic o/ data 5inding!

9xcept as otherwise noted, the content of this page is licensed under the Creative Commons Bttribution -.@ &icense, and code samples are licensed under the Bpache *.@ &icense. For details, see our 'ite 5

ode as well.

To place buttons, text labels and other components on the program window, you need to understand about +5anel. ;t is a kind of container for components, which occupies the rectangular piece on the screen and shows the components arranged in some simple way. $ow exactly the components are arranged depends on which layout have you set to that panel. For the manual programming you will likely need to know at least the ,order&ayout which places four components at the sides and one large component into the middle, then the Flow&ayout which usually arranges them side by side into horiGontal row and finally the 7rid&ayout which arranges components into arbitrary n 2 m table. There are more of them, but others seem too complex for beginners. The key idea here is that a 6component6 can be not just a button or check box S it can also be another %Panel. Hou can get a complex user interface by just putting panels one inside another and choosing the layouts for them.

8nce you have an instance of %Panel, call the .set&ayout method to set the layout and then the .add method to add the components to it. For the 'order&ayout, you need to give the location as a second parameter. For instance, call myPanel.add(my'utton, 'order&ayout."orth) to place your button at the top edge.

The top level container, which appears on the screen representing java application, is not a %Panel but %Frame. Call my%Frame.get(ontentPane().add(my%Panel, 'order&ayout.(enter) to add your main panel to the instance of %Frame.

To make your application to do more than just appear you also need to understand the )ction&istener interface. 9very nonSabstract )ction&istener has a single method, actionPer*ormed, which is called automatically when the user makes an 6action6 with the component on which the listener is registered the action with button is, obviously, pressing it!. To register action listener for the button or other component, call the method .addBction&istener..

EditMethod 1 of 2: Makin

the !verall "ra#e

!. ! $reate a %la&& that e'tend& the JFrame %la&&. This class will hold all of "our #$% components, such as buttons and textfields. &. & Plan the overall layout of your fir&t appli%ation. A good start could be a central panel with BorderLayout with another panel at the bottom 'BorderLayout.South(. This second panel ma" have the FlowLayout and contain several buttons, check boxes and other similar controls. Finall", place the big JTextArea into the center of the central component. )ou will be able to use its getText() and setText() methods to do some text-based interaction with the user.

*. *

(rite %on&tru%tor to your %la&&. This constructor must create all panels and components "ou plan, place them properl" into each other and add the final panel the +holds all+ to "ou frame (myFrame.getContentPane().add(myLargePanel, BorderLayout.Center).

,. , (rite the #ain #ethod )hi%h )ill be the pro ra#*& entry point. %n this method, create an instance of "our frame, set the initial si-e and location 'use .setSi e(x,y) and .setLo!ation(width, height) ( and make it to appear on the screen b" calling .set"isi#le(true). EditMethod 2 of 2: Pro ra##in re&pon&e& to the u&er a%tion&

!. ! Make your fra#e i#ple#ent the ActionListener interfa%e. This will allow "our class to listen to components' activities.

&. & "or every button+ %he%k bo' or other %ontrol that you have %reated+ invoke it& #ethod .addA!tionListener, passing "our frame 'this( as parameter. *. * !verride ,%tion-i&tener*& ab&tra%t #ethod+ actionPerformed(ActionEvent event). %n this method, "ou should put if statements checking where does the action event come from. This if statement should have a condition that sa"s something like + i$ (e%ent.getSour!e() && #utton'(+. This checks where the event came from and if it came from "our button. %nside the if statement, do whatever needs to be done when "our button is pressed.

,. , JTextArea has a method .setText((myText() which seems good as the wa" to program some visible response on "our action.

Edit .ideo

Edit /ip&

%f "ou want to draw "our own graphical ob ects 'like chessboard(, read about the .anvas component. %t can be placed into "our application like an" other, but "ou need to write method .paint which is full" responsible for drawing it. %t is possible to put all components into single panel using )ridBagLayout, but this class is more difficult to master. %t is not much more difficult to implement the *ouseListener interface and use .add*ouseListener to register it to an" component. %f "ou need to ask some input string from the user, call the static method /+,tionPane.show-n,ut.ialog(this, (*y message(). The first parameter must be "our application frame or some panel 'the input box will appear in the center of the parent(. The method returns the value that user enters into the dialog box. %n man" practical applications the most useful 0wing component is /Table. After "ou master the basic, proceed directl" to it.

Edit (arnin &

0ome development environments offer the possibilit" to compose the 0wing #$% in a +user friendl"+ wa". 1owever the" are fre2uentl" unable to complete a panel with advanced features properl". 0uch features include trees, tables, lists and combo boxes that change the" content while the program is running, also components with custom data models and so on. The code,

composed in a +user friendl"+ wa" ma" become a real nightmare if "ou need later to finish it manuall". 1ence do not stick to an" +user friendl" #$% designer+ too much as it will restrict "our programming power to its limited capabilities. 0wing is a single thread application. %f "our action handling takes too much computing time, it will +free-e+ until "our .a!tionPer$ormed method returns. 3earn and use ava multithreading to keep the 0wing +alive+ while "our timeconsuming process is running. The most of the methods of the 0wing components can onl" be safel" called from the event dispatching thread 'the one that calls .a!tionPer$ormed and other similar listener methods(. %f "ou need to call them from some other thread 'for instance, to update the progress bar or show results of some longrunning process(, read about the Swing/tils.in%o0eLater.

Edit 0elated )iki1o)&

$ow to 7et ;nput from #ser in +ava

$ow to Create an Brbitrary Code

$ow to %ake a +ava Bpplet Bnimation 1ith Carpstudio

$ow to ;nstall +ava on &inux

$ow to ;nstall +ava

$ow to 1rite Hour First 5rogram in +ava

$ow to #se 7raphics in a +ava Bpplet

$ow to 5rogram in +ava

Edit Sour%e& and $itation&

Calc lator
;n this tutorial you will learn the basics to creating a calculator with a graphical user interface. ; use =et,eans for this, ; highly suggest you use =et,eans or a similar ;09 ;ntegrated 0evelopment 9nviornment!. Hou will also need +ava P for the =imbus look and feel. ;n this tutorial you will learn about using the Bction&istener and the building of a 7#;. To begin we will need to add a few imports. import java.awt.23 S essential for visual components. import javax.swing.23 S again, it's essential for the components and to set our visual feel. import java.awt.event.23 S essential for handling events such as our Bction&istener.

; will be naming my class (alculator. 'o you'll start this class off like you would any class, public class Calculator 4. 8nly now we need to make use of +Frame and Bction&istener. Hou want to extend +Frame and implement Bction&istener like so, public class Calculator extends +Frame implements Bction&istener 4 C 'ince every program needs a main method, we can add it in right now.
1 public static void main(String[] arguments) { 2 3 Calculator c = new Calculator();

&et's begin on our declarations now. For our frame we will have five rows of components, so ; make / panels, one for each row. +5anelKL row ? new +5anelK/L3 0ecide how many buttons you will have on your calculator. ; use "R. +,uttonKL button ? new +,uttonK"RL3 1ith these buttons we have only declared them, we are going to need to ;nitialiGe them shortly. 9ach button will need a string, but instead of typing out "R lines to initialiGe each one we are going to create a loop for that. 'o we are going to put the string values for each button in an array to use for our loop later. =ote, be careful on the order, you want it setup for buttonK@L to eAual button'tringK@L.
1 String[] buttonString = {!"!# !$!# !%!# !&!# 2 !'!# !(!# !)!# !*!# 3 !1!# !2!# !3!# !+!# ' !,!# !-!# !C!# !.!# ( !&-*!# !=!# !/! ;

Blright, now let's create arrays for the dimension widths and heights of the buttons we will create. intKL dim1 ? 4-@@, ./, "@@, R@C3 S our widths will be -@@, ./, "@@, and R@ for the different types of components. intKL dim$ ? 4-/, .@C3 S our heights will be -/ for the display and .@ for the buttons. &et's declare and initialiGe our dimensions here. 0imension display0imension ? new 0imension dim1K@L, dim$K@L!3 S #ses the first integer in the width, and the first integer in height.

0imension regular0imension ? new 0imension dim1K"L, dim$K"L!3 S #ses the second integer in the width, and the second integer in height. 0imension rColumn0imension ? new 0imension dim1K*L, dim$K"L!3 S #ses the third integer in the width, and the second integer in height. 0imension Gero,ut0imension ? new 0imension dim1K-L, dim$K"L!3 S #ses the fourth integer in width, and the second integer in height. =ow we need to declare some booleans for our functions S adding, subtracting, multiplying, and dividing. &et's use an array for that. booleanKL function ? new booleanK.L3 S not initialiGed yet 1e'll need some temporary doubles later for our calculations so, doubleKL temporary ? 4@, @C3 S these are now initialiGed. &et's create a display using +TextBrea. +TextBrea display ? new +TextBrea ",*@!3 and the last of our declarations, just for a more appealing effect, we will use a different font, style, and pt. Font font ? new Font 6Times new Foman6, Font.,8&0, ".!3 Blright, let's move on to making the constructorT This is how we begin with it,
1 Calculator() { 2 3 --Same as class name

;nside our constructor we start off with super 6Title6!3 S this is reAuired, you will recieve errors if you don't begin with this. Feplace 6Title6 with the title of your program. =ow call the method set0esign !3 S you will recieve an error for this as we have not yet created that method. To set the siGe of the frame we will use set'iGe w, h!3 replace the width with =@) and the height with ?;) 1e will make it so the frame cannot be resiGed, which can sometimes cause the layout to get messed up.

setFesiGable false!3 add in set0efaultClose8peration 9:;T<8=<C&8'9!3 to exit the frame when closed. 8kay, now we think for a second, how to layout the frame. ; want to use / rows, and have up to / components for each row. 'o ;'m going to use the 7rid&ayout manager for this. 7rid&ayout grid ? new 7rid&ayout /,/!3 with the first / in number of rows, and the second / for up to how many components we will allow in the row. to set the layout we will use set&ayout, set&ayout grid!3 %oving on we are still in the constructor!, let's initialiGe our booleans. ;nstead of using . lines of code to do this, we can use a for loop.
1 0or(int i = /; i 1 '; i&&) 2 0unction[i] = 0alse;

'o let's examine how the loop works. 1e are creating an integer, i. so while i is less than ., we have it set function to *alse, +ith it incrementing one each time. Since +e +ant *unction[,], *unction[-], *unction[.], and *unction[/] to 0e set e1ual to *alse, nothing higher and nothing lo+er. "o+ make sure you understand the concept o* a loop, 0ecause +e +ill 0e using a lot o* them. 2kay, so i* +e +ere to use the Flo+&ayout manager, the components are dropped in an area the same +ay +ords are organi3ed on a page in !nglish. From le*t to right, and *rom top to 0ottom. So 4 think +e5ll use Flo+&ayout *or each ro+ no+. #his +ill 0e ho+ +e set up ro+ -(+hich +e5ll call as ro+[,] later), Flo+&ayout *- 6 ne+ Flo+&ayout(Flo+&ayout.(!"#!$)7 8 We are only going to use this *or ro+-. For the remainder o* the ro+s +e only need to set up one ne+ Flo+&ayout. Flo+&ayout *. 6 ne+ Flo+&ayout(Flo+&ayout.(!"#!$,-,-)7 8 the -5s are integers *or hori3ontal gap and vertical gap. &et5s no+ initiali3e our %Panel ro+5s so +e can use them. +e +ill create a loop *or this.
1 0or(int i = /; i 1 (; i&&) 2 row[i] = new 23anel();

"o+ +e can use our ro+s9 So let5s set the layouts +e made to the ro+s. to do this it +ill 0e component.set&ayout(layout). +hat +e +ill do is, ro+[,].set&ayout(*-)7 8 +hich +ill make our *irst ro+ the *irst *lo+layout. "o+ since +e are using the second *lo+layout *or the remainder o* the ro+s +e can use a loop.

1 0or(int i = 1; i 1 (; i&&) 2 row[i],set4a5out(02);

2ur ro+s no+ have the layout +e need them to. Since there5s a *e+ o* the same things +e have to do *or every 0utton, let5s create another loop.
1 0or(int i = /; i 1 1%; i&&) { 2 3 ' ( ) button[i] = new 26utton(); button[i],set7e8t(buttonString[i]); button[i],set9ont(0ont); button[i],add:ction4istener(t;is);

2kay no+ let5s take a look at +hat this code does. We are setting our te:t in the 0uttons +ith the same te:t *rom our 0uttonString. so 0utton[,] +ill have the te:t *rom 0uttonString[,], 0utton[-] +ill have the te:t *rom 0uttonString[-] and so on. ;ere +e are setting the *ont +e declared to every 0utton. the .add)ction&istener(this)7 +ill 0e important *or later +hen +e need to make the 0uttons actually +ork. Well that5s *or the 0uttons, 0ut no+ +hat a0out the display< We have a *e+ things to do +ith the display too. We have no need *or a loop since +e are only dealing +ith one component no+.
1 displa5,set9ont(0ont); 2 displa5,set<ditable(0alse); 3 displa5,setComponent=rientation(Component=rientation,>?@A7B7=B4<97);

So here, +e are setting the *ont, making it so the input is not allo+ed 0y key0oard, and setting it so the input appears *rom right to le*t on the display. "o+ +e can +ork on setting si3es *or all o* our components. 4* you remem0er correctly +e created a dimension *or the display, the regular 0uttons, the 0uttons on the right column, and the 3ero 0utton. #o set the si3e +e +ill use [i]component.setPre*erredSi3e For our display S display.set5referred'iGe display0imension!3 For the regular buttons and the right column buttons we will use loops.
1 0or(int i = /; i 1 1'; i&&) 2 button[i],set3re0erredSiCe(regularDimension);

3 0or(int i = 1'; i 1 1$; i&&) ' button[i],set3re0erredSiCe(rColumnDimension);

and for Gero, we just need to use S buttonK"QL.set5referred'iGe Gero,ut0imension!3 $ere is where we add components to the panel, and the panels to the frame. To add the component to the panel use panel.add component!3 ;'ll show you what we need, rowK@L.add display!3 this adds our display to row ". and adding the panel, add rowK@L!3 which adds row". The other rows will be different because we will be using loops, Follow along for row*.
1 0or(int i = /; i 1 '; i&&) 2 row[1],add(button[i]); 3 row[1],add(button[1']); ' add(row[1]);

1e loop through the first . buttons and add them, then we add in button "/. $ere are the remaining rowsM
/1 0or(int i = '; i 1 $; i&&) /2 row[2],add(button[i]); /3 row[2],add(button[1(]); /' add(row[2]); /( /) 0or(int i = $; i 1 12; i&&) /" row[3],add(button[i]); /$ row[3],add(button[1)]); /% add(row[3]); 1/ 11 row['],add(button[1$]); 12 0or(int i = 12; i 1 1'; i&&) 13 row['],add(button[i]); 1' row['],add(button[1"]); 1( add(row[']);

=ow all we need to do with our constructor is add on set>isible true!3 to it and we're done 8kay, so right now you are recieving * errors and you cannot compile yet, so let's fix those errors so you can see how your calculator looks. 8utside of our constructor we can create a method called set0esign !.
1 public 0inal void setDesign() { 2 3 ' ( ) " tr5 { E?Fanager,set4ooG:nd9eel( !com,sun,Hava,swing,pla0,nimbus,Iimbus4ooG:nd9eel!); catc;(<8ception e) {

This is the set0esign method, for more info on the look and feel look into +ava &ookBndFeel. S ,ecause using the =imbus&ookBndFeel we reAuire +ava P. &et's fix this last error so we can see how it looksT below your set0esign method you can create a new one called action5erformed, this is reAuired when using the Bction&istener.
1 public void action3er0ormed(:ction<vent ae) { 2 3

Hou can leave it blank now, we will be adding into it later. =ow if you run the program you should be able to see what our calculator will look like. The buttons do not work yet, we will get to that last. 1e have some methods to create now. 8ne method for our clear button, one method for our plus minus button, one method for sAuare root, and one method for getting our results from the functions. ; will be posting the full methods and explaining them in comments. &et's start with clear !.
/1 public void clear() { /2 /3 tr5 { displa5,set7e8t(!!); -- Sets t;e displa5 blanG

/' /( /) /" /$ /% 1/

0or(int i = /; i 1 '; i&&) 0unction[i] = 0alse; -- Sets t;e 0unctions bacG to 0alse 0or(int i = /; i 1 2; i&&) temporar5[i] = /; -- Sets our temporar5 variables bacG to / catc;(Iull3ointer<8ception e) {

=ow our sAuare root method.


1 public void getSJrt() { 2 3 tr5 { double value = Fat;,sJrt(Double,parseDouble(displa5,get7e8t())); -Create a variable 0or value# and use Fat;Ks sJuare root to 0ind value displa5,set7e8t(Double,toString(value)); -- Sets displa5 to new ' value ( catc;(Iumber9ormat<8ception e) { ) "

=ow our positive negative method.


/1 public void get3osIeg() { /2 /3 /' /( tr5 { double value = Double,parseDouble(displa5,get7e8t()); -- again we create a variable 0or our current value i0(value L= /) { -- i0 t;e value isnKt /

value = value + (*1); -- we multipl5 it b5 *1 to get itKs opposite value displa5,set7e8t(Double,toString(value)); -- set t;e te8t to t;e /) new value, /" /$ /% 1/ 11 12 catc;(Iumber9ormat<8ception e) { else {

and now our result method which is a little more complex.


/1 public void get>esult() { /2 double result = /; -- variable 0or result temporar5[1] = Double,parseDouble(displa5,get7e8t()); --our second /3 temporar5 number 0rom displa5 String temp/ = Double,toString(temporar5[/]); --necessar5 string 0or /' te8t o0 0irst temp String temp1 = Double,toString(temporar5[1]); --necessar5 string 0or /( te8t o0 second temp /) /" /$ /% 1/ 11 12 13 1' 1( 1) 1" 1$ tr5 { catc;(:rra5?nde8=ut=06ounds<8ception e) { i0(temp1,contains(!*!)) { -- same as above wit; second temporar5 String[] temp11 = temp1,split(!*!# 2); temporar5[1] = (Double,parseDouble(temp11[1]) + *1); at * temporar5[/] = (Double,parseDouble(temp//[1]) + *1); --puts string bacG in double wit; t;e real value, tr5 { i0(temp/,contains(!*!)) { --i0 0irst string contains * String[] temp// = temp/,split(!*!# 2); --split into two strings

i0(0unction[2] == true) --we start o00 wit; multiplication obviousl5 result = temporar5[/] + temporar5[1]; --sets result to 1% multiplication o0 0unction 2/ 21 22 23 2' 2( 2) 2" 2$ 2% else i0(0unction[3] == true) --now division

result = temporar5[/] - temporar5[1]; else i0(0unction[/] == true) --now addition result = temporar5[/] & temporar5[1]; else i0(0unction[1] == true) --now subtraction result = temporar5[/] * temporar5[1]; displa5,set7e8t(Double,toString(result)); --displa5 now ;as result 0or(int i = /; i 1 '; i&&) 0unction[i] = 0alse; --set all t;e 0unctions bacG to 0alse catc;(Iumber9ormat<8ception e) {

3/ 31

=ow that we have all the methods we need, all we have to do is make our buttons work. This is the working method for action5erformed, try not to copy and paste, try to type it out on your own. it's all explained in the paragraph below.
/1 public void action3er0ormed(:ction<vent ae) { /2 /3 /' /( /) /" /$ /% 1/ 11 12 13 1' 1( 1) 1" 1$ 1% 2/ 21 22 23 2' 2( 2) 2" 2$ 2% i0(ae,getSource() == button[$]) displa5,append(!1!); i0(ae,getSource() == button[%]) displa5,append(!2!); i0(ae,getSource() == button[']) displa5,append(!'!); i0(ae,getSource() == button[(]) displa5,append(!(!); i0(ae,getSource() == button[)]) displa5,append(!)!); i0(ae,getSource() == button["]) { --subtract 0unction[1] temporar5[/] = Double,parseDouble(displa5,get7e8t()); 0unction[1] = true; displa5,set7e8t(!!); i0(ae,getSource() == button[/]) displa5,append(!"!); i0(ae,getSource() == button[1]) displa5,append(!$!); i0(ae,getSource() == button[2]) displa5,append(!%!); i0(ae,getSource() == button[3]) { --add 0unction[/] temporar5[/] = Double,parseDouble(displa5,get7e8t()); 0unction[/] = true; displa5,set7e8t(!!);

3/ 31 32 33 3' 3( 3) 3" 3$ 3% '/ '1 '2 '3 '' '( ') '" '$ '% (/ (1 (2 (3 (' (( ()

i0(ae,getSource() == button[1/]) displa5,append(!3!); i0(ae,getSource() == button[11]) { --multipl5 0unction[2] temporar5[/] = Double,parseDouble(displa5,get7e8t()); 0unction[2] = true; displa5,set7e8t(!!); i0(ae,getSource() == button[12]) displa5,append(!,!); i0(ae,getSource() == button[13]) { --divide 0unction[3] temporar5[/] = Double,parseDouble(displa5,get7e8t()); 0unction[3] = true; displa5,set7e8t(!!); i0(ae,getSource() == button[1']) clear(); i0(ae,getSource() == button[1(]) getSJrt(); i0(ae,getSource() == button[1)]) get3osIeg(); i0(ae,getSource() == button[1"]) get>esult(); i0(ae,getSource() == button[1$]) displa5,append(!/!);

To find the source of the button that was pressed we use Bction9vent.get'ource ! ?? button because we called Bction9vent ae we can just use ae.get'ource ! instead. 'o our buttonK@L is P. with +TextBrea we use append string! to add text in. 'o if our button source is buttonK@L which is our P button! display.append 6P6!3 This gets done with all the buttons that produce text in the display. =ow moving on to our function buttons multiply, divide, add, subtract!. for the source of that button being pressed we need to set our first temporary number from the string on the display. i.e. temporaryK@L ? 0ouble.parse0ouble display.getText !!3 now for the function we are doing we need to set that function to true. since buttonK-L is our add function we set functionK@L eAual

to true, as functionK@L is our adding. now we have to reset the text in the display to get our value for our second temporary before eAuals is hit, with a simple display.setText 66!3 'o now do this with the other buttons that have functions, remembering that functionK@L is adding, functionK"L is subtracting, functionK*L is multiplying, and functionK-L is dividing!. =ow simply enough we just need to use those methods we created for those buttons. The clear button will have clear !3 called, the plus minus button will have get5os=eg !3 called, the sAuare root button will have get'Art !3 called, and the eAuals button will have getFesult !3 called. Hour final source code should look similar to thisM
//1 import Hava,awt,+; //2 import Hava8,swing,+; //3 import Hava,awt,event,+; //' //( public class Calculator e8tends 29rame implements :ction4istener { //) //" //$ //% /1/ /11 /12 /13 /1' /1( /1) /1" /1$ /1% /2/ /21 /22 /23 /2' /2( /2) /2" /2$ /2% Calculator() { super(!Calculator!); setDesign(); setSiCe(3$/# 2(/); set>esiCable(0alse); 23anel[] row = new 23anel[(]; 26utton[] button = new 26utton[1%]; String[] buttonString = {!"!# !$!# !%!# !&!# !'!# !(!# !)!# !*!# !1!# !2!# !3!# !+!# !,!# !-!# !C!# !.!# !&-*!# !=!# !/! ; int[] dimM = {3//#'(#1//#%/ ; int[] dimA = {3(# '/ ; Dimension Dimension Dimension Dimension displa5Dimension regularDimension rColumnDimension Cero6utDimension = = = = new new new new Dimension(dimM[/]# Dimension(dimM[1]# Dimension(dimM[2]# Dimension(dimM[3]# dimA[/]); dimA[1]); dimA[1]); dimA[1]);

boolean[] 0unction = new boolean[']; double[] temporar5 = {/# / ; 27e8t:rea displa5 = new 27e8t:rea(1#2/); 9ont 0ont = new 9ont(!7imes new >oman!# 9ont,6=4D# 1');

/3/ /31 /32 /33 /3' /3( /3) /3" /3$ /3% /'/ /'1 /'2 /'3 /'' /'( /') /'" /'$ /'% /(/ /(1 /(2 /(3 /(' /(( /() /(" /($ /(% /)/ /)1 /)2 /)3 /)' /)( );

setDe0aultClose=peration(<N?7B=IBC4=S<); @rid4a5out grid = new @rid4a5out((#(); set4a5out(grid);

0or(int i = /; i 1 '; i&&) 0unction[i] = 0alse;

9low4a5out 01 = new 9low4a5out(9low4a5out,C<I7<>); 9low4a5out 02 = new 9low4a5out(9low4a5out,C<I7<>#1#1); 0or(int i = /; i 1 (; i&&) row[i] = new 23anel(); row[/],set4a5out(01); 0or(int i = 1; i 1 (; i&&) row[i],set4a5out(02);

0or(int i = /; i 1 1%; i&&) { button[i] = new 26utton(); button[i],set7e8t(buttonString[i]); button[i],set9ont(0ont); button[i],add:ction4istener(t;is);

displa5,set9ont(0ont); displa5,set<ditable(0alse); displa5,setComponent=rientation(Component=rientation,>?@A7B7=B4<97 displa5,set3re0erredSiCe(displa5Dimension); 0or(int i = /; i 1 1'; i&&) button[i],set3re0erredSiCe(regularDimension); 0or(int i = 1'; i 1 1$; i&&) button[i],set3re0erredSiCe(rColumnDimension); button[1$],set3re0erredSiCe(Cero6utDimension);

row[/],add(displa5); add(row[/]);

0or(int i = /; i 1 '; i&&)

/)) /)" /)$ /)% /"/ /"1 /"2 /"3 /"' /"( /") /"" /"$ /"% /$/ /$1 /$2 /$3 /$' /$( /$) /$" /$$ /$% /%/ /%1 /%2 /%3 /%' /%( /%) /%" /%$ /%% 1// 1/1

row[1],add(button[i]); row[1],add(button[1']); add(row[1]);

0or(int i = '; i 1 $; i&&) row[2],add(button[i]); row[2],add(button[1(]); add(row[2]); 0or(int i = $; i 1 12; i&&) row[3],add(button[i]); row[3],add(button[1)]); add(row[3]);

row['],add(button[1$]); 0or(int i = 12; i 1 1'; i&&) row['],add(button[i]); row['],add(button[1"]); add(row[']);

setOisible(true);

public void clear() { tr5 { displa5,set7e8t(!!); 0or(int i = /; i 1 '; i&&) 0unction[i] = 0alse; 0or(int i = /; i 1 2; i&&) temporar5[i] = /; catc;(Iull3ointer<8ception e) {

public void getSJrt() { tr5 {

double value = Fat;,sJrt(Double,parseDouble(displa5,get7e8t())); 1/3 displa5,set7e8t(Double,toString(value)); 1/2 1/' 1/( 1/) 1/" 1/$ 1/% 11/ 111 112 113 11' 11( 11) 11" 11$ 11% 12/ 121 122 123 12' 12( 12) 12" 12$ 12% 13/ 131 132 133 13' 13( 13) catc;(:rra5?nde8=ut=06ounds<8ception e) { i0(temp1,contains(!*!)) { String[] temp11 = temp1,split(!*!# 2); temporar5[1] = (Double,parseDouble(temp11[1]) + *1); public void get>esult() { double result = /; temporar5[1] = Double,parseDouble(displa5,get7e8t()); String temp/ = Double,toString(temporar5[/]); String temp1 = Double,toString(temporar5[1]); tr5 { i0(temp/,contains(!*!)) { String[] temp// = temp/,split(!*!# 2); temporar5[/] = (Double,parseDouble(temp//[1]) + *1); catc;(Iumber9ormat<8ception e) { else { public void get3osIeg() { tr5 { double value = Double,parseDouble(displa5,get7e8t()); i0(value L= /) { value = value + (*1); displa5,set7e8t(Double,toString(value)); catc;(Iumber9ormat<8ception e) {

13" 13$ 13% 1'/ 1'1 1'2 1'3 1'' 1'( 1') 1'" 1'$ 1'% 1(/ 1(1 1(2 1(3 1(' 1(( 1() 1(" 1($ 1(% 1)/ 1)1 1)2 1)3 1)' 1)( 1)) 1)" 1)$ 1)% 1"/ 1"1 1"2

tr5 { i0(0unction[2] == true) result = temporar5[/] + temporar5[1]; else i0(0unction[3] == true) result = temporar5[/] - temporar5[1]; else i0(0unction[/] == true) result = temporar5[/] & temporar5[1]; else i0(0unction[1] == true) result = temporar5[/] * temporar5[1]; displa5,set7e8t(Double,toString(result)); 0or(int i = /; i 1 '; i&&) 0unction[i] = 0alse; catc;(Iumber9ormat<8ception e) {

public 0inal void setDesign() { tr5 { E?Fanager,set4ooG:nd9eel( !com,sun,Hava,swing,pla0,nimbus,Iimbus4ooG:nd9eel!); catc;(<8ception e) {

P=verride public void action3er0ormed(:ction<vent ae) { i0(ae,getSource() == button[/]) displa5,append(!"!); i0(ae,getSource() == button[1]) displa5,append(!$!); i0(ae,getSource() == button[2]) displa5,append(!%!); i0(ae,getSource() == button[3]) { --add 0unction[/] temporar5[/] = Double,parseDouble(displa5,get7e8t()); 0unction[/] = true;

1"3 1"' 1"( 1") 1"" 1"$ 1"% 1$/ 1$1 1$2 1$3 1$' 1$( 1$) 1$" 1$$ 1$% 1%/ 1%1 1%2 1%3 1%' 1%( 1%) 1%" 1%$ 1%% 2// 2/1 2/2 2/3 2/' 2/( 2/) 2/" 2/$

displa5,set7e8t(!!); i0(ae,getSource() == button[']) displa5,append(!'!); i0(ae,getSource() == button[(]) displa5,append(!(!); i0(ae,getSource() == button[)]) displa5,append(!)!); i0(ae,getSource() == button["]) { --subtract 0unction[1] temporar5[/] = Double,parseDouble(displa5,get7e8t()); 0unction[1] = true; displa5,set7e8t(!!); i0(ae,getSource() == button[$]) displa5,append(!1!); i0(ae,getSource() == button[%]) displa5,append(!2!); i0(ae,getSource() == button[1/]) displa5,append(!3!); i0(ae,getSource() == button[11]) { --multipl5 0unction[2] temporar5[/] = Double,parseDouble(displa5,get7e8t()); 0unction[2] = true; displa5,set7e8t(!!); i0(ae,getSource() == button[12]) displa5,append(!,!); i0(ae,getSource() == button[13]) { --divide 0unction[3] temporar5[/] = Double,parseDouble(displa5,get7e8t()); 0unction[3] = true; displa5,set7e8t(!!); i0(ae,getSource() == button[1']) clear();

2/% 21/ 211 212 213 21' 21( 21) 21" 21$ 21% 22/ 221 222

i0(ae,getSource() == button[1(]) getSJrt(); i0(ae,getSource() == button[1)]) get3osIeg(); i0(ae,getSource() == button[1"]) get>esult(); i0(ae,getSource() == button[1$]) displa5,append(!/!);

public static void main(String[] arguments) { Calculator c = new Calculator();

Hou should now have a fully working calculator, that should look like this

S-ar putea să vă placă și