You are on page 1of 27

Java GUI Programming

BuildingtheGUIforthe
MicrosoftWindowsCalculator
Lecture2

DesTraynor2005

So, what are we up to

Today,wearegoingtocreatetheGUIforthecalculatoryouall
knowandlove.
Itwillbasicallybeacrashcourseinputtingtogethersimple
interfacesusingSwing.
Youwilllearn...

MakingandplacingGUIcomponents

CreatingGUIsusingJPaneltobreakdownthedesign

DecoratingGUIComponents,viaFonts,Colors(sic)and
Insets

UsingLayoutManagers

JMenuBar,andJMenu

The Calculator

The Calculator, broken into 3


JPanels

So What?

Well,wehavenowgonefrom1large
problem,tothreesmallones.
WewilldoourbesttocreateeachJPanel,
oneatatime.
So,startingwiththesimplest,theJpanel
containingthesingleJTextField.

textPanel.java
classtextPanelextendsJPanel
{
JTextFieldoutput;
textPanel()
{
//setsize,initialtext,fontandtextalignment
output=newJTextField("0.",28);
output.setFont(newFont("Courier",Font.PLAIN,16));
output.setHorizontalAlignment(4);
//addtopanel
this.add(output);
//changebackgroundcolortobethatgraycolor
Colorbackground_color=newColor(241,237,222);
this.setBackground(background_color);
}
//mainremoved.
}

So lets have a look at that

(gototexteditor,showmainetc)
Thereweresomenewmethodsthere,thatyouwouldn't
haveseenbefore.Youdonotneedtolearntheseoffby
heart,theyareallavailableathttp://java.sun.com
Youcanlookupthissiteallthetimeduringlabs,but
notduringyourlabexam,oryourfinalexam.Iwill
providethesignaturesofanyofthenecessarymethods
intheseoccasions(Ithink).

Happy Enough with textPanel?


Great, next is the first row of buttons

Thesebadboys...

So,whatwehavehereis4buttons,3withredtext,
and2ofthemareheavilypadded
Normallybuttonsshrink/expandtofittheirlabel.CE
andCaren'tdoingthat.
Thefirstyoke,isactuallyadisabledbutton(I
workedthatoutafterawhile)

buttonPanel1.java
/*ThecodeforthewholePanelwon'tfitina
slide,soI'llexplainoneJbuttonandhopefullyyou
geniicanworkouttherest
*/
JbuttonCE;
//ThisisRGBcalueofthewindowsbuttoncolor
Colorbackground_color=newColor(241,237,222);
/*Thestringpassedintoconstructoristhelabelthat
appearsontheJbutton*/
CE=newJbutton("CE");
//Thisbitsetsthebuttontexttobered.
CE.setForeground(Color.red);
//Thissetsthebackgroundcolortobethecolorabove
CE.setBackground(buttons_color);
/*Thissetstheborders,we'llbetalkingaboutthisin
asecond*/
CE.setMargin(newInsets(6,29,6,29));
//ThenaddittobuttonPanel1
add(CE);

Insets ?
Insetsistheamountofspacebetweenthecomponent,and
itsborder.

Forabuttonitslike

Youcreatethemlikeso

Insets(inttop,intleft,intbottom,intright)

Alldistancesareinpixels.

So lets have a look at buttonPanel1.java

(gototexteditorandexplain)
(thisisthebitwhereyourealisethat
attendinglectureswasprobablyagoodidea)

2 down, one to go.

Nowfortheslightchallenge,the24buttons
Somebuttonsareblue,somearen't,lotofcopyingand
pastingtospecifythis.

Basicallyeverybuttonhasthefollowingthings...
InsetsbuttonMargin=newInsets(5,1,5,1);
MC=newJbutton("MC");//name
MC.setBackground(buttons_color);//colorfg
MC.setForeground(Color.red);//colorbg
MC.setMargin(buttonMargin); //margins

The GridLayout we are using

setLayout(newGridLayout(4,6,5,5));

