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

Final Exam Study Guide!

by: Taylor Kahl

Final Exam Study Guide! CSC 2310

Taylor Kahl
GPA 4.21

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

Everything from CSC 2310 you need to know for the final.
Princliples of Computer Programming
Kebina Manandhar
Study Guide
50 ?




Popular in Princliples of Computer Programming

Popular in ComputerScienence

This 22 page Study Guide was uploaded by Taylor Kahl on Saturday April 23, 2016. The Study Guide belongs to CSC 2310 at Georgia State University taught by Kebina Manandhar in Winter 2016. Since its upload, it has received 95 views. For similar materials see Princliples of Computer Programming in ComputerScienence at Georgia State University.

Similar to CSC 2310 at GSU

Popular in ComputerScienence


Reviews for Final Exam Study Guide!


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: 04/23/16
Final Exam Review!!! Classes:  Class – a program or template for creating new types of objects  Object – a programming entity, defined by a class, with its own state & behavior  Fields – object state. Variables that are stored within an object o declaring a field within a class assigns a copy of that field to every object of that type o accessing an object’s field: objectName.fieldName  Instance methods – object behavior. Methods stored within in object o if a method is called on an object, the object is passed as the implicit parameter o methods declared within a class are also copied to every object of that type o calling a method on an object: objectName.methodName()  this keyword – refers to the implicit parameter’s fields or methods. Useful if 2 variables have the same name o 2 variables can only have the same name if one of them is a field  Constructor – a special method that initializes the state of new objects as they are created o has the same name as its class & no return type o a class can have multiple constructors if they take different parameters  Client – code that interacts w/ a class or its objects. (Where you write the main method) o classes that you write are not complete programs; they have to be run by client code  Example: creating and using a new Point class (objects with x & y-coordinates (x,y)): Point class Client code Public class Point { public class PointClient { private int x; //field public static void main(String[ ] private int y; //field args) { public Point(int x, int y) { //constructor Point p1 = new Point(2, 5); this.x = x; //this.x = the x field //creates a new Point, calls the this.y = y; constructor } // p1 = (2, 5) public void move(int dx, int dy) { x += dx; //adds dx to the x p1.move(3, -2); field //p1 is passed as the implicit y += dy; //adds dy to the y parameter field // p1 = (5, 3) } } } }  Encapsulation – protecting objects’ internal data from unwanted external modification o forces abstraction – separating external behavior from internal state o achieved by declaring objects to be private  private fields can only be accessed or changed from within their class o to allow outside classes access to fields, write getter/setter methods within the class o Examples for the x field: Getter Setter public int getX() { public void setX(int x) { return x; this.x = x; } } o outside classes can access or change x by calling these methods on Point objects  Examples: point1.getX(); point1.setX(5);  static keyword – part of a class, not part of an object o fields & methods can be static or non-static o static methods and fields are shared by all objects of a class rather than each object having its own copy – all objects within the class can access or modify a static field o Calling a static method from outside its class: ClassName.methodName();  toString method – returns a String representation of an object o every class has a default toString method, but writing a new one will replace the default o Example for the Point class: public String toString() { return “(“ + x + “, “ + y + “)”; //returns (x,y) } Ineritance:  Inheritance – provides an “is-a” relationship between 2 classes o Example: every CS major is a college student o allows code sharing btw a superclass & its subclass(es) so you don’t have to rewrite code  Superclass – parent class in an inheritance relationship  Subclass – child class in an inheritance relationship o subclasses “inherit” the fields and methods of a superclass  additional methods can be added to the subclass o each subclass may only inherit 1 superclass  but 1 superclass can be extended to many subclasses  Syntax for inheriting a superclass using the keyword “extends”: public class Subclass extends Superclass {  Overriding – writing a new version of a method to replace an inherited one o write the same method heading as the method you are overriding; replace the method body statements  super keyword – used by subclasses to refer to the superclass’s constructors or methods o lets the subclass call an overridden method: super.methodName()  Constructors of superclasses are not inherited o subclasses needs their own constructor which calls the superclass using super and the parameters passed to the superclass’s constructor o the super call must be the 1 statement in the subclass’s constructor  Example: the CSMajor class inheriting the CollegeStudent class: public class CollegeStudent { public class CSMajor extends private int creditHours; CollegeStudent { public CollegeStudent(creditHours) { private String concentration; this.creditHours = creditHours; //CSMajor inherits the creditHours } field and adds the concentration field public boolean canGraduate { public CSMajor(creditHours, if (creditHours >= 120) concentration) { return true; super(creditHours); else this.concentration = return false; concentration; } } public int getCreditHours() { //this constructor calls the return creditHours; superclass’s constructor 1 , then } defines concentration public String toString() { public String toString() { return creditHours + return this.getCreditHours() + canGraduate; canGraduate() + concentration; } } } //this toString method overrides the other one //creditHours is a private field from the superclass so we have to call the getter method }  Class diagrams/tables – a way to keep track of inherited & overridden methods o Example of an inheritance hierarchy btw 3 classes: public class A { public class B extends A {public class C extends B { public void method1() public void method2() public void method1() { { { System.out.println(“A 1”); System.out.println(“B 2”);System.out.println(“C 1”); } } } public void method2() } public String toString() { //B inherits method1 & { toString from A; overrides return “C”; System.out.println(“A 2”); method2 } } } public String toString() //C inherits method2 from { B; overrides method1 & return “A”; toString } }  A class table of the method output for classes A, B & C A B C method1 “A 1” “A 1” “C 1” method2 “A 2” “B 2” “B 2” toString “A” “A” “C” Interfaces:  Interface – supertype class that forms “is-a” relationships between classes without code sharing o a list of abstract methods – only have headers, no body statements o unlike classes, you cannot create objects of an interface type  Implementing an interface with the keyword “implements”: o public class Name implements InterfaceName { o one class can implement multiple interfaces  A class that implements an interface has to implement all of its methods by completing the body statements; this allows different classes to implement the methods differently  Example: Square and Circle classes implementing the Shape interface: public Interface Shape public class Circle implements public class Square implements { Shape { Shape { public double private double radius; private double length; getArea() { public double getArea() { public double getArea() { } return 2 * Math.PI * return length * length; } radius * radius; } } } }  Polymorphism – allows the same code to be used with different types of objects o code will behave differently depending on the object type  Objects of a superclass or interface type can store any subclass type o Example: CollegeStudent objects can be of type CollegeStudent or CSMajor  Shape objects can be of type Shape or Circle  Polymorphism allows flexible code – a method that accepts a superclass or interface parameter will accept an object of any of its subtypes  However, if a subclass object is defined as a superclass type, you can only call methods on the object that are defined in the superclass ArrayLists:  ArrayList – a list of objects of a specified type. More flexible than an array because you can add or remove elements  Syntax for creating a new ArrayList: ArrayList<type> name = new ArrayList<type>();  ArrayLists use zero-based indexing o the 1 element is at index 0. The last element is at index = size – 1  ArrayList methods: add(element) adds element to the end of the list add(index, element) adds element at the specified index get(index) returns the value at the specified index remove(index) removes the element at the specified index size() returns the # of elements in the list clear() removes all elements set(index, value) replaces the element at the given index with the new value  Calling an ArrayList method: listName.methodName(parameters);  an ArrayList can’t contain primitive data types; it must contain objects o make an ArrayList of primitive types by using wrapper classes o Example: ArrayList<Integer> numbers = new ArrayList<Integer>(); Primitive type Wrapper type int Integer double Double char Character boolean Boolean  Sorting ArrayLists: o use the method Collections.sort: Collections.sort(list); The Comparable Interface:  Sorting objects is possible by using the Comparable interface o to sort objects, a class has to implement this interface: public interface Comparable<E> { public int compareTo(E other) { }  Point class implementing Comparable: public class Point implements Comparable<Point> {  classes that implement Comparable have to define the compareTo method for how the objects should be compared o Calling compareTo: x.compareTo(y);  compareTo compares the implicit parameter (x) to the parameter “other” (y) o returns a negative # if x < y o returns 0 if x = y o returns a positive # if x > y  Numbers are comparable by size; Strings are comparable by alphabetical ordering  Most java classes, such as String, already have a compareTo method defined  you can only use Collections.sort() on an ArrayList of an object type that has a defined compareTo method Recursion:  Recursion – defining an operation in terms of itself o recursive methods call themselves  Recursive algorithms have 2 cases: o base case – most simple occurrence of a problem, directly answerable  usually for a number n = 1 or 0 o recursive case – not directly answerable  can apply to any number n. Solve by decreasing n until you get to the base case, then apply the solution to n + 1  The mechanics of recursion: o java has an internal call stack which keeps track of the sequence of methods that have been called - imagine that each method is a piece of paper st o when the 1 method is called, it’s placed down o the next method that’s called is placed on top of it, and the next on top of that o java will execute the most recently called method  when that method finishes, it goes to the next method below it  Recursive backtracking – an algorithm to use when multiple combinations of choices can be made. Example: finding all possible permutations of the letters in a String o solution space – the set of all possible decisions o General backtracking algorithm:  if there are no more choices to make, stop  else, make a single choice C from the set of choices  explore the remaining choices  Un-make choice C (backtrack) Searching algorithms:  Sequential search – examines every element in a list from the beginning until locating a target o returns the index at which the target is located o returns -1 if the target is not found  Binary search – locates a target element by repeatedly dividing the list in half o can only be used with lists that are already sorted o compares the target to the element at the middle index  if the middle < target, eliminates the smaller half  if the middle > target, eliminates the larger half  if the middle = target, stops searching o repeats until the target is found, returns the index of the target o if target isn’t found, returns –(insertionPoint + 1)  insertionPoint = index where the target would appear in the sorted list  Binary search is usually more efficient than sequential search Sorting algorithms:  Sorting lists requires that the elements are comparable  Bogo sort – repeatedly shuffles a list & checks if it’s sorted; if it’s not, shuffles again  Selection sort – searches for the smallest element, swaps it with the element at index 0 nd o then searches for the 2 smallest element, swaps it with the element at index 1 o and so on, until it’s sorted  Bubble sort – compares every adjacent pair, swapping elements if they are out of order o runs through the list again, swapping pairs until it’s sorted  Insertion sort – sort the beginning of the list; add unsorted elements to the sorted part o examines elements from the beginning until reaching an element that’s less than the one before it; swaps those two elements o then, compare the smaller of those two elements to every element that comes before it in the list, swapping with larger elements until it’s in its proper spot o go through the list again until it finds unordered elements & repeat  Merge sort – repeatedly divide the list in half, sort each half, combine sorted halves o implemented recursively o divide by half over and over until each half has 1 element o when combining halves, sort the elements, until all halves are combined Runtime efficiency:  Efficiency – a measure of the runtime of a piece of code  Calculating efficiency: o every single statement has the same runtime, 1 unit of time o a loop’s runtime = N * the number of statements in its body o a nested loop’s runtime = N * N * the number of statements in their bodies  Growth rate – change in runtime as the input data size (N) changes o use the highest order of N of the runtime to determine growth rate; ignore coefficients o Example: 3N + 2N + 2  N dominates the overall run time  this algorithm runs “on the order of” N 2  the algorithm is “Big-Oh” of N , written O(N )2  Complexity class – category of efficiency based on Big-Oh of N o algorithms with the lowest complexity class are most efficient Class Big-Oh If you double N, the growth rate constant O(1) doesn’t change logarithmic O(log2N) increases slightly linear O(N) doubles log-linear O(N log2N) slightly more than 2 doubles quadratic O(N ) quadruples cubic O(N ) multiplies by 8 exponential O(2 ) multiplies drastically – AVOID! Complexity classes of sorting & searching algorithms: Sequential search N Binary search log2N Bogo sort no upper limit – terribly inefficient 2 Selection sort N 2 Bubble sort N (but slower than selection sort) Insertion sort N (but faster than selection sort) Merge sort log N 2 Operating systems:  Operating system (OS) – software package that oversees the computer’s operation  History of operating systems: o batch processing – everyone submitted their program or job to a computer operator  OS would read & execute programs 1 at a time o interactive processing – allowed programs to communicate with users  requires real-time processing – quickly enough for the user to interact with it o time-sharing – multiple users could interact with the computer simultaneously  implemented with multiprogramming – time is divided into intervals, and execution of each job is restricted to 1 time interval  gives the illusion that multiple jobs are being executed simultaneously o multiprocessor machines – true multitasking. OS assigns different jobs to different processors & uses time-sharing within individual processors Types of software:  Application software – performs specific tasks for users  System software – provides infrastructure that application software needs to run o consists of utility software & the OS  Utility software – programs for the computer’s installations. Extends the capabilities of OS Components of the OS:  User Interface – communicates with the user o shell – text communication through the monitor & keyboard (older interface) o graphical user interface (GUI) – objects are represented by picture icons  window manager – allocates blocks of space on screen to applications  Kernel – internal part of OS; performs basic required functions o file manager – coordinates use of the computer’s mass storage  directory – a bundle of files that lets the user organize related files  directory path – a chain of directories within directories o device drivers – communicate with controllers & periphery devices o memory manager – coordinates the computer’s use of main memory  virtual memory – if a program requires more main memory than is available, memory manager uses paging to shuffle data btw a disc & main memory o scheduler – determines which activities will be considered for execution o dispatcher – controls the allocation of time to activities Getting the OS started:  Bootstrapping (booting) – runs whenever computer is turned on o boot loader program is permanently stored in ROM (read-only memory)  transfers the OS into main memory; OS takes over control Coordinating the computer’s activities:  process – executing a program; process state – status of an activity  The scheduler maintains a process table: o tracks current processes, adds new ones & removes completed ones  The dispatcher uses multiprogramming to execute scheduled processes o each process is allocated a time slice; when time runs out, an interrupt signal causes the CPU (central processing unit) to switch to a new process o then the dispatcher chooses the process with highest priority to be executed next Competition among processes:  Semaphore – a “flag” that a process is available or unavailable o the OS checks if processes are available & changes the flags when they are in use  Deadlock – multiple processes are blocked by waiting for resources that another one is using o necessary conditions for deadlock:  competition for non-shareable resources  resources are requested on a partial basis  once a resource has been allocated, it can’t be forcibly retrieved Security:  Attacks from the outside: o insecure passwords o sniffing software – records activities running on a computer and reports to an intruder  Protection: auditing software – record & analyze the computer’s activities  Attacks from within: o unruly processes (once an intruder has gained access)  Protection: o privileged instructions, only allowed when the CPU is in privileged mode Networking & the Internet:  Networks – linked computer systems  Network classifications by scope: o PAN – personal area network. Short range, a few meters o LAN – local area network. Single building or complex o MAN – metropolitan area network. Community o WAN – wide area network – different cities/countries  Network classifications by ownership: o open – free to use, in the public domain o closed or proprietary – owned/controlled by an individual or corporation  Network classifications by topology – how the machines are connected: o bus – all machines connected to a common communication line, the bus  machines communicate directly via the bus o star – one machine is the central point (called the access point or AP) that all others connect to  machines communicate indirectly via the AP  Protocols – rules governing activity within a network o CSMA/CD (Carrier Sense, Multiple Access with Collision Detection) protocols  used in bus networks (like Ethernet) for transmitting messages  if a machine has to transmit a message, it waits until the bus is silent  if another machine begins transmitting, they both pause and retry after a random time interval o hidden terminal problem – machines on a wireless star network can’t detect that their transmissions are colliding because the machines’ signals are blocked from each other o CSMA/CA (Carrier Sense, Multiple Access with Collision Avoidance) protocols  used in star networks like WiFi  when a machine detects that the communication channel is silent, it waits a brief period  if the channel is busy, the machine waits for a random time  after the wait period, the machine can claim a silent channel  if new machines try to transmit, they’ll be blocked o Solving the hidden terminal problem:  some WiFi networks require machines to send a request to the AP to transmit  Combining networks: o these devices connect networks that are the same type (or compatible): o repeater – passes all signals btw 2 connected buses o bridge – passes signals btw 2 buses, but checks the destination of messages and only sends messages across the connection if the final destination is on the other side  more efficient than a repeater o switch – a bridge w/ multiple connections; can connect more than 2 buses o compatible connections form a single large network that uses their original protocols  internet – a network of networks of incompatible types o the original networks remain independent o routers – special computers that connect the networks of an internet  Inter-process communication – how different processes being executed on a network or in a computer coordinate/communicate o client-server model – processes are considered clients or servers  clients make requests of other processes; server satisfies the requests  one server for many clients; clients initiate communication  server must execute continuously o peer-to-peer model (P2P) – processes provide and receive services to/from each other  processes only have to execute temporarily  Distributed systems – software systems with different parts on different computers: o cluster computing – many independent computers work together o grid computing – multiple computers working together, but more loosely coupled o cloud computing – shared computers can be used for client programs when needed  Examples: Amazon’s Elastic Compute Cloud; Google Drive  The Internet – a world-wide internet; combination of PANs, LANs, MANs, WANs o Internet Service Providers (ISPs) maintain the organization of networks:  tier-1 ISPs: high-speed, high-capacity international WANs  tier-2 ISPs: more regional, lower capabilities  tier-1 & tier-2 ISPs provide the Internet’s communication infrastructure  tier-3 or access ISPs – provide users access to the Internet  end system – devices users use to access ISPs (laptops, cell phones, etc)  access is delivered by hot spots, telephone lines, cable systems or fiber optics  Internet Addressing: o IP addresses – unique addresses given to each computer in the system  originally 32-bit patterns; currently converting to 128-bit addresses  written in dotted decimal notation  each byte (8 bits) is expressed as an integer and separated by periods  Example: 17.12.25 represents 00010001 00001100 00011001 o Mnemonic addressing – easier for people to remember: o based on the concept of a domain – a “region” of the Internet  each domain is assigned a unique domain name. Example:  top-level domains – the suffix in a domain name (edu, org, com)  When transmitting messages, machines translate the mnemonic address to its IP address o name servers – directories that translate the addresses o domain name system (DNS)– an Internet-wide directory made up of name servers o DNS lookup – using DNS to perform a translation  ICANN (Internet Corporation for Assigned Names and Numbers) o assigns IP addresses to ISPs, who then assign the addresses within their region o oversees domain registration and assigns domain names to registered domains  Email (electronic mail) – domain servers communicate to transmit messages o transmission is run via the SMTP (Simple Mail Transfer Protocol)  Later Internet Applications: o VoIP (Voice over Internet Protocol) – transmit audio data over the Internet o Internet multimedia streaming – transport audio and video in real-time  The World Wide Web – internet technology using hypertext – linked documents o a format for embedding hyperlinks to other documents  Software packages on the Internet are either browsers or webservers o browsers – on user’s computer. Obtain & present requested materials o webserver – on the computer containing the hypertext documents to be accessed. Provides access to documents requested by browsers o hypertext documents are transferred btw browsers & webservers using HTTP (Hypertext Transfer Protocol) o each hypertext document is given a unique URL (Uniform Resource Locator) address o Example URL:  http – protocol required to access the document  – mnemonic name of host holding the document  authors/Shakespeare – directory path, the location of the document  Julias_Ceaser.html – name of the document  HTML (Hypertext Markup Language) o hypertext documents are encoded as text files and contain tags – symbols that describe:  how the document should appear on a display screen  what multimedia should accompany the document  which items within it are linked to other document o HTML uses tags – browsers read the tags to learn how to present the text on screen  Client-side & server-side activities: o browsers act like clients, using a URL to request a copy of the page from its webserver o client-side activities are performed by a client (like a browser) o server-side activities are performed by a server (like a webserver)  Message transmission occurs through a hierarchy of 4 software layers: o application – where the message originates; provides the destination’s address o transport – accepts messages, ensures they’re properly formatted  divides long messages into packets, which are transported individually o network – decides how the packets should be routed through the Internet o link – receives & transmits packets to the next machine o at the final destination, the network layer recognizes that the packet has arrived o transport layer reconstructs the original message o message goes to the application layer  The TCP/IP Protocol Suite is used to implement the transmission hierarchy o Protocol for the transport layer:  TCP (Transmission Control Protocol) – more reliable (ensures the message was received)  UDP (User Datagram Protocol) – more efficient o Protocol for the network layer:  IP (Internet Protocol) implements forwarding & routing of packets  IPv4 (version 4) – uses 32-bit Internet addresses  IPv6 will use a 128-bit addressing system  Internet Security: o malware – malicious software:  virus – infects a computer by inserting itself into programs that are already on it  worm – infects computers & forwards copies of itself to others  Trojan horse – willingly imported, disguised as another program  spyware (or sniffing software) – collects info about the computer it’s on  phishing software – asks for personal info o DoS (Denial of Service) – overload computers with messages to disrupt all of the computers in the network o spam – attempt to overwhelm an individual with excessive amounts of email  Protection: o firewall – filters traffic passing through a network o spam filters – firewalls to block unwanted email o proxy server – a shield btw client & server communication o antivirus software – detects & removes known viruses  Encryption – encodes information so that it can’t be understood if intercepted o HTTP was updated to an encrypted version: HTTPS o public-key encryption:  a public key, used to encrypt messages, is given to anyone needing to send messages to a particular destination  the private key, used to decrypt messages, is kept secret at the destination o certificates establish that a public key is from a trusted source o certificate authorities – trusted Internet sites who maintain accurate lists of parties & their public keys. Provide certificates containing a party’s name & its public key o authentication – text is encrypted with a private key  this encryption pattern produces a digital signature which only the sender knows how to produce  the receiver uses the public key to decrypt the signature to verify that the sender is authentic Graphical user interfaces (GUI):  GUI – interact with a program using graphic elements: windows, buttons, menus, etc.  Objects needed to create a GUI in Java: o components – display information or interact with the user  container – a special component that holds/organizes other components o events – represent an occurrence  event-driven programs respond to events from the user o listener – waits for an event to occur & responds when it does  Requirements for a Java program that uses a GUI: o set up necessary components o implement listener classes; define what happens when events occur o add listeners to the components that generate the events they listen for  Java components and GUI-related classes are defined in 2 packages: o java.awt & javax.swing – newer; provides more versatile components Frames & Panels:  Frame – a container, displayed as a separate window with a title bar o defined by the JFrame class  Panel – a container that can’t be displayed on its own – organizes other components o defined by the JPanel class  Containers are either heavyweight or lightweight o heavyweight – managed by the operating system; more complex. Ex: frame o lightweight – managed by the Java program itself. Ex: panel  Frames have multiple panes which are responsible for characteristics of the frame window o a frame’s content pane displays all visible elements of a Java interface  GUI-based Java applications usually create a frame that contains a panel, which can be further organized into more panels  Label – a component that displays a line of text or an image; not interactive o from the JLabel class Interactive GUI Components:  Text field – allows user to enter typed input o getting a String value of the text in the text field: fieldName.getText();  Check box – a button that can be toggled on or off, which sets or unsets a boolean condition o multiple check boxes may be used together – they are independent o to find whether a checkbox is selected use this method:  checkboxName.isSelected()  Radio buttons – used together to create a set of mutually exclusive options (can only select one) o when another button is pushed, the one that was currently on is toggled off o to put radio buttons together in the same group, make a button group, then add each button to it:  ButtonGroup group = new ButtonGroup();  group.add(button1);  group.add(button2);  Sliders – allow user to specify a numeric value within a bounded range o can be horizontal or vertical  Combo box – allows the user to select one of several options from a drop- down menu o 2 ways to add options to the combo box:  create an list, then pass it to the JComboBox constructor  JComboBox combo1=new JComboBox(ArrayName);  or, use the addItem method to add items to a combo box that already exists  combo1.addItem(StringName); o combo boxes can contain text or ImgaeIcon objects as options  Timer – manages an activity over time o has no visual representation on screen o generates an action event at regular intervals  Tabbed pane – a container that allows users to choose which of several panes is currently visible by clicking on its tab o Adding a new tab to a tabbed pane:  pane.addTab(“Tab 1”, new JPanel); Component: From the class: Constructor: Event generated: push button JPushButton new action event JPushButton(“Text on the button”); text field JTextField new JTextField(int size action event of text field); check box JCheckBox new item event JCheckBox(“Check box label”); radio button JRadioButton new JRadioButton(“ action event radio button label”); slider JSlider new change event JSlider(JSlider.HORIZO NTAL or JSlider.VERTICAL, int min, int max, int initial); combo box JComboBox new JComboBox(); or action event new JComboBox(list of options); timer Timer new Timer(int delay, action event actionListener listener); tabbed pane JTabbedPane new JTabbedPane(); Listener classes:  listeners have to be added to components which generate events o the method within a listener class defines what happens when the event is generated  listener classes are usually defined as a private class within a panel class  listener classes have to implement listener interfaces: o ActionListener for action events  contains the method: public void actionPerformed(ActionEvent event) o ItemListener for item events  contains the method: public void itemStateChanged(ItemEvent event) o ChangeListener for change events  contains the method: public void stateChanged(ChangeEvent event) o listeners often have to identify the source of the event:  Object source=event.getSource(); Basic code for a GUI: import javax.swing.JFrame; import java.awt.*; import java.awt.event.*; public class GUI extends JFrame { import javax.swing.*; public static void main(String[] args) { JFrame frame = new JFrame("GUI"); public class GUIPanel extends JPanel { //the frame will be in a new window with the private JButton push; title “GUI” private int count; frame.setDefaultCloseOperation(JFrame.EXIT_O public PushCounterPanel() { N_CLOSE); count = 0; //sets the close button to exit the GUI when push = new JButton("Push Me!"); pushed push.addActionListener(new ButtonListener()); //the action listener listens to the button GUIPanel panel = new GUIPanel(); add(push); frame.getContentPane().add(panel); //adds the button to the panel //adds a panel to the content pane setBackground(; setPreferredSize(new Dimension(300,40)); frame.pack(); } //puts the components on the frame in a private class ButtonListener implements ActionListener reasonable size { frame.setVisible(true); //implements ActionListener and defines its method //makes the frame appear on the screen public void actionPerformed(ActionEvent event) { } count++; } } } } Fonts:  Font class – font objects are defined by name, style (plain, bold or italic) & size o Example setting the font of a label: label.setFont(“Helvetica, Font.PLAIN, 36); where Helvetica is the font name, the font style is plain, and the font size is 36 Layout Managers:  Layout manager – an object that manages every container & determines how the container’s components are arranged visually o adjusts the size & position of components when a container is resized or a component is added  Every container has a default layout manager but can be changed o Setting a new layout manager: containerName.setLayout(new LayoutType());  Flow layout – puts as many components as possible on a row from left to right at their preferred size; moves to the next row as needed o the default layout for JPanels  Border layout – has 5 areas where components can be added: North (top), South (bottom), East (right), West (left), Center o each area may only contain 1 component or container o the 4 outer areas are as large as needed to accommodate their components o if no component is added to one of the outer areas, that area does not appear o the center area expands to fill any available space o adding components to a box layout:  add(componentName, BorderLayout.AREA_NAME);  Grid layout – arranges components in a rectangular grid of equally sized cells o one component per cell o creating a new grid layout:  new GridLayout(# of rows, # of columns) o components are added from left to right, top to bottom o size of cells changes to match overall container’s size  Box layout – organizes components in 1 row or in 1 column o setting a box layout:  setLayout (new BoxLayout(this, BoxLayout.Y_AXIS)); //or X-AXIS o creating space between components:  rigid areas – a fixed area between components  add(Box.createRigidArea(new Dimension(xSize, ySize);  vertical glue – where excess space in the container should go  add(Box.createVerticalGlue()); //or HorizontalGlue  Containment hierarchies – the way components are grouped o usually 1 primary or top-level container, like a frame or applet  which usually contains other containers, like panels  panels may contain other panels to organize their components o each container can have its own distinct layout manager Mouse Events:  Mouse events – generated by pressing or releasing the mouse button: o mouse pressed – button is pushed down o mouse released – button is released o mouse clicked – button is pushed down & released in the same location o mouse entered – mouse pointer is moved onto a component o mouse exited – mouse pointer is moved off of a component o the listener for mouse events implements the MouseListener interface  which contains void methods for mousePressed, mouseReleased, mousePressed, mouseEntered & mouseExited  if you don’t need all of those methods, you can define them as empty methods  Example: public void mouseReleased(MouseEvent event) {}  Mouse motion events – generated by moving the mouse: o mouse moved – the mouse is moved o mouse dragged – mouse is moved while the mouse button is pressed down o the listener for mouse motion events should implement the MouseMotionListener interface, which contains void methods for mouseMoved & mouseDragged  Java coordinate system – origin is in the upper-left corner of a panel o x-coordinates increase to the right; y-coordinates increase downward


Buy Material

Are you sure you want to buy this material for

50 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."

Janice Dongeun University of Washington

"I used the money I made selling my notes & study guides to pay for spring break in Olympia, Washington...which was Sweet!"

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."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

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.