New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Kathleen Cartwright


Kathleen Cartwright
GPA 3.73


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course

Popular in Computer Information Technology

This 6 page Class Notes was uploaded by Kathleen Cartwright on Monday September 28, 2015. The Class Notes belongs to CIS110 at University of Pennsylvania taught by Staff in Fall. Since its upload, it has received 24 views. For similar materials see /class/215380/cis110-university-of-pennsylvania in Computer Information Technology at University of Pennsylvania.

Similar to CIS110 at Penn

Popular in Computer Information Technology




Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/28/15
GUI building with Swing By David Mastuszek Edited by Diana Palsetia if How to build a GUI Create awindow in which to display thingsiusually aJFrome for an application or aJApplet for webbrowser Use the sedoyoutiLoyoutMonoger manager methodto specify a layout manager Create some Components such as buttons panels etc Add your components to your display area according to your chosen layout manager Wn39te some Listeners and attach them to your Components Interacting with a Component causes an Eventto occur AListenergets a message when an interesting event occurs and executes e code to deal with it Display your window 6232009 Im on tha rrlercessary packages The GUI components are in javaxswing so you always need to import that for a Swing application I Swing is built on top of AWT Abstract Window Toolkit and uses a number of AWT packages including most of the layout managers so you need to impon java awtf l Most listeners also come from the AWT so you also need to impon javaawt event Make a container For an application your drawing window is typically a JFrome JFrarne i a Container object Container i like a drawing meet that hold the component JFrarne frame new JFrarne JFrarne frame new JFrarne Tegtltt to put in title bar However the frame is not displayed until it is made visible frameetViibietrue You can create a JFrome in your main class It s o en more convenient to have your main class Extend rome ciarr rnyCla extend JFrarne i Add a la out manager The most important layout managers are BorderLayout pmmdes ve areas mtu whmh W can put cumpunents Thts is the defaultlayuutmanager fur hdth JFrame and JApplet FlowLayout Cumpunents are added le tu ngnt tup tn hdttdm Gndtayont Cumpunents are put tn arectangular 31d All areasarethesamesxzezndsthe Creates a hunzuntal ruW m a nemest stack Thts canbealxttlewardtu use GrvdBagLayout Tun cumplexandadzngertuyuurszmty SprmgLayo New very dexthtelsydutmsnsga Add com onents to containers l The usual command 1s container add component For FlowLayout GridLoyout and BoxLoyout this adds the component to the next awjlahle location For BorderLoyout this puts the component in the CENTER by default For Bo rderLayout it s usually better to use container addcnmpnnent Bo rderLayoutpusitian paxm39nn is one ofNORTH SOUTH EAST WEST or CENTER 6232009 Create com onents JButton button new JButtonC Clvck rnel JLabel label new JLabel Thv V a label JTeXtheld textheldt new JTeXtheld Thv V the tntttal text JTeXtheld teXthele new JTeXtheldC lnmal ted column J extAre t ea new JTeXtArea lmUal text new JTextArearovt column new JTeXLArea lmUal ted row column ogtlt Label for checkbox JRadvoButton radvoButtont new JRadvoButton Label for button ButtonGroup group new ButtonGroup groupaddradvoButtont groupaddradvoButtonZ Etc 2 Y v o X l m 9 2 Y 07 Thts xsjust a samphng ofthe avatlable constructors see the javaxvmngAPl or all the rest BorderLaygut d Event amp Listeners I Interacting with a GUI component such as a button causes an event to occur I An Event is an object in Java I You create Listeners for interesting events I Listener is an interface you create a Listener by implementing that interface I The Listener method gets the Event as a parameter d Create and attach listeners I IButton okButton new IButtonquotOKquot I okButtonaddActionListenernew MyOkListener I class MyOkListenerimplements ActionListener public void actionPerformedActionEvent event code to handle okButton click I Or have your main class implement ActionListener at same time it extends J Frame I prefer this one I Then all you have to is say okButtonaddAction Listenerthis d actionPerformed method I If there are multiple buttons then we want to know which button was presse I event getSource return reference heap address to the object component that was pressed I ifeventgetSource button1 do something else if eventgetSource button2 do something different d Suggested program arrangement 1 class Some ass implements ActionListener Declare components as instance variables JFrame frame an also define them here if you prefer JBunion button 1 Define components and attach listeners in a method void createGui frame new JFrame button new J5uttonquotoiltquot frameaddbutton usesdefault BorderLayout buttonaddActionListenerlthis public void actionPerformedActionEvent event ode to handle button click goes here llTo make it application program public static void main5tring args new SomelasscreaheGui 6232009 Suggested program arrangement 2 class umeClass extendsJFrame implementsAetvuntvstene Declare cum unents as Instance varvables JFrame amEY Don t need thvs JButtun butterY Denne components and attach listeners m a method vmd createGuv name new JFrame Don t need ms button new JEuttunp w addmuuen Was rame addmuuen button addAelyentyslenerums Llse an mnerelassas uurlvstener ublve vmd aetvunPer unned AetvunEvent event Code in handle button elvek gees here publv slane vmd mamtrmg argn new umeClassU createGuvU lg S uitt1ng th Program I setDefaultCloseOpemtionJFrameEXIT70N7CLOSE I Other options are DONOTHNGONCLOSE HIDE70N7CLOSE and DISPOSE70N7CLOSE 4 Enabl ng and disabling components I It is poor style to remove components you don t Want the user to be able to use Where did it go It ms here aminute ago I It s better to enable and disable controls Disabled controls appear grayed out The user may still wonder why but that s still less confusing I arg lepanmtsetEnabledenalzlcd I Parameter should be true to enable fake to disable a More Layouts GTidLayout I public class GridLayoutExample extends JFrame public void creatGui setLayoutmew GridLayoutZ 4 addnew JButtonquotOnequot ddd addnew JButton39Threequot39 addnew JButton 39Fourquot addnew JButtonquotFivequot n l 6232009 More La outs Nested layouts A JPanel is both a Container and a Component Because it s a container you can put other components into it Because it s a component you can put it into other containers I All but the very simplest GUIs are built by creating several JPanels arranging them and putting components possibly other JPanels into them I A good approach is to draw on paper the arrangement you want then nding an arrangement of JPanels and their layout managers that accomplishes this More La outs An example nested layout Container container new JFrmeo JPanel p1 new JPanel p1 setLayoutnew BorderLayout p1addnew JButtonquotAquot BorderLayoutNORTH also add buttons B C D E JPanel p2 new JPanel pZsetLayoutnew GridLayout3 2 pZaddnew JButtonquotFquot also add buttons 6 H I J K JPanel p3 new JPanel p3setLayoutnew BoXLayoutp3 BoxLayoutY p3addnew JButtonquotLquot also add buttons M N 0 P containersetLayoutnew BorderLayout containeraddp1 BorderLayoutCENTER containeraddp2 BorderLayoutSOUTH containeradd p3 BorderLayoutEAST Com onents use various listeners JButton JMenultem JCom boBox JTeXtField addActionListenerActionListener public void actionPerformedActionEvent event JCheckBox JRadioButton addltemListenerItemListener ic void itemStateChangedItemEvent event JSlider addChangeListenerChangeListener ic void stateChangedChangeEvent event JTeXtArea getDocumentaddDocumentListenerDocumentListener ublic void insertUpdateDocumentEvent event public void removeUpdateDocumentEvent event public void changedUpdateDocumentEvent event Gettin values Some user actions normally cause the program to do something clicking a button or selecting from a menu Some user actions set values to be used later entering text setting a checkbox or a radio button You can listen for events from these but it s not usually a good idea Instead read their values when you need them String myTegtltt myJTeXtFieldgetTegtltt String myTegtltt myJTeXtAreagetTegtltt boolean checked myJCheckBoxisSelected boolean selected1 myJRadioButton1isSelected 6232009 6232009 d Joption Pane I A Dialog window is an independent subwindow meant to carry temporary notice apart from the main Swing Application Window I Most Dialogs present an error message or warning to a user but Dialogs can present images I For convenience several Swing component classes can directly instantiate and display dialogs To create simple standard dialogs you use the JOptionPane class


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Anthony Lee UC Santa Barbara

"I bought an awesome study guide, which helped me get an A in my Math 34B class this quarter!"

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.