GridLayoutplacescomponentsasyouaddthem,startingtop
right,endingbottomleft.Youcannotdirectlyplacea
componentinaspecificplaceeasily.

The4and6relatethetothe4x6layout,the5and5relateto
thehorizontalandverticalgapbetweencomponents(in
pixels.)

Again,letstakealookatthecodeitself.
(buttonPanel2.java)

Putting it all together

Well,wehavebuiltthe3subcomponents,so
wenowneedtobuildtheFramethat
containsthethreeofthem,inthecorrect
fashion.
WewillalsoaddaJMenubartocomplete
thelookoftheprogram.

CalcFrame.java (the class members)


classCalcFrameextendsJFrame
{
/*Theseareourthreepanelsthatwealreadywrote*/
textPaneltp;
buttonPanel1bp1;
buttonPanel2bp2;

/**Thisisthemenustuff**/
JMenuBarjmb;
JMenujmi1,jmi2,jmi3;

ClassFrame.java (the constructor)


CalcFrame()
{
super("Calculator");//settitletoCalculator
Containercp=getContentPane();//wesawthisalready
cp.setLayout(newFlowLayout());//wehavetouseflow
cp.setBackground(newColor(241,237,222));
tp=newtextPanel();//createourthreecomponents
bp1=newbuttonPanel1();
bp2=newbuttonPanel2();
cp.add(tp);
cp.add(bp1);//andaddthem
cp.add(bp2);//inorder
....//notfinished

CalcFrame.java (the menu)

TheJMenuBaristhetoplevelline.Itis
initiallyempty.
AJMenuisasinglemenu(e.gFile,orEdit)
AJMenuItemisaniteminsideaJMenu,(e.g
Open,Cut)
Togetasubmenu,simplyaddaJMenutoa
JMenu.

JMenus and their associates

OneJMenuBar
5JMenus

7JMenuItems

So lets have a look at our Menu

GotoTextEditor

Explainstuff.

The final bits of code


this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(340,320);//Iworkedoutthesizeafterward
setVisible(true);
setResizable(false);//Thispreventsitgettingmessedup

TomaketheactualCalcFrameappear...

public static void main(String args[])


{
CalcFrame cf = new CalcFrame();
}

So, how did we do?

MicrosoftWindowsCalculator
Version5.1

TheCS211Calculator

Good enough

It'sclose.Certainlynotperfect.
WecouldhavesettheLookAndFeeltobeMS
Windows,thatwouldgetthebuttonsspoton.(Ifwe
havetime,I'llelaborate)
Itsoffafewpixelshereandthere,butnothingmajor.If
wespentlongerit'dbeawasteoftime.
So,youcannowbuilduncomplicatedGUIs.Cantyou?

What do you mean Look and


Feel

Javahas3looks,(bylooksImeanhowthe
componentslook).Windows,Motif,and
Metal.
Thesearegood/bad.Ifyouusethem,you
endupwithafewdifficultieswhenyougo
crossplatform.
Butseeingasitsonly2linesofcodeI'llgive
youallalook.

Altering Look and Feel


// First an import statement
import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
/* And then , in your Frame class ( whatever your base
container is (calcFrame.java in this case) */
try
{
// This line sets the look and feel
UIManager.setLookAndFeel
("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch(Exception cnfe) // you have to catch the exceptions
{
System.out.println("Error changing look and feel");
}
// This line tells the application to update itself
SwingUtilities.updateComponentTreeUI(getContentPane());
//andthatsit!

Lets look at the results!

Ifitwasn'tforthelittlejavaicon,you'dbestruggling!
Thereyouhaveita(near)perfectclone.

End of Lecture

So,whatdidwelearn?

Howtobreakauserinterfaceintosubcomponents,
makingiteasiertocreate

Howtodecoratebuttonsandtextfieldssotheylook
appropriate

HowtouseInsetstochangethepaddingoncomponents

HowJMenuBarswork

GridLayoutandFlowLayout

HowtoaltertheLookandFeelofanGUI

Your Lab this week...

Needstobedecidedupon.

You might also like