Object Oriented Programming Concepts-15CS45

Size: px
Start display at page:

Download "Object Oriented Programming Concepts-15CS45"

Transcription

1 Module 05 Chethan Raj C Assistant Professor Dept. of CSE APPLET: 1. Introduction 2. Two types of Applets 3. Applet basics 4. Applet Architecture 5. An Applet skeleton 6. Simple Applet display methods 7. Requesting repainting; 8. Using the Status Window 9. The HTML APPLET tag 10. Passing parameters to Applets 11. getdocumentbase() and getcodebase() 12. ApletContext and showdocument() 13. The AudioClip Interface; 14. The AppletStub Interface; 15. Output to the Console. SWINGS: 1. The origins of Swing 2. Two key Swing features 3. Components and Containers 4. The Swing Packages, A simple Swing Application 5. Create a Swing Applet 6. Jlabel and ImageIcon 7. JTextField 8. The Swing Buttons 9. JTabbedpane 10. JScrollPane 11. JList 12. JComboBox 13. JTable Chethan Raj C, Assistant Professor Dept. of CSE Page 1

2 The Applet Introduction Object Oriented Programming Concepts-15CS45 Applet is a small program that can be placed on a web page and it is executed by the web browser. Java Applets enable user interaction with GUI elements and provides the web pages dynamic content Applet is a Java program embedded within HTML pages. Java applets is compatible with almost all the web browsers like Mozilla Firefox, Google Chrome, Internet explorer, Netscape navigator and others that are java enabled. Applets make a website more dynamic and are secure. When browser loads Web page containing applet, Applet downloads into Web browser and begins execution or applets can be executed in appletviewer. Applets are not stand alone programs. Applets are specified in html document by using applet tag /* <applet code= MyApplet width=200 height=100> </applet> */ The applet will be executed in java enabled web browser when it encounters applet tag within the html file. Applet is designed to run remotely on the client browser. They cannot access system resources on local computer. They are often used for a small internet and intranet applications. Applet Basics: All applets are subclasses of Applet. Thus, all applets must import java.applet. Applets must also import java.awt. Since all applets run in a window, it is necessary to include support for that window i.e AWT stands for the Abstract Window Toolkit.Applets are not executed by the console-based Java run-time interpreter. Rather, they are executed by either a Web browser or an applet viewer. The appletviewer, provided by the SDK. But user can use any applet viewer or browser. Execution of an applet does not begin at main( ). Actually, few applets even have main( ) methods. Instead, execution of an applet is started and controlled with an entirely different mechanism, which will be explained shortly. Output to your applet s window is not performed by System.out.println( ). Rather, it is handled with various AWT methods, such as drawstring( ), which outputs a string to a specified X,Y location. Input is also handled differently than in an application. Once an applet has been compiled, it is included in an HTML file using the APPLET tag. The applet will be executed by a Java-enabled web browser when it encounters the APPLET tag within the HTML file. To view and test an applet more conveniently, simply include a comment at the head of your Java source code file that contains the APPLET tag. The user code is documented with the necessary HTML statements needed by your applet, and you can test the compiled applet by starting the applet viewer with your Java source code file specified as the target. Here is an example of such a comment: /* <applet code="myapplet" width=200 height=60> </applet> */ Chethan Raj C, Assistant Professor Dept. of CSE Page 2

3 This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high. Since the inclusion of an APPLET command makes testing applets easier, all of the applets shown in this book will contain the appropriate APPLET tag embedded in a comment. Applet class Applet class provides all necessary methods to start and stop the applet program. It also provides methods to load and display images, and play audio clips. Applet extends the AWT class Panel. Panel extends Container which extends Component User can perform event handling in AWT or Swing and also perform by using applet also. JApplet have all the controls of swing. The JApplet class extends the Applet class. Applet provides all necessary support for applet execution, such as starting and stopping. It also provides methods that load and display images, and methods that load and play audio clips. Applet extends the AWT class Panel. In turn, Panel extends Container, which extends Component. These classes provide support for Java s window-based, graphical interface. Thus, Applet provides all of the necessary support for window-based activities. Hierarchy of Applet As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass of Component. Chethan Raj C, Assistant Professor Dept. of CSE Page 3

4 An Applet has its own unique functionality getappletcontext() getparameter(string name) getcodebase(), getdocumentbase() showstatus(string msg) returns an object which allows some communication with browser & HTML page returns value of parameter with name (or null) return URLs of page, etc puts message in status window of browser Applet Program Running Steps: There are two ways to run an applet 1. By html file. 2. By appletviewer tool (for testing purpose). Example of applet program to run applet using html import java.applet.*; import java.awt.*; public class JavaApp extends Applet public void paint(graphics g) Font f=new Font("Arial",Font.BOLD,30); g.setfont(f); setforeground(color.red); setbackground(color.white); g.drawstring("student",200,200); Html code, myapplet.html <html> <title> AppletEx</Title> Chethan Raj C, Assistant Professor Dept. of CSE Page 4

5 <body> <applet code="javaapp.class" </applet> </body> </html> height="70%" width="80%"> If applet code not run on browser then allow blocked contents. Simple example of Applet by html file: To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet code in html file. Now click the html file. //First.java import java.applet.applet; import java.awt.graphics; public class First extends Applet public void paint(graphics g) g.drawstring("welcome",150,150); Note: class must be public because its object is created by Java Plugin software that resides on the browser. myapplet.html <html> <body> <applet code="first.class" width="300" height="300"> </applet> </body> Chethan Raj C, Assistant Professor Dept. of CSE Page 5

6 </html> Running of applet using appletviewer Some browser does not support <applet> tag so that Sun MicroSystem was introduced a special tool called appletviewer to run the applet program. In this example Java program should contain <applet> tag in the commented lines so that appletviewer tools can run the current applet program. Example of Applet import java.applet.*; import java.awt.*; /*<applet code="lifeapp.class" height="500",width="800"> </applet>*/ public class LifeApp extends Applet String s= " "; public void init() s=s+ " int "; public void start() s=s+ "start "; public void stop() s=s+ "stop "; public void destroy() Chethan Raj C, Assistant Professor Dept. of CSE Page 6

7 s=s+ " destory "; public void paint(graphics g) Font f=new Font("Arial",Font.BOLD,30); setbackgroundcolor(color."red"); g.setfont(f); g.drawstring(s,200,250); Execution of applet program javac LifeApp.java appletviewer LifeApp.java Note: init() always execute only once at the time of loading applet window and also it will be executed if the applet is restarted. Simple example of Applet by appletviewer tool: To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for testing purpose only. //First.java import java.applet.applet; import java.awt.graphics; public class First extends Applet public void paint(graphics g) g.drawstring("welcome to applet",150,150); Chethan Raj C, Assistant Professor Dept. of CSE Page 7

8 /* <applet code="first.class" width="300" height="300"> </applet> */ To execute the applet by appletviewer tool, write in command prompt: c:\>javac First.java c:\>appletviewer First.java Applet Architecture An applet is a window-based program. As such, its architecture is different from the console-based programs 1 Applets are event driven. 2 An applet waits until an event occurs. 3 The run-time system notifies the applet about an event by calling an event handler that has been provided by the applet. 4 Once this happens, the applet must take appropriate action and then quickly return. 5 Applet must perform specific actions in response to events and then return control to the runtime system. 6 In those situations in which your applet needs to perform a repetitive task on its own (for example, displaying a scrolling message across its window), an additional thread of execution must be started. Ex: The event-driven architecture impacts the design of an applet. An applet resembles a set of interrupt service routines. An applet waits until an event occurs. The AWT notifies the applet about an event by calling an event handler that has been provided by the applet. Once this happens, the Chethan Raj C, Assistant Professor Dept. of CSE Page 8

9 applet must take appropriate action and then quickly return control to the AWT. For the most part, user applet should not enter a mode of operation in which it maintains control for an extended period. Instead, it must perform specific actions in response to events and then return control to the AWT run-time system. In those situations in which user applet needs to perform a repetitive task on its own (for example, displaying a scrolling message across its window), user must start an additional thread of execution. The user interacts with the applet as he or she wants, when he or she wants. These interactions are sent to the applet as events to which the applet must respond. 1 when the user clicks the mouse inside the applet s window, a mouse-clicked event is generated. 2 If the user presses a key while the applet s window has input focus, a keypress event is generated. 3 Applets can contain various controls, such as push buttons and check boxes. When the user interacts with one of these controls, an event is generated. Ex:In nonwindowed program, when the program needs input, it will prompt the user and then call some input method, such as readline( ). This is not the way it works in an applet. Instead, the user interacts with the applet as he or she wants, when he or she wants. These interactions are sent to the applet as events to which the applet must respond. For example, when the user clicks a mouse inside the applet s window, a mouse-clicked event is generated. If the user presses a key while the applet s window has input focus, a keypress event is generated. (Refer Previous examples for events)the applets can contain various controls, such as push buttons and check boxes. When the user interacts with one of these controls, an event is generated. While the architecture of an applet is not as easy to understand as that of a console-based program, Java s AWT makes it as simple as possible. If you have written programs for Windows, you know how intimidating that environment can be. Fortunately, Java s AWT provides a much cleaner approach that is more quickly mastered. The java provides console based programming language environment and window based programming environment. An applet is a window based programming environment. So applet architecture is different than console base program. Java applets are essentially java window programs that can run within a web page.applete programs are java classes that extend that java.applet.applet class and are enabaled by reference with HTML page. You can observed that when applet are combined with HTML, thet can make an interface more dynamic and powerful than with HTML alone. While some Applet do not more than scroll text or play movements, but by incorporating theses basic features in webpage you can make them dynamic. These dynamic web page can be used in an enterprise application to view or manipulate data comming from some source on the server. The Applet and there class files are distribute through standard HTTP request and therefore can be sent across firewall with the web page data. Applete code is referenced automatically each time the user revisit the hosting website. Therefore keeps full application up to date on each client desktop on which it is running. Chethan Raj C, Assistant Professor Dept. of CSE Page 9

10 An Applet skeleton The applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods init( ), start( ), stop( ), and destroy( ) are defined by Applet. Another, paint( ), is defined by the AWT Component class. Default implementations for all of these methods are provided. Applets do not need to override those methods they do not use. However, only very simple applets will not need to define all of them. When an applet begins, the AWT calls the following methods, in this sequence: 1. init( ) 2. start( ) 3. paint( ) When an applet is terminated, the following sequence of method calls takes place: 1. stop( ) 2. destroy( ) // An Applet skeleton. import java.awt.*; import java.applet.*; /* <applet code="appletskel" width=300 height=100> </applet> */ public class AppletSkel extends Applet // Called first. Chethan Raj C, Assistant Professor Dept. of CSE Page 10

11 public void init() // initialization /* Called second, after init(). Also called whenever the applet is restarted. */ public void start() // start or resume execution // Called when the applet is stopped. public void stop() // suspends execution /* Called when applet is terminated. This is the last method executed. */ public void destroy() // perform shutdown activities // Called when an applet's window must be restored. public void paint(graphics g) // redisplay contents of window Chethan Raj C, Assistant Professor Dept. of CSE Page 11

12 All the above methods are explained in Applet Life cycle. Fig: Applet Life Cycle When Applet is created it under goes series of changes in its state. The applet state include. 1. Born or initialize state 2. Running state 3. Idle state 4. Dead or destroyed state Initialization state or init() The life cycle of an applet is begin on that time when the applet is first loaded into the browser and called the init() method. The init() method is called only one time in the life cycle on an applet. The init() method is basically called to read the PARAM tag in the html file. The init () method retrieve the passed parameter through the PARAM tag of html file using get Parameter() method All the initialization such as initialization of variables and the objects like image, sound file are loaded in the init () method.after the initialization of the init() method user can interact with the Applet and mostly applet contains the init() method. Applet enters the initialization state when it is first loaded. This is achieved by overriding init() method. public void init() Chethan Raj C, Assistant Professor Dept. of CSE Page 12

13 The init( ) method is the first method to be called. This is where you should initialize variables. This method is called only once during the run time of applet. With init() method following task may do. Running state or start() 1. Create objects needed by applet. 2. Set up initial values. 3. Load images or fonts. 4. set up colors. The start method of an applet is called after the initialization method init(). This method may be called multiples time when the Applet needs to be started or restarted. For Example if the user wants to return to the Applet, in this situation the start Method() of an Applet will be called by the web browser and the user will be back on the applet. In the start method user can interact within the applet. An applet enters in running state when system calls the start().this is achieved by overriding start() method. public void start() The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Whereasinit( ) is called once the first time an applet is loaded start( ) is called each time an applet s HTML document is displayed onscreen. So, if a user leaves a web page and comes back, the applet resumes execution atstart( ). Idle or Stopped state or stop() The stop() method can be called multiple times in the life cycle of applet like the start () method. Or should be called at least one time. There is only miner difference between the start() method and stop () method. For example the stop() method is called by the web browser on that time When the user leaves one applet to go another applet and the start() method is called on that time when the user wants to go back into the first program or Applet. Chethan Raj C, Assistant Professor Dept. of CSE Page 13

14 An applet become idle when it is stopped from running. This is achieved by overriding stop() method. public void stop() The stop( ) method is called when a web browser leaves the HTML document containing the applet when it goes to another page, for example. When stop( ) is called, the applet is probably running. stop( ) method is also used to suspend threads that don t need to run. when the applet is not visible. It can be restarted when start( ) is called if the user returns to the page. Dead state or destroy() The destroy() method is called only one time in the life cycle of Applet like init() method. This method is called only on that time when the browser needs to Shut down. An applet is said to be dead when it is removed from memory. This is achieved by overriding destroy() method. public void destroy() The destroy( ) method is called when the environment determines that applet needs to be removed completely from memory. this point, you should free up any resources the applet may be using. stop( ) method is always called before destroy( ). Like initialization, destroying stage occurs only once in the applet s life cycle. Display state or paint() Applet moves to the display state whenever it has to perform some output operations on the screen. This happen immediately after the applet enters into the running state. The paint method is called to accomplish this task. This is achieved by overriding destroy() method. The paint( ) method is called each time your applet s output must be redrawn. This situation can occur for several reasons. For example, the window in which the applet is running may be overwritten by another window and then uncovered. Or the applet window may be minimized and Chethan Raj C, Assistant Professor Dept. of CSE Page 14

15 then restored. paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required. public void paint(graphics g) Overriding update( ) AWT, defines a method called update( ). This method is called when applet has requested that a portion of its window be redrawn. update( ) method simply calls paint( ). Example import java.applet.*; import java.awt.*; // public void drawstring(string message,int x,int y) /* */ <applet code="appletlifecycle" width=300 height=300> </applet> public class AppletLifecycle extends Applet String str = ""; public void init() \ str += "init; "; public void start() Chethan Raj C, Assistant Professor Dept. of CSE Page 15

16 str += "start; "; public void stop() // stop public void destroy() //destroy public void paint(graphics g) str += "Paint; "; g.drawstring(str, 10, 25); Output: Save source file with name : AppletLifecycle.java Compile source file Open file in appletviewer : javac AppletLifecycle.java : appletviewer AppletLifecycle.java Chethan Raj C, Assistant Professor Dept. of CSE Page 16

17 Example: import java.awt.*; import java.applet.*; /* <applet code="appletskeleton" width=300 height=100> </applet> */ public class AppletSkeleton extends Applet String msg; public void init() setbackground(color.cyan); setforeground(color.red); Label l = new Label("Non Functioning Button"); add(l); Button b = new Button("Button"); add(b); public void start() Chethan Raj C, Assistant Professor Dept. of CSE Page 17

18 setbackground(color.magenta); setforeground(color.pink); msg = "Inside Start method"; System.out.println("Inside Start method"); repaint(); public void stop() msg = "Inside Stop method"; System.out.println("Inside stop method"); repaint(); public void destroy() msg = "Inside destroy method"; System.out.println("Applet Destroyed"); repaint(); public void paint(graphics g) g.drawstring(msg, 100, 150); Output: C:users/CRC>javac AppletSkeleton.java C:users/CRC>appletviewer AppletSkeleton.java Chethan Raj C, Assistant Professor Dept. of CSE Page 18

19 Advantage of Applet 1. Applets are supported by most web browsers. 2. Applets works on client side so less response time. 3. Secured: No access to the local machine and can only access the server it came from. 4. Easy to develop applet, just extends applet class. 5. To run applets, it requires the Java plug-in at client side. 6. Android, do not run Java applets. Drawback of Applet 1. Plugin is required at client browser to execute applet. 2. Some applets require a specific JRE. If it required new JRE then it take more time to download new JRE. Two types of Applets Applet is a Java program that can be transported over the internet and executed by a Java enabled web-browser(if browser is supporting the applets) or an applet can be executed using appletviewer utility provided with JDK. An applet is created using the Applet class, whch is a part of java.applet package. Applet class provides several useful methods to give you a full control over execution of an applet. There are two types of applet - 1. Applets based on the AWT(Abstract Window Toolkit) package by extending its Applet class. 2. Applets based on the Swing package by extending its JApplet class Note : At present, some modern versions of browsers like Google Chrome and Mozilla Firefox have stopped supporting applets, hence applets are not displayed or viewed with these browsers although some browsers like Internet Explorer and Safari are still supporting applets. Types of Applets based on location: Web pages can contain two types of applets which are named after the location at which they are stored. 1. Local Applet 2. Remote Applet Chethan Raj C, Assistant Professor Dept. of CSE Page 19

20 Local Applets: A local applet is the one that is stored on our own computer system. When the Webpage has to find a local applet, it doesn't need to retrieve information from the Internet. A local applet is specified by a path name and a file name as shown below in which the codebase attribute specifies a path name, whereas the code attribute specifies the name of the byte-code file that contains the applet's code. <applet codebase="myapppath" code="myapp.class" width=200 height=200> </applet> Remote Applets: A remote applet is the one that is located on a remote computer system. This computer system may be located in the building next door or it may be on the other side of the world. No matter where the remote applet is located, it's downloaded onto our computer via the Internet. The browser must be connected to the Internet at the time it needs to display the remote applet. To reference a remote applet in Web page, we must know the applet's URL (where it's located on the Web) and any attributes and parameters that we need to supply. A local applet is specified by a url and a file name as shown below. <applet codebase=" code="myapp.class" width=200 height=200> </applet> Applet basics Applet is a predefined class in java.applet package used to design distributed application. It is a client side technology. Applets are run on web browser. Application vs applets Applets are the small programs while applications are larger programs. Applets don't have the main method while in an application execution starts with the main method. Applets can run in our browser's window or in an appletviewer. To run the applet in an appletviewer will be an advantage for debugging. Applets are designed for the client site programming purpose while the applications don't have such type of criteria. Applet are the powerful tools because it covers half of the java language picture. Java applets are the best way of creating the programs in java. There are a less number of java programmers that have the hands on experience on java applications. This is not the deficiency of java applications but the global utilization of internet. It doesn't mean that the java applications don't have the place. Both (Applets and the java applications) have the same importance at their own places. Applications are also the platform independent as well as byte oriented just like the applets. Applets are designed just for handling the client site problems. while the java applications are designed to work with the client as well as server. Applications are designed to exists in a secure area. while the applets are typically used. Applications and applets have much of the similarity such as both have most of the same features and share the same resources. Applets are created by extending the java.applet.applet class while the java applications start execution from the main method. Applications are not too small to embed into a html page so that the user can view the application in your browser. On the other hand applet have Chethan Raj C, Assistant Professor Dept. of CSE Page 20

21 the accessibility criteria of the resources. The key feature is that while they have so many differences but both can perform the same purpose. Application are independent program (maybe fully compiled, though more likely byte-code compiled and then interpreted) Application have full access to host machine GUI normal file access (standard security constraints on file ownership) ability to create sockets (arbitrary network connections) (slightly restricted) access to environment variables create Frame object as principal window may have additional windows for dialogs, alerts etc. Simple Applet display methods The applets are displayed in a window and they use the AWT to perform input and output. Although user will examine the methods, procedures, and techniques necessary to fully handle the AWT windowed environment in subsequent chapters, a few are described here, because we will use them to write sample applets. Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java. Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavyweight i.e. its components are using the resources of OS. The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc. In order to output a string to an applet, use drawstring( ), which is a member of the Graphics class. Typically, it is called from within either update( ) or paint( ). It has the following general form: void drawstring(string message, int x, int y) Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is location 0,0. The drawstring( ) method will not recognize newline characters. If you want to start a line of text on another line, you must do so manually, specifying the precise X,Y location where you want the line to begin. (As you will see in later chapters, there are techniques that make this process easy.) To set the background color of an applet s window, use setbackground( ). To set the foreground color (the color in which text is shown, for example), use setforeground( ). These methods are defined by Component, and they have the following general forms: void setbackground(color newcolor) Chethan Raj C, Assistant Professor Dept. of CSE Page 21

22 void setforeground(color newcolor) Here, newcolor specifies the new color. The class Color defines the constants shown here that can be used to specify colors: Color.black Color.magenta Color.blue Color.orange Color.cyan Color.pink Color.darkGray Color.red Color.gray Color.white Color.green Color.yellow Color.lightGray For example, this sets the background color to green and the text color to red: setbackground(color.green); setforeground(color.red); A good place to set the foreground and background colors is in the init( ) method. User can change these colors as often as necessary during the execution of the applet. The default foreground color is black. The default background color is light gray. User can obtain the current settings for the background and foreground colors by calling getbackground( ) and getforeground( ), respectively. They are also defined by Component and are shown here: Color getbackground( ) Color getforeground( ) Example: import java.awt.*; Chethan Raj C, Assistant Professor Dept. of CSE Page 22

23 import java.applet.*; Object Oriented Programming Concepts-15CS45 /* <applet code="appletsample" width=300 height=100> </applet> */ public class AppletSample extends Applet String msg; // Set the foreground and background colors public void init() setbackground(color.cyan); setforeground(color.red); msg="inside init() --"; //Initialize the string to be displayed public void start() msg+="inside start()--"; // Display message in the applet window public void paint(graphics g) msg+="inside paint()."; g.drawstring(msg,10,30); Chethan Raj C, Assistant Professor Dept. of CSE Page 23

24 Requesting repainting; The paint () method is called automatically by the environment (usually a web browser) that contains the applet whenever the applet window needs to be redrawn. This happens when the component is first displayed, but it can happen again if the user minimizes the window that displays the component and then restores it or if the user moves another window over it and then move that window out of the way. In addition to these implicit calls to the paint() method by the environment, one can also call the paint () method explicitly whenever the applet window needs to be redrawn, using the repaint () method. The repaint () method causes the AWT runtime system to execute the update () method of the Component class which clears the window with the background color of the applet and then calls the paint () method. For example: Suppose you want to display the current x and y coordinates of the location where the mouse button is clicked in the applet window. As the applet needs to update information displayed in its window (i.e. redraw the window), each time the mouse is being clicked so this is possible with the use of repaint () method. To sum up, the repaint() method is invoked to refresh the viewing area i.e. user call it when user have new things to display. As a general rule, an applet writes to its window only when its update( ) or paint( ) method is called by the AWT i.e the applet itself cause its window to be updated when its information changes.for example, if an applet is displaying a moving banner, what mechanism does the applet use to update the window each time this banner scrolls is that one of the fundamental architectural constraints imposed on an applet is that it must quickly return control to the AWT run-time system. It cannot create a loop inside paint( ) that repeatedly scrolls the banner, for example. This would prevent control from passing back to the AWT. Given this constraint, it may seem that output to your applet s window will be difficult at best. Fortunately, this is not the case. Whenever your applet needs to update the information displayed in its window, it simply calls repaint( ). The repaint( ) method is defined by the AWT. It causes the AWT run-time system to execute a call to your applet s update( ) method, which, in its default implementation, calls paint( ). Thus, for another part of your applet to output to its window, simply store the output and then call repaint( ). The AWT will then execute a call to paint( ), which can display the stored information. For example, if part of your applet needs to output a string, it can store this string in a String variable and then call repaint( ). Inside paint( ), you will output the string using drawstring( ). The repaint( ) method has four forms. Let s look at each one, in turn. The simplest version of repaint( ) is shown here: Chethan Raj C, Assistant Professor Dept. of CSE Page 24

25 void repaint( ) This version causes the entire window to be repainted. The following version specifies a region that will be repainted: void repaint(int left, int top, int width, int height) Here, the coordinates of the upper-left corner of the region are specified by left and top, and the width and height of the region are passed in width and height. These dimensions are specified in pixels. You save time by specifying a region to repaint. Window updates are costly in terms of time. If you need to update only a small portion of the window, it is more efficient to repaint only that region. Calling repaint( ) is essentially a request that your applet be repainted sometime soon. However, if your system is slow or busy, update( ) might not be called immediately. Multiple requests for repainting that occur within a short time can be collapsed by the AWT in a manner such that update( ) is only called sporadically. This can be a problem in many situations, including animation, in which a consistent update time is necessary. One solution to this problem is to use the following forms of repaint( ): void repaint(long maxdelay) void repaint(long maxdelay, int x, int y, int width, int height) Here, maxdelay specifies the maximum number of milliseconds that can elapse before update( ) is called. Beware, though. If the time elapses before update( ) can be called, it isn t called. There s no return value or exception thrown, so you must be careful. It is possible for a method other than paint( ) or update( ) to output to an applet s window. To do so, it must obtain a graphics context by calling getgraphics( ) (defined by Component) and then use this context to output to the window. However, for most applications, it is better and easier to route window output through paint( ) and to call repaint( ) when the contents of the window change. import java.awt.*; import java.applet.applet; import java.awt.event.*; /*<applet code="repaintjavaexample.class" width="350" height="150"> </applet>*/ public class RepaintJavaExample extends Applet implements MouseListener private int mousex, mousey; private boolean mouseclicked = false; public void init() Chethan Raj C, Assistant Professor Dept. of CSE Page 25

26 setbackground(color.cyan); addmouselistener(this); public void mouseclicked(mouseevent e) mousex = e.getx(); mousey=e.gety(); mouseclicked = true; repaint(); public void mouseentered(mouseevent e); public void mousepressed(mouseevent e); public void mousereleased(mouseevent e); public void mouseexited(mouseevent e); public void paint( Graphics g ) String str; g.setcolor(color.red); if (mouseclicked) str = "X="+ mousex + "," + "Y="+ mousey ; g.drawstring(str,mousex,mousey); mouseclicked = false; Chethan Raj C, Assistant Professor Dept. of CSE Page 26

27 Using the Status Window Displaying messages is of two ways in Applet. One way is displaying anywhere in the applet window and the other way is displaying in the status bar with showstatus() method. In addition to displaying information in its window, an applet can also output a message to the status window of the browser or applet viewer on which it is running. To do so, call showstatus( ) with the string that you want displayed. The status window is a good place to give the user feedback about what is occurring in the applet, suggest options, or possibly report some types of errors. The status window also makes an excellent debugging aid, because it gives you an easy way to output information about your applet. status bar The bottom of the applet window is known as status bar. In a Browser or MS-Word, the bottom panel is known as status bar where in the line number where the cursor exists, current page number and total number of pages etc. are displayed. Status bar comes at the bottom of the browser and is used by the browser to display the status of the document opened. The applet can use this status bar to display strings (messages). Ex: To display the two ways, the Graphics class comes drawstring() method and Applet class comes with showstatus() method. Let us see what API says about these methods. void drawstring(string str, int x, int y): Draws the text given by the specified string, using this graphics context s current font and color. The baseline of the leftmost character is at position (x, y) in this graphics context s coordinate system. void showstatus(string msg): Requests that the argument string be displayed in the "status window". Many browsers and applet viewers provide such a window, where the application can inform users of its current state. Chethan Raj C, Assistant Professor Dept. of CSE Page 27

28 The following applet draws a string in the applet window (using drawstring()) and another string message on the status bar (using showstatus() ). HTML file: SSD.html <applet code="showstatusdemo.class" width="300" height="200"> </applet> Applet file: ShowStatusDemo.java import java.applet.applet; import java.awt.graphics; public class ShowStatusDemo extends Applet public void paint(graphics g) g.drawstring("hello World", 50, 75); // using drawstring() to display in applet window showstatus("greetings"); // using showstatus() to display in status bar Output The following applet demonstrates showstatus( ): // Using the Status Window. import java.awt.*; import java.applet.*; Chethan Raj C, Assistant Professor Dept. of CSE Page 28

29 /* <applet code="statuswindow" width=300 height=50> </applet> */ public class StatusWindow extends Applet public void init() setbackground(color.cyan); // Display msg in applet window. public void paint(graphics g) g.drawstring("this is in the applet window.", 10, 20); showstatus("this is shown in the status window."); Applet Example: Drawing Strings and Graphics in Applets given with Screenshots in Simple terms for a Beginner. After practicing the earlier simple life cycle program, let us write another program that prints some strings on applet window (not at DOS prompt as done previously). Now we use the java.awt.graphics object passed as parameter to paint() method. The application includes two files Demo.java, applet file and Demo.html, HTML file. HTML file should be opened in a browser using File menu. Applet Example: 1st File: Applet Demo.java import java.awt.*; import java.applet.*; public class Demo extends Applet Chethan Raj C, Assistant Professor Dept. of CSE Page 29

30 String s1, s2; public void init() s1 = "Welcome to way2java practices"; s2 = "on today " + new java.util.date(); public void paint(graphics g) g.drawstring(s1, 50, 50); g.drawstring(s2, 50, 70); g.drawstring("best Wishes", 50, 90); // directly writing a string public void destroy() s1 = null; s2 = null; 2nd File: HTML Demo.html <applet code="demo.class" width="250" height="250"> </applet> Execution Compile the Demo.java file as usual at DOS prompt as in the previous program. Let us run this program both using appletviewer and browser. Execution using appletviewer: C:\snr\way2java\applets> appletviewer Demo.html Execution using browser: Open the Demo.html file through File menu of browser. Two strings are assigned with some values in init() method and used in paint() method. Graphics is an abstract class and includes many methods of drawing. Here we use drawstring() method. The drawstring() takes three parameters the first one is a string that is to be drawn, the second and third Chethan Raj C, Assistant Professor Dept. of CSE Page 30

31 parameters are integer values of x and y coordinates in pixels, the position of the string on the applet window. Remember, the left top corner of the window is 0, 0 pixels. The other methods of drawing, we come to know in AWT Graphics Note: All the methods of Applet class are concrete methods (not abstract). The programmer can override what ever methods he would like and the other that are not used, are implicitly created and called by the browser (like the default constructor in an application). The HTML APPLET tag HTML (Hyper Text Markup Language). It is a type of data file which is transferred to the client machine. The HTML file gets translated and displayed on the screen if the client is using a Web browser like Netscape Navigator, Microsoft Internet Explorer etc. HTML File HTML stands for Hyper Text Markup Language. An HTML file is a text file containing small markup tags. The markup tags tell the Web browser how to display the page. An HTML file must have an htm or html file extension. An HTML file can be created using a simple text editor. HTML provides a tag that enables the developer to "embed" the applet within the page. This tag is known as the APPLET tag. HTML Tags HTML tags are used to mark-up HTML elements HTML tags are surrounded by the two characters < and > The surrounding characters are called angle brackets HTML tags normally come in pairs like <b> and </b> The first tag in a pair is the start tag, the second tag is the end tag The text between the start and end tags is the element content HTML tags are not case sensitive, <b> means the same as <B> HTML Elements Recall the HTML example from the previous previous section: <html> <head> Chethan Raj C, Assistant Professor Dept. of CSE Page 31

32 <title>title of page</title> </head> <body> Object Oriented Programming Concepts-15CS45 This is my first homepage. <b>this text is bold</b> </body> </html> Applet HTML Tag The APPLET tag can be used to start an applet from both an HTML document and from an applet viewer. An applet viewer will execute each APPLET tag that it finds in a separate window, while web browsers will allow many applets on a single page. Bracketed items are optional. < APPLET [CODEBASE = codebaseurl] CODE = appletfile [ALT = alternatetext] [NAME = appletinstancename] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [< PARAM NAME = AttributeName VALUE = AttributeValue>] [< PARAM NAME = AttributeName2 VALUE =AttributeValue>] [HTML Displayed in the absence of Java] </APPLET> CODEBASE CODEBASE is an optional attribute that specifies the base URL of the applet code The HTML document s URL directory is used as the CODEBASE if this attribute is not specified. CODE Chethan Raj C, Assistant Professor Dept. of CSE Page 32

33 CODE is a required attribute that gives the name of the file containing your applet s compiled.class file. ALT The ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser recognizes the APPLET tag but can t currently run Java applets. NAME NAME is an optional attribute used to specify a name for the applet instance. To obtain an applet by name, getapplet( ) methos is ised, which is defined by the AppletContext interface. WIDTH and HEIGHT WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display area. ALIGN ALIGN is an optional attribute that specifies the alignment of the applet.with values: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM. VSPACE and HSPACE These attributes are optional. VSPACE specifies the space, in pixels, above and below the applet. HSPACE specifies the space, in pixels, on each side of the applet. PARAM NAME and VALUE The PARAM specifies applet-specific arguments in an HTML page. Applets access their attributes with the getparameter( ) method. Passing parameters to Applets Java applet has the feature of retrieving the parameter values passed from the html page. So, you can pass the parameters from your html page to the applet embedded in your page. The param tag(<parma name="" value=""></param>) is used to pass the parameters to an applet. For the illustration about the concept of applet and passing parameter in applet, a example is given below. In this example, we will see what has to be done in the applet code to retrieve the value from parameters. Value of a parameter passed to an applet can be retrieved using getparameter() function. E.g. code: String strparameter = this.getparameter("message"); Chethan Raj C, Assistant Professor Dept. of CSE Page 33

34 Printing the value: Object Oriented Programming Concepts-15CS45 Then in the function paint (Graphics g), we prints the parameter value to test the value passed from html page. Applet will display "Hello! Java Applet" if no parameter is passed to the applet else it will display the value passed as parameter. In our case applet should display "Welcome in Passing parameter in java applet example." message. code for the Java program : import java.applet.*; import java.awt.*; public class appletparameter extends Applet private String strdefault = "Hello! Java Applet."; public void paint(graphics g) String strparameter = this.getparameter("message"); if (strparameter == null) strparameter = strdefault; g.drawstring(strparameter, 50, 25); code for the html program : <HTML> <HEAD> <TITLE>Passing Parameter in Java Applet</TITLE> </HEAD> <BODY> This is the applet:<p> <APPLET code="appletparameter.class" width="800" height="100"> <PARAM name="message" value="welcome in Passing parameter in java applet example."> </APPLET> Chethan Raj C, Assistant Professor Dept. of CSE Page 34

35 </BODY> </HTML> There is the advantage that if need to change the output then you will have to change only the value of the param tag in html file not in java code. Compile the program : javac appletparameter.java Output after running the program : To run the program using appletviewer, go to command prompt and type appletviewer appletparameter.html Appletviewer will run the applet for you and and it should show output like Welcome in Passing parameter in java applet example. Alternatively you can also run this example from your favorite java enabled browser. Ex: The APPLET tag in HTML allows to pass parameters to applet. To retrieve a parameter, getparameter( ) method is used. It returns the value of the specified parameter in the form of a String object. Thus, for numeric and boolean values,its need to convert their string representations into their internal formats. Here is an example that demonstrates passing parameters: // Use Parameters import java.awt.*; import java.applet.*; /* <applet code= ParamDemo width=300 height=200> </applet> */ public class ParamDemo extends Applet String fontname; int fontsize; float leading; boolean active; // Initialize the string to be displayed. Chethan Raj C, Assistant Professor Dept. of CSE Page 35

36 public void start() String param; fontname = getparameter("fontname"); if(fontname == null) fontname = "Not Found"; param = getparameter("fontsize"); try if(param!= null) // if not found fontsize = Integer.parseInt(param); else fontsize = 0; catch(numberformatexception e) fontsize = -1; param = getparameter("leading"); try if(param!= null) // if not found leading = Float.valueOf(param).floatValue(); else leading = 0; Chethan Raj C, Assistant Professor Dept. of CSE Page 36

37 catch(numberformatexception e) leading = -1; Object Oriented Programming Concepts-15CS45 param = getparameter("accountenabled"); if(param!= null) active = Boolean.valueOf(param).booleanValue(); public void paint(graphics g) g.drawstring("font name: " + fontname, 0, 10); g.drawstring("font size: " + fontsize, 0, 26); g.drawstring("leading: " + leading, 0, 42); g.drawstring("account Active: " + active, 0, 58); conversions to numeric types must be attempted in a try statement that catches NumberFormatException. Uncaught exceptions should never occur within an applet. getdocumentbase() and getcodebase() User will create applets that will need to explicitly load media and text. Java will allow the applet to load data from the directory holding the HTML file that started the applet (the document base) and the directory from which the applet s class file was loaded (the code base). These directories are returned as URL objects (described in Chapter 18) by getdocumentbase( ) and getcodebase( ). They can be concatenated with a string that names the file you want to load. To actually load another file, Chethan Raj C, Assistant Professor Dept. of CSE Page 37

38 you will use the showdocument( ) method defined by the AppletContext interface, discussed in the next section. The following applet illustrates these methods: // Display code and document bases. import java.awt.*; import java.applet.*; import java.net.*; /* <applet code="bases" width=300 height=50> </applet> */ public class Bases extends Applet // Display code and document bases. public void paint(graphics g) String msg; URL url = getcodebase(); // get code base msg = "Code base: " + url.tostring(); g.drawstring(msg, 10, 20); url = getdocumentbase(); // get document base msg = "Document base: " + url.tostring(); g.drawstring(msg, 10, 40); Drawing in an Applet In an applet to load an image or draw different shapes like an oval, rectangle and a line in an applet. To perform these operations the three methods are required: Chethan Raj C, Assistant Professor Dept. of CSE Page 38

39 getcodebase() method of Applet class. public URL getcodebase() This method gives us the location of the directory in which our applet code file is located. This location is returned to us in terms of an object of URL class. Using this object of URL class, we can get and load any image file present in the same directory using the next two methods. getimage() method of Applet class. public Image getimage(url url, String name) This method gets the image file in the form of Image object. This image file named name is present in the directory location specified by url. This directory also contains the applet code. drawimage() method of Image class. public drawimage(image img, int x, int y, ImageObserver observer) This method draws the image referred by Image object img, at the coordinates x and y in an applet's window. We also need to pass an object of ImageObserver interface. We can do by passing this reference of our Applet class, because it implements ImageObserver interface. getdocumentbase() and getcodebase() In most of the applets, it is required to load text and images explicitly. Java enables loading data from two directories. The first one is the directory which contains the HTML file that started the applet (known as the document base). The other one is the directory from which the class file of the applet is loaded (known as the code base). These directories can be obtained as URL objects by using getdocumentbase ()and getcodebase ()methods respectively. You can concatenate these URL objects with the string representing the name of the file that is to be loaded. Java will allow the applet to load data from the directory holding the html file that started the applet (the document base) and the directory from which the applet s class file was loaded (the code base). These directories are returned by getdocumentbase( ) and getcodebase( ). Ex: import java.applet.applet; import java.awt.graphics; /* <applet code="javaapp" width=300 height=100> */ </applet> public class Javaapp extends Applet public void paint(graphics g) Chethan Raj C, Assistant Professor Dept. of CSE Page 39

40 g.drawstring("getcodebase : "+getcodebase(), 20, 20); g.drawstring("getdocumentbase : "+getdocumentbase(), 20, 40); Ex: /*java code for the program GetDocumentBase and getcodebase Example :.*/ /* <applet code="getdocumentbase" width=350 height=250> </applet> */ import java.applet.applet; import java.awt.graphics; import java.net.url; import java.awt.*; import java.awt.event.*; public class GetDocumentBase extends Applet public void paint(graphics g) String message; //getcodebase() method gets the base URL of the directory in which contains this applet. URL appletcodedir=getcodebase(); message = "Code Base : "+appletcodedir.tostring(); Chethan Raj C, Assistant Professor Dept. of CSE Page 40

41 g.drawstring(message,10,90); // getdocumentbase() Returns an absolute URL of the Document URL appletdocdir = getdocumentbase(); message="document Base : "+appletdocdir.tostring(); g.drawstring(message,10,120); g.drawstring(" 200, 250); ApletContext and showdocument() Java allows the applet to transfer the control to another URL by using the showdocument () Method defined in the AppletContext interface. For this, first of all, it is needed to obtain the Context of the currently executing applet by calling the getappletcontext () method defined by the Applet. Once the context of the applet is obtained with in an applet, another document can be brought into view by calling showdocument () method. There are two showdocument () methods which are as follows: showdocument(url url) showdocument(url url,string lac) where, url is the URL from where the document is to be brought into view. loc is the location within the browser window where the specified document is to be displayed. Example import java.applet.*; import java.awt.*; import java.net.*; import java.awt.event.*; public class ShowDocument_AppletContext extends Applet implements ActionListener Chethan Raj C, Assistant Professor Dept. of CSE Page 41

42 public void init() Button button = new Button("Go To Html Page"); button.addactionlistener(this); add(button); public void actionperformed(actionevent ae) try URL url = new URL(getDocumentBase(), "HtmlExample.html"); getappletcontext().showdocument(url); catch (MalformedURLException e) showstatus("url not found"); //html code <html> <head> <title>showdocument_appletcontext</title> </head> <body> <applet code="showdocument_appletcontext" width="700" height="500"></applet> Chethan Raj C, Assistant Professor Dept. of CSE Page 42

43 </body> </html> The AudioClip Interface The AudioClip class is used to load and play sound files. To load a sound file the getaudioclip () Method of the AudioClip class is used. The general form of the getaudioclip () method is AudioClip getaudioclip (URL pathname, String filename) AudioClip getaudioclip (URL pathname) where, pathname is the address of the sound file. When the image file and the source file are in the same directory, getcodebase () method is used as first parameter to the method. filename is the name of the sound file Some of the methods of AudioClip class along with their description are listed in Table Method and Description void play() used to play the sound for once void loop() used to play the sound in loop void stop () used to stop playing the sound Example: An applet code to demonstrate the use of AudioClip class import java.applet.*; import java.awt.*; Chethan Raj C, Assistant Professor Dept. of CSE Page 43

44 public class SoundExample extends Applet private AudioClip mysound; public void init() mysound=getaudioclip(getcodebase(), "chimes.wav"); public void start() mysound.loop(); public void stop() mysound.stop(); The HTML code for SoundExample is <HTML> <HEAD> </HEAD> <BODY> <CENTER> <APPLETCODE="SoundExample.class" WIDTH="200" HEIGHT="l30"> </APPLET> </CENTER> </BODY> </HTML> Chethan Raj C, Assistant Professor Dept. of CSE Page 44

45 FEATURE APPLICATION APPLET main() method Present Not present Execution Requires JRE Requires a browser like Chrome Nature Restrictions Security Called as stand-alone application as application can be executed from command prompt Can access any data or software available on the system Does not require any security Requires some third party tool help like a browser to execute cannot access any thing on the system except browser s services Requires highest security for the system as they are untrusted The AppletStub Interface; When an applet is first created, an applet stub is attached to it using the applet's setstub method. This stub serves as the interface between the applet and the browser environment or applet viewer environment in which the application is running. User code will not typically implement this interface.( public interface AppletStub) The AppletStub interface provides a way to get information from the run-time browser environment. The Applet class provides methods with similar names that call these methods. void AppletContext URL URL String boolean Method Summary appletresize(int width, int height) //Called when the applet wants to be resized. getappletcontext() //Returns the applet's context. getcodebase() //Gets the base URL. getdocumentbase()//gets the URL of the document in which the applet is embedded. getparameter(string name) //Returns the value of the named parameter in the HTML tag. isactive() //Determines if the applet is active. isactive boolean isactive() Determines if the applet is active. An applet is active just before its start method is called. It becomes inactive just before its stop method is called. Returns: true if the applet is active; false otherwise. Chethan Raj C, Assistant Professor Dept. of CSE Page 45

46 getdocumentbase URL getdocumentbase() Gets the URL of the document in which the applet is embedded. For example, suppose an applet is contained within the document: The document base is: Returns: the URL of the document that contains the applet. See Also: getcodebase() getcodebase URL getcodebase() Gets the base URL. This is the URL of the directory which contains the applet. Returns: the base URL of the directory which contains the applet. See Also: getdocumentbase() getparameter String getparameter(string name) Returns the value of the named parameter in the HTML tag. For example, if an applet is specified as <applet code="clock" width=50 height=50> <param name=color value="blue"> </applet> then a call to getparameter("color") returns the value "blue". Parameters: name - a parameter name. Returns: the value of the named parameter, or null if not set. getappletcontext AppletContext getappletcontext() Returns the applet's context. Returns: the applet's context. Chethan Raj C, Assistant Professor Dept. of CSE Page 46

47 appletresize void appletresize(int width, int height) Called when the applet wants to be resized. Parameters: width - the new requested width for the applet. height - the new requested height for the applet. Output to the Console. Although output to an applet s window must be accomplished through AWT methods, such as drawstring( ), it is still possible to use console output in your applet especially for debugging purposes. In an applet, when you call a method such as System.out.println( ), the output is not sent to your applet s window. Instead, it appears either in the console session in which you launched the applet viewer or in the Java console that is available in some browsers. Use of console output for purposes other than debugging is discouraged, since it violates the design principles of the graphical interface most users will expect.apletcontext and showdocument(); Swings Swing, a part of Java Federation Classes (JFC) is the next generation GUI toolkit that allows us to develop large scale enterprise applications in Java. It is a set of classes which provides many powerful and flexible components for creating graphical user interface. Earlier, the concept of Swing did not exist in Java and the user interfaces were built by using the Java's original GUI system, AWT. Because of the limitations of the AWT, Swing was introduced in 1997 by the Sun Microsystems. It provides new and improved components that enhance the look and functionality of GUIs. With Java 1.1, Swing was used as a separate library. However, it was fully integrated into Java with the start of Java 1.2. So, user working with Java 1.2 can easily work with Swing. Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT. In addition to the familiar components, such as buttons, check boxes, and labels, Swing supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables. Even familiar components such as buttons have more capabilities in Swing. For example, a button may have both an image and a text string associated with it. Also, the image can be changed as the state of the button changes. Unlike AWT components, Swing components are not implemented by platform-specific code. Instead, they are written entirely in Java and, therefore, are platform-independent. The term lightweight is used to describe such elements. Swing are built on AWT. Chethan Raj C, Assistant Professor Dept. of CSE Page 47

48 The origins of Swing Object Oriented Programming Concepts-15CS45 Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). Swing provides a native look and feel that emulates the look and feel of several platforms, and also supports a pluggable look and feel that allows applications to have a look and feel unrelated to the underlying platform. It has more powerful and flexible components than AWT. In addition to familiar components such as buttons, check boxes and labels, Swing provides several advanced components such as tabbed panel, scroll panes, trees, tables, and lists. Two key Swing features Swing has the following features : Extensible : Swing has the feature to "plug" custom specified framework's interfaces implementation. Customizable : Swing allows to customize its standard components programmatically for example, assigning specific borders, colors, backgrounds, etc. Configurable : Swing is configurable, it allows to change in its fundamental settings at runtime. For example, changing in the look and feel implementation at the runtime. Light Weight UI : Swing components are light weight UI. However, all swing components are inherited from the AWT because, the JComponent of Swing package extends the container of AWT that uses the OS-native "heavyweight" widget but the swing uses its own OS-agnostic over the fundamental components. Loosely Coupled : Swing framework is designed in such a way that there is no tight coupling between the interfaces, presentation, and controller. MVC : Java Swing is a MVC based framework (a Software Design Pattern) that separates the data viewed from the interface using which it is viewed. Even the Swing provides many new features two of its popular features are: 1. Swing components are light weight They are entirely written in java they does not map to native platform specific code. More flexible and more efficient. Not in rectangular shapes. Swing components are lightweight as they are written entirely in Java and do not depend on native peers (platform specific code resources). Rather, they use simple drawing primitives to render themselves on the screen. The look and the feel of the component is not controlled by the underlying operating system but by Swing itself. Thus, they are not restricted to platform-specific appearance like, rectangular or opaque shape. Chethan Raj C, Assistant Professor Dept. of CSE Page 48

49 Note: Most of the components are lightweight but not all. 2. Swing supports a pluggable look and feel. It becomes possible to change the that component is rendered with out affecting any of its other aspects. Possible to create new look and feel for any given component with out side effects. Look and feel is simply plugged in. The pluggable look arid feel feature allows us to tailor the look and feel of the application and applets to the standard looks like, Windows and Motif. We can even switch to different look and feel at runtime. Swing has the capability to support several look and feels, but at present, it provides support for the Windows and Motif. As the look and feel of components is controlled by Swing rather than by operating system, the feel of components can also be changed. The look and feel of a component can be separated form the logic of the component. Thus, it is possible to "plug in" a new look and feel for any given component without affecting the rest of the code. Note: Default look and feel, provided by JE 1.6 is called metal, which is also called the Java look and feel. Components and Containers Swing component is an independent control, such as button, label, text field, etc. They need. a container to display themselves. Swing components are derived from JComponent class. JComponent provides the functionality common for all components. JComponent inherits the AWT class Container and Component. Thus, a Swing component and AWT component are compatible with each other. There are two types of containers namely, top-level containers and lightweight containers Top-Level Containers A top-level container, as the name suggests, lies at the top of the containment hierarchy. The toplevel containers are JFrame, JApplet, and JDialog. These containers do not inherit JComponent class but inherit the AWT classes' Component and Container. These containers are heavyweight components. The most commonly used containers are JFrame and JApplet. Each top-level container defines a set of panes. JRootPane is a special container which extends JComponent and manages the appearance of JApplet and JFrame objects. It contains a fixed set of panes, namely, glass pane, content pane, and layered pane. Glass pane: A glass pane is a top-level pane which covers all other panes. By default, it is a transparent instance of JPanel class. It is used to handle the mouse events affecting the entire container. Layered pane: A layered pane is an instance of JLayeredPane class. It holds a container called the content pane and an optional menu bar. Content pane: A content pane is a pane which is used to hold the components. All the visual components like buttons, labels are added to content pane. By default, it is an opaque instance of Chethan Raj C, Assistant Professor Dept. of CSE Page 49

50 JPanel class and uses border layout. The content pane is accessed via getcontentpane () method of JApplet and JFrame classes. Lightweight Containers Lightweight containers lie next to the top-level containers in the containment hierarchy. They inherit. JComponent. One of the examples of lightweight container is JPanel. As lightweight container can be contained within another container, they can be used to organize and manage groups of related components. Components and containers 1. A Swing GUI consists of two key items: Components and Container 2. A term component is an independent visual control such as push button or slider. 3. A container holds group of components. Thus container is special kind of component that holds that is designed to hold other components. Container are also called components so container can hold other container. Components 1. Swing components are derived from JComponent Class. Supports pluggable look and feel. It inherits Component and Container of AWT. Swing Components : JButton, JCheckBox, JComboBox,JTree,JLabel, JTable,JPanel..etc Container 1. Swing defines two types of heavy weight container. JFrame, JApplet 2. Others are light weight containers. 3. Top level containers should be declared first like JFrame and JApplet. 4. Light weight containers example if JPanel. This is used to manage group of related components 5. JPanel is used to create subgroups of related components that are contained with in another container. Examples of containers JPanel is Swing s version of the AWT class Panel and uses the same default layout,flowlayout. JPanel is descended directly from JComponent. JFrame is Swing s version of Frame and is descended directly from that class. The components added to the frame are referred to as its contents; these are managed by the contentpane. To add a component to a JFrame, we must use its contentpane instead. Chethan Raj C, Assistant Professor Dept. of CSE Page 50

51 JWindow is Swing s version of Window and is descended directly from that class. LikeWindow, it uses BorderLayout by default. JDialog is Swing s version of Dialog and is descended directly from that class. Like Dialog, it uses BorderLayout by default. Like JFrame and JWindow. Commonly used Methods of Component class. The methods of Component class are widely used in java swing that are given below. Method public void add(component c) public void setsize(int width,int height) public void setlayout(layoutmanager m) public void setvisible(boolean b) Description add a component on another component. sets size of the component. sets the layout manager for the component. sets the visibility of the component. It is by default false. Add a component to a container In order to add a component to a container, first create an instance of the desired component and then call the add () method of the Container class to add it to a window. The add () method has many forms and one of these is. Component add (Component c) This method adds an instance of component (i.e. c) to the container. The component added is automatically visible whenever its parent window is displayed. import java.awt.*; class AddComponent public static void main(string args[]) Frame frame = new Frame("Add Components to a Container"); Button button = new Button("OK"); frame.add(button); frame.setsize(300,250); frame.setvisible(true); Chethan Raj C, Assistant Professor Dept. of CSE Page 51

52 The Swing Packages Some of the packages of swing components that are used as follows: Javax.swing javax.swing.event javax.swing.plaf.basic javax.swing.table javax.swing.border javax.swing.tree The largest of the swing packages, javax.swing, contains most of the user-interface classes (these are J classes, the classes having the prefix J). JTableHeader and JTextComponent are the exceptional classes implemented in the packages javax.swing.table and javax.swing.text, respectively. javax.swing.text contains two sub-packages known as javax.swing.text.html and javax.swing.text.rtf used for HTMLcontent and for Rich Text Format content, respectively. To define the look and feel of the swing component, the javax.swing.plaf.basic package is used. javax.swing.border contains an interface called Border which is implemented by all the border classes. These classes cannot be instantiated directly. They are instantiated using the factory method (BorderFactory) defined in the javax.swing package. The javax.swing.event package contains all the classes that are used for event handling. The javax.swing.tree package includes classes and interfaces that are specific to the JTree component. There are totally 16 packages in the swings packages and javax.swing is one of them. A brief description of all the packages in swing is given below. Chethan Raj C, Assistant Professor Dept. of CSE Page 52

53 Packages javax.swing javax.swing.border javax.swi ng.colorchooser javax.swing.event javax.swing.filechooser javax.swing.plaf javax.swing.plaf.basic javax.swing.plaf.metal javax.swi ng.plaf.mult javax.swing.table javax.swing.text javax.swing.text.html javax.swing.text.html.parser javax.swing.text.rtf javax.swing.tree javax.swing.undo Description Provides a set of "lightweight" (all-java language) components to the maximum degree possible, work the same on all platforms. Provides classes and interface for drawing specialized borders around a Swing component. Contains classes and interfaces used by the JcolorChooser component. Provides for events fired by Swing components Contains classes and interfaces used by the JfileChooser component. Provides one interface and many abstract classes that Swing uses to provide its pluggable look-and-feel capabilities. Provides user interface objects built according to the Basic look and feel. Provides user interface objects built according to the Java look and feel (once condenamed Metal), which is the default look and feel. Provides user interface objects that combine two or more look and feels. Provides classes and interfaces for dealing with javax.swing.jtable Provides classes and interfaces that deal with editable and noneditable text components Provides the class HTML Editor Kit and supporting classes for creating HTML text editors. Provides the default HTML parser, along with support classes. Provides a class RTF Editor Kit for creating Rich- Text-Format text editors. Provides classes and interfaces for dealing with javax.swing.jtree Allows developers to provide support for undo/redo in applications such as text editors. Chethan Raj C, Assistant Professor Dept. of CSE Page 53

54 Difference between java awt and swing that are given below. No. Java AWT Java Swing 1) AWT components are platformdependent. Java swing components are platformindependent. 2) AWT components are heavyweight. Swing components are lightweight. 3) AWT doesn't support pluggable look and feel. 4) AWT provides less components than Swing. 5) AWT doesn't follows MVC(Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view. Swing supports pluggable look and feel. Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser, tabbedpane etc. Swing follows MVC. The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications. Fig:Java Swing API Chethan Raj C, Assistant Professor Dept. of CSE Page 54

55 JFrame In a Java Swing, A JFrame is the class that represents the window in which graphics applications running on Java. JFrame Class is the top-level container that contains content pane all visible components contain in the content pane. The usual procedure to be used to create a new class that inherits from JFrame. Normally JFrame's are used as primary containers, that is, not contained in other containers. A frame is often put a main panel from which the other elements are organized. To place this main panel method is used. public void setcontentpane(cantainer contentpane) import java.awt.*; import javax.swing.*; public class JFrameContentPane extends JFrame private final int SIZE = 200; private Container con = getcontentpane(); private JButton BtnClckIt = new JButton("Click it"); public JFrameContentPane() super("jframe ContentPane Layout in Java Swing Example"); setsize(500,500); setvisible(true); con.setlayout(new FlowLayout()); con.add(btnclckit); public static void main(string[] args) JFrameContentPane JFrameCP = new JFrameContentPane(); Chethan Raj C, Assistant Professor Dept. of CSE Page 55

56 JFrame is a top-level container that is used to hold components in it. These components could be button, textfield, label etc. The default layout of JFrame by which it positions the components in it is BoderLayout manager. Constructors of JFrame Constructor public JFrame() public JFrame(String name) Description Creates a JFrame window with no name. Creates a JFrame window with a name. JFrame methods Methods public void add(component comp) public void setlayout(layoutmanager object) public void remove(component comp) public void setsize(int widthpixel, int heightpixel) public setdefaultcloseoperation(int operation) public void setvisble(boolean b) void Description This method adds the component, comp, to the container JFrame. This method sets the layout of the components in a container, JFrame. This method removes a component, comp, from the container, JFrame. This method sets the size of a JFrame in terms of pixels. This method sets the operation that will take place when a a user clicks on close(x) button of this JFrame. An operation may take any of the values- DO_NOTHING_ON_CLOSE HIDE_ON_CLOSE DISPOSE_ON_CLOSE EXIT_ON_CLOSE This method set the visibility of JFrame using boolean value. BorderLayout is the default layout manager of JFrame. The default layout of JFrame by which it positions the components in it is BoderLayout manager. Hence, if we add components to JFrame without calling it's setlayout() method, these components are added to the center region of by default. Note : Remember, using the BorderLayout manager, only one component can be placed in a region, Chethan Raj C, Assistant Professor Dept. of CSE Page 56

57 hence if multiple elements are added to a region, only the last element will be visible. import javax.swing.*; //import java.awt.*; class SwingEx implements Runnable public static void main(string...ar) SwingUtilities.invokeLater(new SwingEx()); public void run() new A(); class A JFrame frame; JLabel label; JButton button; A() frame = new JFrame("JFrame"); label = new JLabel("Hello there, how are you today? :-)"); button = new JButton("Button1"); //Adding JLabel and JButton to JFrame, which will added to BorderLayout.CENTER region of JFrame. frame.add(label); frame.add(button); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(210,250); frame.setvisible(true); In the last code, two components i.e JLabel and JButton are added to top-level container, JFrame, without calling its setlayout() method. These components are added to BorderLayout.CENTERregion of JFrame. Hence, only the last component added, i.e. JButton Chethan Raj C, Assistant Professor Dept. of CSE Page 57

58 will be visible. When user run the code, you are presented a window that only shown a button. Figure 1 A simple example of JFrame with FlowLayout manager. In the code user add two components i.e JLabel and JButtonto JFrame. Before adding these components to JFrame, we will call setlayout() method to position components in JFrame according to FlowLayoutManager import javax.swing.*; //import java.awt.*; class SwingEx implements Runnable public static void main(string...ar) SwingUtilities.invokeLater(new SwingEx()); public void run() new A(); class A JFrame frame; JLabel label; JButton button; A() frame = new JFrame("JFrame"); Chethan Raj C, Assistant Professor Dept. of CSE Page 58

59 label = new JLabel("Hello there, how are you today? :-)"); button = new JButton("Button1"); //Setting the layout of components in JFrame to FlowLayout frame.setlayout(new FlowLayout()); frame.add(label); frame.add(button); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(210,250); frame.setvisible(true); When user run the code, you are presented a window that contains a top-level container, JFrame, which includes two components that are positioned in JFrame using FlowLayout manager - A JLabel displaying a message. A JButton displaying a button. Figure 2 A simple Swing Application Swing is important to develop Java programs with a graphical user interface (GUI). There are many components which are used for the building of GUI in Swing. The Swing Toolkit consists of many components for the building of GUI. These components are also helpful in providinginteractivity to Java applications. Following are components which are included in Swing toolkit: list controls buttons labels tree controls Chethan Raj C, Assistant Professor Dept. of CSE Page 59

60 table controls Object Oriented Programming Concepts-15CS45 All AWT flexible components can be handled by the Java Swing. Swing toolkit contains far more components than the simple component toolkit. It is unique to any other toolkit in the way that it supports integrated internationalization, a highly customizable text package, rich undo support etc. Not only this you can also create your own look and feel using Swing other than the ones that are supported by it. The customized look and feel can be created usingsynth which is specially designed. Not to forget that Swing also contains the basic user interface such as customizable painting, event handling, drag and drop etc. The Java Foundation Classes (JFC) which supports many more features important to a GUI program comprises ofswing as well. The features which are supported by Java Foundation Classes (JFC) are the ability to create a program that can work in different languages, the ability to add rich graphics functionality etc. The features which are provided by Swing and the Java Foundation Classes are as follows: Swing GUI Components There are several components contained in Swing toolkit such as check boxes, buttons, tables, text etc. Some very simple components also provide sophisticated functionality. For instance, text fields provide formatted text input or password field behavior. Furthermore, the file browsers and dialogs can be used according to one's need and can even be customized. Ex: The basic window on the screen. import javax.swing.jframe; import javax.swing.swingutilities; public class Example extends JFrame public Example() settitle("simple example"); setsize(300, 200); setlocationrelativeto(null); setdefaultcloseoperation(exit_on_close); public static void main(string[] args) Example ex = new Example(); ex.setvisible(true); Chethan Raj C, Assistant Professor Dept. of CSE Page 60

61 While this code is very small, it can be resized, maximized, minimized. All the complexity that comes with it has been hidden from the application programmer. import javax.swing.jframe; import javax.swing.swingutilities; Here we import Swing classes, that will be used in the code example. public class Example extends JFrame The Example class inherits from the JFrame widget. JFrame is a toplevel container, which is used for placing other widgets. settitle("simple example"); Here we set the title of the window using the settitle() method. setsize(300, 200); This code will resize the window to be 300px wide and 200px tall. setlocationrelativeto(null); This line will center the window on the screen. setdefaultcloseoperation(exit_on_close); This method will close the window, if we click on the close button of the titlebar. By default nothing happens. Example ex = new Example(); ex.setvisible(true); Create an instance of our code example and make it visible on the screen. Note that the main method is static, so when it is called (when the program starts), there is not yet any object Example. Again, main is like an external global method. Only when we explicitly create an instance (with new Example()) that an object Example, thus a JFrame appears. Chethan Raj C, Assistant Professor Dept. of CSE Page 61

62 Figure: Simple example Ex: When user click on the button, the application terminates. import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.swingutilities; public class Example extends JFrame public Example() initui(); public final void initui() JPanel panel = new JPanel(); getcontentpane().add(panel); panel.setlayout(null); JButton quitbutton = new JButton("Quit"); quitbutton.setbounds(50, 60, 80, 30); quitbutton.addactionlistener(new ActionListener() public void actionperformed(actionevent event) System.exit(0); Chethan Raj C, Assistant Professor Dept. of CSE Page 62

63 panel.add(quitbutton); settitle("quit button"); setsize(300, 200); setlocationrelativeto(null); setdefaultcloseoperation(exit_on_close); public static void main(string[] args) public void run() Example ex = new Example(); ex.setvisible(true); We position a JButton on the window. We will add an action listener to this button. public Example() initui(); It is a good programming practice to put the code that creates the GUI inside a specific method. JPanel panel = new JPanel(); getcontentpane().add(panel); create a JPanel component. It is a generic lightweight container. We add the JPanel to the JFrame. panel.setlayout(null); By default, the JPanel has a FlowLayout manager. The layout manager is used to place widgets onto the containers. If we call setlayout(null) we can position our components absolutely. For this, we use the setbounds() method. JButton quitbutton = new JButton("Quit"); quitbutton.setbounds(50, 60, 80, 30); quitbutton.addactionlistener(new ActionListener() Chethan Raj C, Assistant Professor Dept. of CSE Page 63

64 Object Oriented Programming Concepts-15CS45 public void actionperformed(actionevent event) System.exit(0); User create a button by position it calling the setbounds() method. Then we add an action listener. The action listener will be called, when we perform an action on the button. In our case, if we click on the button. The click will terminate the application. panel.add(quitbutton); In order to show the quit button, we must add it to the panel. Figure: Quit button For complex applications, it is more convenient to define an action listener that is not anonymous. The JFrame class can itself act like one by implementing the ActionListener interface. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Example extends JFrame implements ActionListener public Example() initui(); public final void initui() Chethan Raj C, Assistant Professor Dept. of CSE Page 64

65 JButton button1 = new JButton("Button1"); JButton button2 = new JButton("Button2"); button1.setbounds(50, 60, 100, 30); button2.setbounds(180, 60, 100, 30); getcontentpane().setlayout(null); getcontentpane().add(button1); getcontentpane().add(button2); button1.addactionlistener(this); button2.addactionlistener(this); setsize(300, 200); setlocationrelativeto(null); setdefaultcloseoperation(exit_on_close); public void actionperformed(actionevent e) System.out.println("Oui!"); public static void main(string[] args) Example ex = new Example(); ex.setvisible(true); It is also possible to define externally the action listener class as follows. class MyActionListener implements ActionListener Chethan Raj C, Assistant Professor Dept. of CSE Page 65

66 public MyActionListener(String msg) this.msg = msg; public void actionperformed(actionevent e) System.out.println(msg); String msg; In the above example, user used the same action listener for two buttons. In general, an application may contain tens of buttons, and we do not want to create a new class for each of them. In order to distinguish the "source" of the action, modify user action Performed method by using the information contained in the ActionEvent argument Create a Swing Applet User can create the applets based on AWT(Abstract Window Toolkit) by extending the Appletclass of the awt package. Similarly user can also create applets based on the Swing package. In order to create such applets, user must extend the JApplet class of the swing package. JApplet extends Applet class, hence all the features of Applet class are available in JApplet as well, including JApplet's own Swing based features. Swing applets provies easier to use user interface than AWT applets. When user create an AWT applet, we implement the paint(graphics g) method to draw in it but when we create a Swing applet, we implement paintcomponent(graphics g) method to draw in it. For an applet class that extends Swing's JApplet class, the way elements like textfield, buttons, checksboxes etc are added to this applet is performed by using a default layout manager, i.e. BorderLayout Note: JApplet is a top-level container class and you should never draw on it directly, instead you should draw on the component class like JPanel and then add this JPanel to the JApplet, as shown in the upcoming code. Ex:Create a swing applet by extending JApplet class and we have added a JPanel to it. Next, create a class B, which has extended JPanel class of Swing package and have also implemented ActionListener interace to listen to the button click event generated when buttons added to JPanel are clicked. Chethan Raj C, Assistant Professor Dept. of CSE Page 66

67 import java.awt.*; import java.applet.*; import java.awt.event.*; import javax.swing.*; /* <applet code="applet21" width="500" height="200"> </applet> */ public class Applet21 extends JApplet public void init() add(new B()); //Adding a JPanel to this Swing applet class B extends JPanel implements ActionListener JLabel jb; JButton Box2, box2, box3, box4; String str; B() jb= new JLabel("Welcome, please click on any button for text information -"); Box2 = new JButton("Box2"); box2 = new JButton("Box2"); box3 = new JButton("Box3"); box4 = new JButton("Box4"); Chethan Raj C, Assistant Professor Dept. of CSE Page 67

68 str =""; setlayout(new FlowLayout()); add(jb); add(box2); add(box2); add(box3); add(box4); Box2.addActionListener(this); box2.addactionlistener(this); box3.addactionlistener(this); box4.addactionlistener(this); public void actionperformed(actionevent ae) if(ae.getactioncommand().equals("box2")) str=" The digital revolution is far more significant than the invention of writing or even of printing."; repaint(); if(ae.getactioncommand().equals("box2")) str=" Never trust a computer you can't throw out a window."; repaint(); if(ae.getactioncommand().equals("box3")) str=" Man is still the most extraordinary computer of all.."; Chethan Raj C, Assistant Professor Dept. of CSE Page 68

69 repaint(); if(ae.getactioncommand().equals("box4")) str=" You can t have great software without a great team."; repaint(); public void paintcomponent(graphics g) super.paintcomponent(g); g.drawstring(str, 2, 170); In the applet shown above, four buttons are presented in the output. These buttons are added to Bclass(which has extended JPanel). This JPanel is inturn added to our Swing applet class, Applet21. Whenever a button is clicked, the data is presented to the user. Jlabel and ImageIcon A displayed label object is known as the Label. Most of the times label is used to demonstrate the significance of the other parts of the GUI. It helps to display the functioning of the next text field. A label is also restricted to a single line of text as a button. The example below shows the significance of Label. In this example, we have added two labels in the applet as shown. import java.awt.*; import java.applet.applet; public class MyLabel extends Applet public void init() Chethan Raj C, Assistant Professor Dept. of CSE Page 69

70 add(new Label("label one")); add(new Label("label two", Label.RIGHT)); output: C:\newprgrm>javac MyLabel.java C:\newprgrm>appletviewer MyLabel.html Paint means draw an image and set its on the frame to the specified location according to its x coordinate and y coordinate. Description of program: This program shows how to paint an image on the fame to specified location. For this user need images that have to be set on the frame. Initially draw a rectangle and set the two images on to rectangle. Paint the rectangle in the yellow color. All drawing process is done using the paint() method. Here is the code of program: import java.awt.*; import java.awt.event.*; public class PaintIcon extends Frame Image image; public static void main(string[] args) new PaintIcon(); Chethan Raj C, Assistant Professor Dept. of CSE Page 70

71 public PaintIcon() Object Oriented Programming Concepts-15CS45 settitle("paint an Icon example!"); setsize(200,200); setvisible(true); addwindowlistener(new WindowAdapter() public void windowclosing(windowevent we) System.exit(0); public void paint(graphics g) Toolkit tool = Toolkit.getDefaultToolkit(); image = tool.getimage("warning.gif"); g.drawrect(20,50,100,100); g.drawstring("draw Images:",20,40); g.setcolor(color.yellow); g.fillrect(20,50,100,100); g.drawimage(image,30,85,this); image = tool.getimage("tom.gif"); g.drawimage(image,80,85,this); Chethan Raj C, Assistant Professor Dept. of CSE Page 71

72 JTextField Java JTextField The object of a JTextField class is a text component that allows the editing of a single line text. It inherits JTextComponent class. JTextField class declaration The declaration for javax.swing.jtextfield class. 1. public class JTextField extends JTextComponent implements SwingConstants Commonly used Constructors: Constructor JTextField() JTextField(String text) JTextField(String text, int columns) JTextField(int columns) Description Creates a new TextField Creates a new TextField initialized with the specified text. Creates a new TextField initialized with the specified text and columns. Creates a new empty TextField with the specified number of columns. Commonly used Methods: Methods void addactionlistener(actionlistener l) Description It is used to add the specified action listener to receive action events from this textfield. Chethan Raj C, Assistant Professor Dept. of CSE Page 72

73 Action getaction() void setfont(font f) void removeactionlistener(actionlistener l) It returns the currently set Action for this ActionEvent source, or null if no Action is set. It is used to set the current font. It is used to remove the specified action listener so that it no longer receives action events from this textfield. Java JTextField Example import javax.swing.*; class TextFieldExample public static void main(string args[]) JFrame f= new JFrame("TextField Example"); JTextField t1,t2; t1=new JTextField("Welcome to Java"); t1.setbounds(50,100, 200,30); t2=new JTextField("AWT Tutorial"); t2.setbounds(50,150, 200,30); f.add(t1); f.add(t2); f.setsize(400,400); f.setlayout(null); f.setvisible(true); Chethan Raj C, Assistant Professor Dept. of CSE Page 73

74 Output: Java JTextField Example with ActionListener import javax.swing.*; import java.awt.event.*; public class TextFieldExample implements ActionListener JTextField tf1,tf2,tf3; JButton b1,b2; TextFieldExample() JFrame f= new JFrame(); tf1=new JTextField(); tf1.setbounds(50,50,150,20); tf2=new JTextField(); tf2.setbounds(50,100,150,20); tf3=new JTextField(); tf3.setbounds(50,150,150,20); Chethan Raj C, Assistant Professor Dept. of CSE Page 74

75 tf3.seteditable(false); b1=new JButton("+"); b1.setbounds(50,200,50,50); b2=new JButton("-"); b2.setbounds(120,200,50,50); b1.addactionlistener(this); b2.addactionlistener(this); f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2); f.setsize(300,300); f.setlayout(null); f.setvisible(true); public void actionperformed(actionevent e) String s1=tf1.gettext(); String s2=tf2.gettext(); int a=integer.parseint(s1); int b=integer.parseint(s2); int c=0; if(e.getsource()==b1) c=a+b; else if(e.getsource()==b2) c=a-b; String result=string.valueof(c); Chethan Raj C, Assistant Professor Dept. of CSE Page 75

76 tf3.settext(result); public static void main(string[] args) new TextFieldExample(); Output: JTextField class is used to create a textfield control, which allows a user to enter a single line text and edit it. When an enter key is pressed in a JTextField, an ActionEvent is generated. In order to handle such event, ActionListener interface should be implemented. JTextField is a component which extends TextComponent class, which further extends JComponent class. Constructors of JTextField Constructor public JTextField) public JTextField(String text) public JTextField(int width) public JTextField(String text, int width) Description Creates a JTextField. Creates a JTextField with a specified default text. Creates a JTextField with a specified width. Creates a JTextField with a specified default text and width. Chethan Raj C, Assistant Professor Dept. of CSE Page 76

77 Some methods of JTextField class Object Oriented Programming Concepts-15CS45 Methods public void settext(string text) public String gettext() public void seteditable(boolean b) public void setfont(font f) void setforeground(color c) Description Sets a String message on the JTextField. Gets a String message of JTextField. Sets a Sets a JTextfield to editable or uneditable. Sets a font type to the JTextField Sets a foreground color, i.e. color of text in JTextField. An example of different kinds of JTextField import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TextField2 public static void main(string args[]) SwingUtilities.invokeLater(new Runnable() public void run() new A(); ); //Closing the main method //Closing the class A class A //implements ActionListener JButton button; JLabel label1, label2, label3, label4, label5; JTextField field1, field2, field3, field4, field5; String str =""; JFrame jf; Chethan Raj C, Assistant Professor Dept. of CSE Page 77

78 A() jf = new JFrame("Hello"); jf.setsize(440,150); Object Oriented Programming Concepts-15CS45 label1= new JLabel("First Textfield"); label2= new JLabel("Second Textfield "); label3= new JLabel("Third TextField"); label4= new JLabel("Fourth TextField"); label5= new JLabel("Fifth TextField"); field1 = new JTextField(); //calling TextField() constructor field2 = new JTextField("World peace is important"); //calling TextField(String) Constructor field3 = new JTextField(5); //calling TextField(int) constructor field4 = new JTextField("Smile and spread it",15); //calling TextField(String, int) constructor //Setting the font color to blue, in a JTextField field2.setforeground(color.blue); field4.seteditable(false); //Making a text field uneditable field4.setfont(new Font("Serif", Font.BOLD, 10)); //Setting a font style in a TextField jf.setlayout(new FlowLayout()); jf.add(label1); jf.add(field1); jf.add(label2); jf.add(field2); jf.add(label3); jf.add(field3); jf.add(label4); jf.add(field4); //button.addactionlistener(this); jf.setvisible(true); When you run the code, you are presented a window shown below -: Chethan Raj C, Assistant Professor Dept. of CSE Page 78

79 Figure 1 Handling JTextField events and reading from JTextField. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TextField3 public static void main(string args[]) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method //Closing the class A class A implements ActionListener JButton button; JLabel label1, label2, label3; JTextField field1, field2, field3; JFrame jf; A() jf = new JFrame("Handling TextField Event"); jf.setsize(400,150); label1= new JLabel("Enter your name"); Chethan Raj C, Assistant Professor Dept. of CSE Page 79

80 label2= new JLabel("Enter your city"); label3= new JLabel("Enter your age"); field1 = new JTextField(20); field2 = new JTextField(20); //calling TextField(String) field3 = new JTextField(20); button = new JButton("Submit"); jf.setlayout(new FlowLayout()); jf.add(label1); jf.add(field1); jf.add(label2); jf.add(field2); jf.add(label3); jf.add(field3); jf.add(button); button.addactionlistener(this); //As soon as button is clicked, data from all the textfields is read jf.setvisible(true); public void actionperformed(actionevent ae) if(ae.getactioncommand().equals("submit")) System.out.println("Your name : " + field1.gettext()+ ", Your city : " + field2.gettext()+ ", Your age :" + field3.gettext()); When you run the code, you are presented a window shown in the Figure2 below -: Figure 2 Chethan Raj C, Assistant Professor Dept. of CSE Page 80

81 User may enter the data in the each textfield. Figure 3 and this data is read and displayed on command prompt, as soon as you press Enter Key in any of the textfield, as shown below. Enter Key is pressed Your name : Anuj Sobti, Your city : New York, Your age :29 The Swing Buttons JButton class is used to create a push button control, which can generate an ActionEvent when it is clicked. In order to handle a button click event, ActionListener interface should be implemented. JButton is a component which extends JComponent class and it can be added to the container. Constructors of JButton Constructor public JButton() public JButton(String text) public JButton(Icon image) public JButton(String text, Icon image) Description Creates a button with no text on it.. Creates a button with a text on it. Creates a button with an icon on it. Creates a button with a text and and an icon on it. Methods of JButton class Methods public void settext(string text) public String gettext() public void seticon(icon icon) Description Sets a String message on the JButton. Gets a String message of JButton. Sets an icon or image over the JButton. Chethan Raj C, Assistant Professor Dept. of CSE Page 81

82 public Icon geticon() void sethorizontaltextposition(int textposition) void setverticaltextposition(int textposition) Gets the icon or image of the JButton. Sets the button message on the LEFT/RIGHT of its icon or image. Sets the button message on the TOP/BOTTOM of its icon or image. An example of JButton import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Btn1 public static void main(string args[]) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method //Closing the class A class A //implements ActionListener JFrame jf; JButton button1, button2, button3; A() jf= new JFrame(); button1= new JButton(); button2= new JButton("Click here"); button3= new JButton(); button3.settext("button3"); Chethan Raj C, Assistant Professor Dept. of CSE Page 82

83 jf.add(button1); jf.add(button2); jf.add(button3); jf.setlayout(new FlowLayout()); jf.setsize(300,100); jf.setvisible(true); When you run the code, you are presented a window shown below -: Setting an image over JButton import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.border.emptyborder; public class Btn4 public static void main(string... ar) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method //Closing the class A class A JFrame jf; JButton button1, button2, button3, button4; Figure 1 Chethan Raj C, Assistant Professor Dept. of CSE Page 83

84 A() jf= new JFrame(); Object Oriented Programming Concepts-15CS45 //Setting an image over a JButton and limited its border space, so that image fits perfectly over JButton. button1= new JButton(new ImageIcon("JButton1.jpg")); button1.setborder(new EmptyBorder(2,2,2,2)); //Setting an image over a JButton with and without text. button2 = new JButton(new ImageIcon("Smiley3.jpg")); button3 = new JButton("Smiley", new ImageIcon("Smiley3.jpg")); //Setting a big image over a JButton button4 = new JButton(new ImageIcon("Big Smiley", "BigSmiley.gif")); button4.sethorizontaltextposition(swingconstants.left); jf.add(button1); jf.add(button2); jf.add(button3); jf.add(button4); jf.setlayout(new FlowLayout()); jf.setsize(300,300); jf.setvisible(true); When you run the code, you are presented a window shown in the Figure2 below -: Figure 2 Chethan Raj C, Assistant Professor Dept. of CSE Page 84

85 Handling button click events by implementing ActionListener interface import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Btn5 public static void main(string args[]) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method //Closing the class A class A implements ActionListener JFrame jf; JButton button1, button2; JLabel label; A() jf= new JFrame(); button1= new JButton("Yes"); button2= new JButton("No"); label = new JLabel(); jf.add(button1); jf.add(button2); jf.add(label); button1.addactionlistener(this); button2.addactionlistener(this); jf.setlayout(new FlowLayout(FlowLayout.CENTER,60,10)); jf.setsize(250,150); jf.setvisible(true); Chethan Raj C, Assistant Professor Dept. of CSE Page 85

86 public void actionperformed(actionevent ae) if(ae.getactioncommand().equals("yes")) label.settext("you've clicked Yes"); jf.add(label); jf.setvisible(true); System.out.println("Yes button is clicked"); if(ae.getactioncommand().equals("no")) label.settext("you've clicked No"); jf.add(label); jf.setvisible(true); System.out.println("No button is clicked"); When you run the code, you are presented a window shown in the Figure3 below -: Figure 3 When you click on any of the buttons, you will be displayed an appropriate message, for example, when we click on Yes button, we get such message - Figure 4 Chethan Raj C, Assistant Professor Dept. of CSE Page 86

87 Button class Object Oriented Programming Concepts-15CS45 Button class is used to create a push button control, which can generate an ActionEvent when it is clicked. In order to handle a button click event, ActionListener interface should be implemented. Button is a component which extends JComponent class and it can be added to the container like Frame or a component like Panel. Constructors of Button Constructor public Button() public Button(String text) Description Creates a button with no text on it. Creates a button with a text on it. Methods of Button class Methods Description public void settext(string text) Sets a String message on the Button. public String gettext() Gets a String message of Button. public void setlabel() Sets a String text on button. public String getlabel() Gets the String text of this button. An example of Button import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ButtonEx1 Frame jf; Button button1, button2, button3; ButtonEx1() jf= new JFrame("Frame displaying buttons"); button1= new Button(); button2= new Button("Click here"); button3= new Button(); button3.setlabel("button3"); jf.add(button1); jf.add(button2); Chethan Raj C, Assistant Professor Dept. of CSE Page 87

88 jf.add(button3); jf.setlayout(new FlowLayout()); jf.setsize(300,100); jf.setvisible(true); public static void main(string... ar) new ButtonEx1(); When you run the code, you are presented a window shown below -: Figure 1 Handling button click events by implementing ActionListener interface import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ButtonEx2 implements ActionListener Frame jf; Button button1, button2; Label label; ButtonEx2() jf= new Frame("Button click events"); button1= new Button("Yes"); button2= new Button("No"); label = new Label(); jf.add(button1); jf.add(button2); jf.add(label); button1.addactionlistener(this); Chethan Raj C, Assistant Professor Dept. of CSE Page 88

89 button2.addactionlistener(this); Object Oriented Programming Concepts-15CS45 jf.setlayout(new FlowLayout(FlowLayout.CENTER,60,10)); jf.setsize(250,150); jf.setvisible(true); public void actionperformed(actionevent ae) if(ae.getactioncommand().equals("yes")) label.settext("you've clicked Yes"); jf.add(label); jf.setvisible(true); if(ae.getactioncommand().equals("no")) label.settext("you've clicked No"); jf.add(label); jf.setvisible(true); public static void main(string... ar) new ButtonEx2(); When user run the code presented a window shown in the Figure2 below -: Figure 2 When user click on any of the buttons displayed an appropriate message, for example, when we click on Yes button, we get such message - Chethan Raj C, Assistant Professor Dept. of CSE Page 89

90 JTabbedpane Figure 3 The JTabbedPane class is used to switch between a group of components by clicking on a tab with a given title or icon. It inherits JComponent class. JTabbedPane class declaration Let's see the declaration for javax.swing.jtabbedpane class. 1. public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstan ts Commonly used Constructors: Constructor JTabbedPane() JTabbedPane(int tabplacement) JTabbedPane(int tabplacement, int tablayoutpolicy) Description Creates an empty TabbedPane with a default tab placement of JTabbedPane.Top. Creates an empty TabbedPane with a specified tab placement. Creates an empty TabbedPane with a specified tab placement and tab layout policy. Java JTabbedPane Example import javax.swing.*; public class TabbedPaneExample JFrame f; TabbedPaneExample() f=new JFrame(); JTextArea ta=new JTextArea(200,200); JPanel p1=new JPanel(); p1.add(ta); Chethan Raj C, Assistant Professor Dept. of CSE Page 90

91 JPanel p2=new JPanel(); JPanel p3=new JPanel(); JTabbedPane tp=new JTabbedPane(); tp.setbounds(50,50,200,200); tp.add("main",p1); tp.add("visit",p2); tp.add("help",p3); f.add(tp); f.setsize(400,400); f.setlayout(null); f.setvisible(true); public static void main(string[] args) new TabbedPaneExample(); Output: Object Oriented Programming Concepts-15CS45 javax.swing.jtabbedpane provides the feature to add tabs onto the frame in Java. Using tab user can switch to one component to another. Example Example to add tabs onto the frame. i.e how to add tabs into the JFrame and how to add components on each tabs. First creata Java Class named AddJTabbedPane.java into which create a method that describes the user interface. In this method user instantiated various Jlabel, JPanel. As well as instantiated JTabbedPane and JFrame. These labels are created for labeling the values which will be Chethan Raj C, Assistant Professor Dept. of CSE Page 91

92 displayed with the associated tabs. Then created a JFrame and added two tabs named 'Fruit' and 'Vegetable' onto the JFrame. Source Code import javax.swing.jtabbedpane; import javax.swing.jtextfield; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.jbutton; import javax.swing.jframe; import java.awt.*; import java.awt.event.*; class AddJTabbedPane JTabbedPane tp; JLabel lab1, lab2, lab3, lab4, lab5, lab6, lab7, lab8; JPanel fruit, vegetable; JFrame frame; public void createui() frame=new JFrame("JTabbedPane Example"); frame.setdefaultcloseoperation(jframe.exit_on_close); fruit = new JPanel(new GridLayout(6,2)); lab1=new JLabel("Apple"); lab2=new JLabel("Orange"); lab3=new JLabel("Papaya"); lab4=new JLabel("Pine Apple"); fruit.add(lab1); fruit.add(lab2); fruit.add(lab3); fruit.add(lab4); Chethan Raj C, Assistant Professor Dept. of CSE Page 92

93 vegetable = new JPanel(new GridLayout(6,2)); lab5=new JLabel("Cauliflower"); lab6=new JLabel("Brinjal"); lab7=new JLabel("Peas"); lab8=new JLabel("Lady finger"); vegetable.add(lab5); vegetable.add(lab6); vegetable.add(lab7); vegetable.add(lab8); tp=new JTabbedPane(); Container pane = frame.getcontentpane(); pane.add(tp); tp.addtab("fruit",fruit); tp.addtab("vegetable",vegetable); frame.setsize(200,200); frame.setvisible(true); public static void main(string[] args) AddJTabbedPane tbp = new AddJTabbedPane(); tbp.createui(); Chethan Raj C, Assistant Professor Dept. of CSE Page 93

94 Output When you will execute the above example you will get the output as follows : And the Frame will be look like as follows : And when you will switch to Vegetable tab then the vegetable's name will be displayed. JScrollPane JScrollPane provides a scrollable view of a component, where a component maybe an image, table, tree etc. A JScrollPane can be added to a top-level container like JFrame or a component like JPanel. JScrollPane is another lightweight component which extends JComponent class. Constructors of JScrollPane Constructor public JScrollPane() public JScrollPane(Component view) Description Creates an empty JScrollPane with no viewport, where both the horizontal and vertical scrollbars appearing when required. Creates a JScrollPane that displays a component within it. Chethan Raj C, Assistant Professor Dept. of CSE Page 94

95 This JScrollPane also shows the horizontal and vertical bar, only when its component's contents are larger than the viewing area. Methods of JScrollPane class Methods public setpreferredsize(dimension d) public int setlayout(layoytmanager managaer) Description Sets the preferred size of JScrollPane. Sets the layout manager for JScrollPane. An example of JScrollPane import javax.swing.*; import java.awt.*; public class ScrollPane1 public static void main(string... ar) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method //Closing the class Combo class A //implements ActionListener JFrame jf; JPanel jp; JLabel label1; A() jf = new JFrame("JScrollPane"); label1 = new JLabel("Displaying a picture ",JLabel.CENTER); //Creating an ImageIcon object to create a JLabel with image Chethan Raj C, Assistant Professor Dept. of CSE Page 95

96 ImageIcon image = new ImageIcon("nature.jpg"); JLabel label = new JLabel(image, JLabel.CENTER); //Creating a JPanel and adding JLabel that contains the image jp = new JPanel(new BorderLayout()); jp.add( label, BorderLayout.CENTER ); //Adding JPanel to JScrollPane JScrollPane scrollp = new JScrollPane(jp); //Adding JLabel and JScrollPane to JFrame jf.add(label1,borderlayout.north); jf.add(scrollp,borderlayout.center); jf.setsize(350,270); jf.setvisible(true); When you run the code, you are presented a window that shows an image with a horizontal and a vertical scroll bar. Figure 1 Displaying two images with their individuals JScrollPane. In the next code, we are going to display two images within a JFrame and each of these image has a JScrollpane attached to it. import javax.swing.*; import java.awt.*; public class ScrollPane3 Chethan Raj C, Assistant Professor Dept. of CSE Page 96

97 public static void main(string args[]) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method //Closing the class Combo class A Object [] index; JFrame jf; JPanel jp1, jp2; JLabel label; A() jf = new JFrame("JScrollPane"); jp1 = new JPanel(); label = new JLabel("Displaying two images ",JLabel.CENTER); ImageIcon image1 = new ImageIcon("nature.jpg"); JLabel label1= new JLabel(image1, JLabel.CENTER); jp1 = new JPanel(new BorderLayout()); jp1.add( label1, BorderLayout.CENTER ); JScrollPane scrollp1 = new JScrollPane(jp1); scrollp1.setpreferredsize(new Dimension(300, 190)); ImageIcon image2 = new ImageIcon("nature2.jpg"); JLabel label2 = new JLabel(image2, JLabel.CENTER); jp2 = new JPanel(new BorderLayout()); jp2.add( label2, BorderLayout.CENTER); JScrollPane scrollp2 = new JScrollPane(jp2); scrollp2.setpreferredsize(new Dimension(300, 190)); jf.add(label,borderlayout.north); jf.add(scrollp1,borderlayout.center); Chethan Raj C, Assistant Professor Dept. of CSE Page 97

98 jf.add(scrollp2,borderlayout.east); jf.setsize(600,270); jf.setvisible(true); When you run the code, you are presented a window that shows two images, with their own JScrollPane giving them horizontal and vertical bars. Figure 2 JScrollPane with JTable import javax.swing.*; import java.awt.*; import javax.swing.table.tablemodel; import javax.swing.table.defaulttablemodel; import javax.swing.table.defaulttablecellrenderer; public class ScrollPane5 public static void main(string args[]) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method //Closing the class Combo Chethan Raj C, Assistant Professor Dept. of CSE Page 98

99 class A String [] index; JFrame jf; DefaultTableModel dtablemodel; JTable table1; JLabel label1; JPanel jp; Object Oriented Programming Concepts-15CS45 A() index= new String[]"Rank", "Country", "Forested Area(km sq)", "% of land area"; jf= new JFrame("JScrollPane with JTable"); label1 = new JLabel("Top 10 countries with most forested area",jlabel.center); Object[][] rawdata = new Object[] [] "1", "Russia", "8,149,300", "49.40%", "2", "Canada", "4.196,438", "49.24%", "3", "Brazil", "4,777,980", "56.10%", "4", "United States", "2,083,210", "33%", "5", "China", "2,083,210", "21.83", "6", "Congo", "1,819,326", "50%", "7", "Australia", "1,147,832", "19.90%", "8", "Argentina", "945,336", "34%", "9", "Indonesia", "884,950", "46.46%", "10", "India", "778,424", "24.68%", ; //creating a DeFaultTableModel object, which is subclass of TableModel dtablemodel = new DefaultTableModel(rawData, index); //Initializing a JTable from DefaultTableModel. table1 = new JTable(dTableModel); //Adjusting the contents of each cell of JTable in CENTER DefaultTableCellRenderer tablerenderer = new DefaultTableCellRenderer(); tablerenderer.sethorizontalalignment(jlabel.center); //Aligning the table data centrally. table1.setdefaultrenderer(object.class, tablerenderer); //Creating a JPanel, setting it layout to BorderLayout and adding JTable to it. jp= new JPanel(new BorderLayout()); jp.add(table1, BorderLayout.CENTER); //Creating a JScrollPane and adding its functionalities to JPanel Chethan Raj C, Assistant Professor Dept. of CSE Page 99

100 JScrollPane scrollp = new JScrollPane(jp); //Adding a JLabel and JScrollPane to JFrame. jf.add(label1, BorderLayout.NORTH); jf.add(scrollp,borderlayout.center); jf.setsize(320,200); jf.setvisible(true); When user run the code presented a window shows us a table displaying the top 10 countries with the maximum forested area. User created a JTable with a JScrollPane attached to it, giving it the horizontal and vertical bars(when required). JList Figure 3 JList class is used to create a list with multiple values, allowing a user to select any of these values. When a value is selected from JList, a ListSelectionEvent is generated, which is handled by implementing ListSelectionListener interface. JList is another lightweight component which extends JComponent class. Constructors of JList Constructor public JList() public JList(E[] items) public JList(ListModel <E>) Description Creates a JList with an empty, read-only, model. Creates a JList that is populated with the items of specfied array. Creates a JList that displays elements from the specified ListModel. Chethan Raj C, Assistant Professor Dept. of CSE Page 100

101 Methods of JList class Object Oriented Programming Concepts-15CS45 Methods public void addlistselectionlistener(listselectionlistener listener) public void clearselection() public E getselectedvalue()) Description Gets a String message of JList. Appends the text to the JList. Gets the total number of rows in JList. An example of JList import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class List1 public static void main(string args[]) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method //Closing the class Combo class A String [] seasons; JFrame jf; JList<String> list; JLabel label1; A() seasons= new String[]"Spring", "Summer", "Monsoon", "Autumn", "Winter"; jf= new JFrame("JList"); list= new JList<String>(seasons); label1 = new JLabel("Select your favorite season from the list :"); Chethan Raj C, Assistant Professor Dept. of CSE Page 101

102 jf.add(label1); jf.add(list); jf.setlayout(new FlowLayout()); jf.setsize(260,200); jf.setvisible(true); When user run the code presented a window shown below -: Figure 1 Creating and initializing a JList from an existing ListModel In the given program user is handle events when a JRadioButton is checked or unchecked. In the next code, user combined a JRadioButton with a JLabel to add an icon/image next to a radiobutton. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class List2 public static void main(string args[]) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method Chethan Raj C, Assistant Professor Dept. of CSE Page 102

103 //Closing the class Combo class A //implements ActionListener String [] continents; JFrame jf; DefaultListModel<String> list1; JList<String> list2; JLabel label1; Object Oriented Programming Concepts-15CS45 A() list1= new DefaultListModel<String>(); list1.addelement("asia"); list1.addelement("africa"); list1.addelement("north America"); list1.addelement("south America"); list1.addelement("antarctica"); list1.addelement("europe"); list1.addelement("australia"); list2= new JList<String>(list1); jf= new JFrame("JList"); label1= new JLabel("Name of all the continents in the world -"); jf.add(label1); jf.add(list2); jf.setlayout(new FlowLayout()); jf.setsize(300,250); jf.setvisible(true); When user run the code presented a window shown in the Figure2. This window displays a list containing all the continents in our world -: Chethan Raj C, Assistant Professor Dept. of CSE Page 103

104 Handling JList events import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.event.listselectionlistener; import javax.swing.event.listselectionevent; public class list3 public static void main(string args[]) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method //Closing the class Combo4 class A implements ListSelectionListener String [] fav; JFrame jf; JList<String> list; JLabel label1, label2; Figure 2 A() fav = new String[]"USA", "Switzerland", "India", "New Zealand", "Iceland"; Chethan Raj C, Assistant Professor Dept. of CSE Page 104

105 jf= new JFrame("JList"); list= new JList<String>(); label1 = new JLabel("Please select a country to visit"); label2 = new JLabel(); jf.add(label1); jf.add(list); jf.add(label2); list.addlistselectionlistener(this); jf.setlayout(new FlowLayout()); jf.setsize(250,200); jf.setvisible(true); public void valuechanged(listselectionevent e) if (!e.getvalueisadjusting()) label2.settext( (String)list.getSelectedValue() + " is selected from the list"); When user run the code presented a window shown in the Figure3. In this window user is asked to select one of the countries in the list that user would like to visit -: Figure 3 as soon as we clicked on the item Iceland, the window shows that we have selected the item Icelandfrom the list, shown in the figure below- Chethan Raj C, Assistant Professor Dept. of CSE Page 105

106 Figure 4 List class List class is used to create a list with multiple values, allowing a user to select any of the values. When a value is selected from List, an ItemEvent is generated, which is handled by implementing ItemListener interface. List is another component in AWT which extends Componentclass. Constructors of List Constructor public List() public List(int rows) public List(int rows, boolean mode) Description Creates a scrolling list. Creates a List with a number of rows. Creates a List with a number of rows, allowing us to select multiple values from list if mode is true. Methods of List class Methods public void add(string item) public void add(string item, int index) public void addactionlistener(actionlistener al) public void additemlistener(itemlistener al) public String getitem( int index) Description Adds the item to the end of List. Adds the item at a specific index in the list. Adds a specific ActionListener to listen an Action event generated when item is selected from this list. Adds a specific ItemListener to listen an Item event generated when item is selected from this list. Gets an item from a specific index in the list. Chethan Raj C, Assistant Professor Dept. of CSE Page 106

107 public String getselecteditem() Gets the selected item in the list. public String[] getselecteditems() Gets the selected item in the list. public int getrows() Gets the total number of rows in the list. An example of List, where you can select one item from the list. Program to create a list of sports with 7 items, user can only select one item from the list. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ListEx1 String [] seasons; Frame jf; List list; Label label1; ListEx1() jf= new Frame("List"); list= new List(7); label1 = new Label("Select your favorite sports from the list :"); list.add("badminton"); list.add("hockey"); list.add("tennis"); list.add("football"); list.add("cricket"); list.add("formula One"); list.add("rugby"); jf.add(label1); jf.add(list); jf.setlayout(new FlowLayout()); jf.setsize(260,220); jf.setvisible(true); public static void main(string... ar) Chethan Raj C, Assistant Professor Dept. of CSE Page 107

108 new ListEx1(); When user run the code presented a window displaying a list of sports, asking you to select your favorite one from the list. We have selected Tennis from the list. -: Figure 1 An example of List, where you can select multiple items from the list. Program to create a list of seasons with 5 items, user can only multiple items from the list. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ListEx2 String [] seasons; Frame jf; List list; Label label1; ListEx2() jf= new Frame("List"); //Creating a list with 5 items and boolean true allows us to select multiple items in the list. list= new List(5, true); label1 = new Label("Select your favorite seasons from the list :"); Chethan Raj C, Assistant Professor Dept. of CSE Page 108

109 list.add("spring"); list.add("summer"); list.add("monsoon"); list.add("autumn"); list.add("winter"); jf.add(label1); jf.add(list); jf.setlayout(new FlowLayout()); jf.setsize(260,200); jf.setvisible(true); public static void main(string... ar) new ListEx2(); When user run the code presented a window displaying a list of seasons, asking you to select your favorite seasons from the list. User as selected Spring and Monsoon from the list. -: Figure 2 Handling List events when one item can be selected in the list import javax.swing.*; import java.awt.*; import java.awt.event.*; Chethan Raj C, Assistant Professor Dept. of CSE Page 109

110 public class ListEx4 implements ItemListener Frame jf; List list; Label label1, label2; ListEx4() jf= new Frame("List"); list= new List(8); list.add("red"); list.add("black"); list.add("blue"); list.add("yellow"); list.add("green"); list.add("gray"); list.add("turquoise"); list.add("purple"); label1 = new Label("Please select your favorite color", Label.CENTER); label2 = new Label(); jf.add(label1); jf.add(list); jf.add(label2); //Registering class ListEx3 to listen to an ItemEvent, generated when an item in the list is selected. list.additemlistener(this); jf.setlayout(new FlowLayout()); jf.setsize(280,240); jf.setvisible(true); public void itemstatechanged(itemevent e) List l = (List)e.getSource(); label2.settext("you have selected "+ l.getselecteditem()); jf.setvisible(true); public static void main(string... ar) new ListEx4(); Chethan Raj C, Assistant Professor Dept. of CSE Page 110

111 When user run the code presented a window shown in the Figure3. In this window you are asked to select one of colors from the list -: Figure 3 User has selected item Blue from the list and hence this selected item is notified to us, shown in the figure below Figure4 Handling List events when multiple items can be selected in the list. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ListEx4 implements ItemListener Frame jf; Chethan Raj C, Assistant Professor Dept. of CSE Page 111

112 List list; Label label1, label2; ListEx5() jf= new Frame("List"); list= new List(8,true); list.add("red"); list.add("black"); list.add("blue"); list.add("yellow"); list.add("green"); list.add("gray"); list.add("turquoise"); list.add("purple"); Object Oriented Programming Concepts-15CS45 label1 = new Label("Please select your favorite color", Label.CENTER); label2 = new Label(); jf.add(label1); jf.add(list); jf.add(label2); //Registering class ListEx4 to listen to an ItemEvent, generated when an item in the list is selected. list.additemlistener(this); jf.setlayout(new FlowLayout()); jf.setsize(280,240); jf.setvisible(true); public void itemstatechanged(itemevent e) String selected=""; List l = (List)e.getSource(); String str[]= l.getselecteditems(); for(string s: str) selected += s + " "; label2.settext("you have selected - "+ selected); jf.setvisible(true); public static void main(string... ar) Chethan Raj C, Assistant Professor Dept. of CSE Page 112

113 new ListEx4(); When user run the code presented a window shown in the Figure5. In this window you are asked to select one of colors from the list -: Figure 5 User selected item Blue and Turquoise from the list and hence these multiple selected items are notified to us, shown in the figure below JComboBox Figure6 JComboBox consists of an editable field and a drop-down list. A user can either select or edit any value from drop-drop list. JComboBox is a is a component which extends JComponent class and it can be added to a container like JFrame or a component like JPanel. Chethan Raj C, Assistant Professor Dept. of CSE Page 113

114 Constructors of JComboBox Object Oriented Programming Concepts-15CS45 Constructor public JComboBox() public JComboBox(E[] items) public JComboBox(ComboBoxModel <E>) Description Creates a JComboBox with a default data model. Creates a JComboBox that takes its items from an existing array. Creates a JComboBox that takes its items from an existing ComboBoxModel. Methods of JComboBox class Methods public void additem(e item) public Object getselecteditem() public void seteditable(boolean b) addactionlistener(actionlistener a) Description Adds an item to JComboBox. Gets the item selected by the user from JCombobox. Allows to edit the option selected from the dropdown list of items in JComboBox. Adds an ActionListener. An example of JComboBox import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class Combo public static void main(string... ar) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method //Closing the class Combo class A //implements ActionListener String [] BRICS; JFrame jf; Chethan Raj C, Assistant Professor Dept. of CSE Page 114

115 JComboBox<String> combo; A() BRICS = new String[]"Russia", "India", "South Africa", "Brazil", "China"; jf= new JFrame("JComboBox"); combo= new JComboBox<String>(BRICS); jf.add(combo); jf.setlayout(new FlowLayout()); jf.setsize(300,200); jf.setvisible(true); When user run the code presented a window shown below -: Figure 1 When user click on the arrow poiting down, and output are presented with a dropdown list, with its first option "Russia" preselected Figure 2 Chethan Raj C, Assistant Professor Dept. of CSE Page 115

116 Remember the last JCheckbox(ch4) will not be visible because its icon has covered it, but it is still a checkbox, just covered by its icon. Creating and initializing a JComboBox from an existing ComboBoxModel In the upcoming code, we are going to handle events when a JRadioButton is checked or unchecked. In the next code, we have also combined a JRadioButton with a JLabel to add an icon/image next to a radiobutton. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class Combo2 public static void main(string... ar) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method //Closing the class Combo class A //implements ActionListener String [] planets; JFrame jf; DefaultComboBoxModel<String> combo1; JComboBox<String> combo2; A() planets = new String[]"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Pluto"; combo1= new DefaultComboBoxModel<String>(planets); combo2= new JComboBox<String>(combo1); jf= new JFrame("JComboBox"); jf.add(combo2); Chethan Raj C, Assistant Professor Dept. of CSE Page 116

117 jf.setlayout(new FlowLayout()); jf.setsize(300,250); jf.setvisible(true); When user run the code and output are presented a window shown in the Figure3 below -: Figure 3 When user click on the arrow pointing down, you are presented with a dropdown list, with its first option "Mercury" preselected. Handling JComboBox events import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; Figure 4 Chethan Raj C, Assistant Professor Dept. of CSE Page 117

118 public class Combo4 public static void main(string... ar) SwingUtilities.invokeLater(new Runnable() public void run() new A(); ); //Closing the main method //Closing the class Combo4 class A implements ActionListener String [] BRICS; JFrame jf; JComboBox<String> combo; JLabel label1; A() BRICS = new String[]"Russia", "India", "South Africa", "Brazil", "China"; jf= new JFrame("JComboBox"); combo= new JComboBox<String>(BRICS); label1 = new JLabel(); jf.add(combo); combo.addactionlistener(this); jf.setlayout(new FlowLayout()); jf.setsize(210,200); jf.setvisible(true); public void actionperformed(actionevent ae) JComboBox cb = (JComboBox)ae.getSource(); label1.settext( ((String)cb.getSelectedItem()) + " is selected"); jf.add(label1); jf.setvisible(true); Chethan Raj C, Assistant Professor Dept. of CSE Page 118

119 When user run the code and are presented a window shown in the Figure5 below -: Figure 5 When user check a JComboBox an ActionEvent is fired and presented a message to display which option of JComboBox is selected. For example, when user select the option of South Africa from dropdown list of JComboBox, and are notified like - Creating an editable JComboBox import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class Combo5 public static void main(string args[]) SwingUtilities.invokeLater(new Runnable() public void run() new A(); Figure6 Chethan Raj C, Assistant Professor Dept. of CSE Page 119

120 //Closing the main method //Closing the class Combo5 class A implements ActionListener String [] planets; JFrame jf; JComboBox combo; JLabel label1; A() planets = new String[]"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Pluto"; jf= new JFrame("JComboBox"); combo= new JComboBox(planets); combo.seteditable(true); label1 = new JLabel(); jf.add(combo); combo.addactionlistener(this); jf.setlayout(new FlowLayout()); jf.setsize(210,250); jf.setvisible(true); public void actionperformed(actionevent ae) JComboBox cb = (JComboBox)ae.getSource(); label1.settext( ((String)cb.getSelectedItem()) + " is selected"); jf.add(label1); jf.setvisible(true); When you run the code, you are presented a window shown in the Figure7 below : Chethan Raj C, Assistant Professor Dept. of CSE Page 120

121 Figure 7 Notice that the first option Mercury is editable in the next figure-: Figure 8 Now user edited the first option Mercury to First Planet, in the figure 9. Figure 9 As soon as hit the Enter Key after editing the Mercury to First Planet, an ActionEvent is fired and output is presented a message to display which option of JComboBox is selected. For example, and in this example, user are notified like. Chethan Raj C, Assistant Professor Dept. of CSE Page 121

122 Program Description: Fig: Drop-Down List by using Java AWT package. The program uses the Choice class for creating a Drop-Down List. This program is also using add() method of the Choice class for add item to the list like "R", "INDIA" and "WELCOME". Choice():- This is the default constructor of Choice class. This creates simply a drop-down list. Here is the code of this program: import java.awt.*; import java.awt.event.*; public class ChoiceOptionExample public static void main(string[] args) Frame frame=new Frame("Choice"); Label label=new Label("What is your Choice:"); Choice choice=new Choice(); frame.add(label); frame.add(choice); choice.add("r"); choice.add("india"); choice.add("welcome"); frame.setlayout(new FlowLayout()); frame.setsize(250,150); frame.setvisible(true); Chethan Raj C, Assistant Professor Dept. of CSE Page 122

123 frame.addwindowlistener(new WindowAdapter() public void windowclosing(windowevent e) System.exit(0); Output this program: JTable JTable class is used to create a table with information displayed in multiple rows and columns. When a value is selected from JTable, a TableModelEvent is generated, which is handled by implementing TableModelListener interface. JTable is another lightweight component which extends JComponent class. Constructors of JTable Constructor public JTable() public JTable(int rows, int columns) public JTable(TableModel tm) Methods of JTable class Description Constructs a default JTable that is initialized with a default data model, a default column model, and a default selection model. Creates a JTable to display the values in rows and columns, using DefaultTableModel. Creates a JTable that is initialized with tm as the data model, default column model, and a default selection model. Methods Description Chethan Raj C, Assistant Professor Dept. of CSE Page 123

124 public TableModel getmodel() public int getrowcount() public int getcolumns() public void setdefaultrenderer(class <?> class, TableCellRenderer renderer) Gets the TableModel whose data is displayed by JTable. Gets the current total number of the rows in the JTable. Gets the current total number of the columns in the JTable. Sets the default cell renderer to be used to set the values, alignment, background of a cell in JTable An example of JTable import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.table.defaulttablecellrenderer; public class Table1 public static void main(string... ar) SwingUtilities.invokeLater(new Runnable() public void run() new A(); ); //Closing the main method //Closing the class Combo class A //implements ActionListener String [] index; JFrame jf; JTable table1, table2; JLabel label1, label2; A() index= new String[]"Rank", "Country", "GDP(millions of US$)"; jf= new JFrame("JTable"); label1 = new JLabel("Top 10 economies in the world"); Chethan Raj C, Assistant Professor Dept. of CSE Page 124

125 Object[][] rawdata = new Object[] [] "1", "USA", "$19.42 Trillion", "2", "China","$11.8 Trillion", "3", "Japan", "$4.84 Trillion", "4", "Germany", "$3.42 Trillion", "5", "United Kingdom", "$2.91 Trillion", "6", "India", "$2.45 Trillion", "7", "France", "$2.42 Trillion", "8", "Brazil", "$2.14 Trillion", "9", "Italy", "$1.81 Trillion", "10", "Canada", "$1.6 Trillion" ; table1 = new JTable(rawData, index); JScrollPane scrollp = new JScrollPane(table1); DefaultTableCellRenderer tablerenderer = new DefaultTableCellRenderer(); tablerenderer.sethorizontalalignment(jlabel.center); //Aligning the table data centrally. table1.setdefaultrenderer(object.class, tablerenderer); scrollp.setborder(borderfactory.createemptyborder()); //How to remove the border of JScrollPane. scrollp.setpreferredsize(new Dimension(400, 180)); //Setting the size of JScrollPane //Setting the label2 with message to show total number of rows and columns in JTable. label2 = new JLabel("Rows : " + table1.getrowcount() + ", Columns : "+ table1.getcolumncount() ); jf.add(label1); jf.add(scrollp); jf.add(label2); jf.setlayout(new FlowLayout()); jf.setsize(500,280); jf.setvisible(true); When user run the code, presented a window shown below -: Chethan Raj C, Assistant Professor Dept. of CSE Page 125

126 Figure 1 Creating and initializing a JTable from an existing TableModel In the code, user going to create a JTable by using its constructor that takes an object of TableModel object. We will create table using DefaultTableModel, which has implemented TableModelinterface and user use this table to create JTable. import javax.swing.*; import java.awt.*; import javax.swing.table.tablemodel; import javax.swing.table.defaulttablemodel; import javax.swing.table.defaulttablecellrenderer; public class Table4 public static void main(string args[]) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method //Closing the class Combo class A String [] index; JFrame jf; DefaultTableModel dtablemodel; Chethan Raj C, Assistant Professor Dept. of CSE Page 126

127 JTable table1; JLabel label1; A() index= new String[]"Rank", "Country", "Points"; jf= new JFrame("JTable"); label1 = new JLabel("Top 10 rankings in Football"); Object[][] rawdata = new Object[] [] "1", "Germany", "1609", "2", "Brazil","1603", "3", "Argentina", "1413", "4", "Portugal", "1332", "5", "Switzerland", "1329", "6", "Poland", "1319", "7", "Chile", "1250", "8", "Colombia", "1208", "9", "France", "1199", "10", "Belgium", "1194" ; //creating a DeFaultTableModel object, which is subclass of TableModel dtablemodel = new DefaultTableModel(rawData, index); //Initializing a JTable from DefaultTableModel. table1 = new JTable(dTableModel); //Adding JTable to JScrollPane to display it properly JScrollPane scrollp = new JScrollPane(table1); //Adjusting the contents of each cell of JTable in CENTER DefaultTableCellRenderer tablerenderer = new DefaultTableCellRenderer(); tablerenderer.sethorizontalalignment(jlabel.center); //Aligning the table data centrally. table1.setdefaultrenderer(object.class, tablerenderer); //Removing the unnecessary border of JScrollPane scrollp.setborder(borderfactory.createemptyborder()); //How to remove the border of JScrollPane. jf.add(label1); jf.add(scrollp); jf.setlayout(new FlowLayout()); jf.setsize(500,280); jf.setvisible(true); Chethan Raj C, Assistant Professor Dept. of CSE Page 127

128 When user run the code, output provides the window shown in the Figure2. This window displays a JTable showing the top 10 world rankings in Football Figure 2 Handling JTable events by implementing TableModelListener To handle the events occuring when a particular cell of JTable is selected or when it's value is changed, to handle such events, then implement TableModelListener interface and will provide implementation of its method tablechanged(). import javax.swing.*; import java.awt.*; import javax.swing.table.tablemodel; import javax.swing.event.tablemodelevent; import javax.swing.table.defaulttablemodel; import javax.swing.event.tablemodellistener; import javax.swing.table.defaulttablecellrenderer; public class Table5 public static void main(string... ar) SwingUtilities.invokeLater(new Runnable() public void run() new A(); //Closing the main method Chethan Raj C, Assistant Professor Dept. of CSE Page 128

129 //Closing the class Combo Object Oriented Programming Concepts-15CS45 class A implements TableModelListener String [] index; JFrame jf; JPanel jp; DefaultTableModel dtablemodel; JTable table1, table2; JLabel label1, label2; A() index= new String[]"Rank", "Country", "Points"; jf = new JFrame("JTable"); label1 = new JLabel("Top 10 rankings in Football"); label2 = new JLabel(""); Object[][] rawdata = new Object[] [] "1", "Germany", "1609", "2", "Brazil","1603", "3", "Argentina", "1413", "4", "Portugal", "1332", "5", "Switzerland", "1329", "6", "Poland", "1319", "7", "Chile", "1250", "8", "Colombia", "1208", "9", "France", "1199", "10", "Belgium", "1194" ; //creating a DeFaultTableModel object, which is subclass of TableModel dtablemodel = new DefaultTableModel(rawData, index); //Initializing a JTable from DefaultTableModel. table1 = new JTable(dTableModel); JScrollPane scrollp = new JScrollPane(table1); DefaultTableCellRenderer tablerenderer = new DefaultTableCellRenderer(); tablerenderer.sethorizontalalignment(jlabel.center); //Aligning the table data centrally. table1.setdefaultrenderer(object.class, tablerenderer); scrollp.setborder(borderfactory.createemptyborder()); //How to remove the border of JScrollPane. Chethan Raj C, Assistant Professor Dept. of CSE Page 129

130 scrollp.setpreferredsize(new Dimension(350, 180)); //Setting the size of JScrollPane jf.add(label1); jf.add(scrollp); jf.add(label2); //Registering our Jtable for event listening table1.getmodel().addtablemodellistener(this); jf.setlayout(new FlowLayout()); jf.setsize(400,340); jf.setvisible(true); public void tablechanged(tablemodelevent e) TableModel tabmodel= (TableModel)e.getSource(); int row = e.getfirstrow(); int column = e.getcolumn(); //Retrieving the value a specific row,column from the JTable and setting this value to JLabel, to show the selected or a new edited cell value. label2.settext( (String)tabModel.getValueAt(row,column)); jf.setvisible(true); When user run the code the output provides the window shown in the Figure 3, showing the top 10 rankings of international Football country name Figure 3 \ Now user selected and edited Poland to Polska and as soon as finished editing it, user notifed about the change in the window itself. Chethan Raj C, Assistant Professor Dept. of CSE Page 130

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Module 5 The Applet Class, Swings OOC 4 th Sem, B Div 2017-18 Prof. Mouna M. Naravani The Applet Class Types of Applets (Abstract Window Toolkit) Offers richer and easy to use interface than AWT. An Applet

More information

Module 5 Applets About Applets Hierarchy of Applet Life Cycle of an Applet

Module 5 Applets About Applets Hierarchy of Applet Life Cycle of an Applet About Applets Module 5 Applets An applet is a little application. Prior to the World Wide Web, the built-in writing and drawing programs that came with Windows were sometimes called "applets." On the Web,

More information

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Module 5 The Applet Class, Swings OOC 4 th Sem, B Div 2016-17 Prof. Mouna M. Naravani The Applet Class Types of Applets (Abstract Window Toolkit) Offers richer and easy to use interface than AWT. An Applet

More information

Unit 1- Java Applets. Applet Programming. Local Applet and Remote Applet ** Applet and Application

Unit 1- Java Applets. Applet Programming. Local Applet and Remote Applet ** Applet and Application Applet Programming Applets are small Java applications that can be accessed on an Internet server, transported over Internet, and can be automatically installed and run as a part of a web document. An

More information

SIMPLE APPLET PROGRAM

SIMPLE APPLET PROGRAM APPLETS Applets are small applications that are accessed on Internet Server, transported over Internet, automatically installed and run as a part of web- browser Applet Basics : - All applets are subclasses

More information

Java Applet Basics. Life cycle of an applet:

Java Applet Basics. Life cycle of an applet: Java Applet Basics Applet is a Java program that can be embedded into a web page. It runs inside the web browser and works at client side. Applet is embedded in a HTML page using the APPLET or OBJECT tag

More information

OBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613

OBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613 OBJECT ORIENTED PROGRAMMING Course 8 Loredana STANCIU loredana.stanciu@upt.ro Room B613 Applets A program written in the Java programming language that can be included in an HTML page A special kind of

More information

UNIT-2: CLASSES, INHERITANCE, EXCEPTIONS, APPLETS. To define a class, use the class keyword and the name of the class:

UNIT-2: CLASSES, INHERITANCE, EXCEPTIONS, APPLETS. To define a class, use the class keyword and the name of the class: UNIT-2: CLASSES, INHERITANCE, EXCEPTIONS, APPLETS 1. Defining Classes, Class Name To define a class, use the class keyword and the name of the class: class MyClassName {... If this class is a subclass

More information

UNIT -1 JAVA APPLETS

UNIT -1 JAVA APPLETS UNIT -1 JAVA APPLETS TOPICS TO BE COVERED 1.1 Concept of Applet Programming Local and Remote applets Difference between applet and application Preparing to write applets Building applet code Applet life

More information

PROGRAMMING LANGUAGE 2

PROGRAMMING LANGUAGE 2 1 PROGRAMMING LANGUAGE 2 Lecture 13. Java Applets Outline 2 Applet Fundamentals Applet class Applet Fundamentals 3 Applets are small applications that are accessed on an Internet server, transported over

More information

Java Applet & its life Cycle. By Iqtidar Ali

Java Applet & its life Cycle. By Iqtidar Ali Java Applet & its life Cycle By Iqtidar Ali Java Applet Basic An applet is a java program that runs in a Web browser. An applet can be said as a fully functional java application. When browsing the Web,

More information

9. APPLETS AND APPLICATIONS

9. APPLETS AND APPLICATIONS 9. APPLETS AND APPLICATIONS JAVA PROGRAMMING(2350703) The Applet class What is an Applet? An applet is a Java program that embedded with web content(html) and runs in a Web browser. It runs inside the

More information

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Module 5 The Applet Class, Swings OOC 4 th Sem, B Div 2016-17 Prof. Mouna M. Naravani The HTML APPLET Tag An applet viewer will execute each APPLET tag that it finds in a separate window, while web browsers

More information

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets Java Applets Road Map Introduction to Java Applets Review applets that ship with JDK Make our own simple applets Introduce inheritance Introduce the applet environment html needed for applets Reading:

More information

CSC System Development with Java Introduction to Java Applets Budditha Hettige

CSC System Development with Java Introduction to Java Applets Budditha Hettige CSC 308 2.0 System Development with Java Introduction to Java Applets Budditha Hettige Department of Statistics and Computer Science What is an applet? applet: a Java program that can be inserted into

More information

Contents 8-1. Copyright (c) N. Afshartous

Contents 8-1. Copyright (c) N. Afshartous Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 8-1 Chapter 8: Applets

More information

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a CBOP3203 An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled

More information

Java TM Applets. Rex Jaeschke

Java TM Applets. Rex Jaeschke Java TM Applets Rex Jaeschke Java Applets 1997 1998, 2009 Rex Jaeschke. All rights reserved. Edition: 3.0 (matches JDK1.6/Java 2) All rights reserved. No part of this publication may be reproduced, stored

More information

Introduction to Java Applets 12

Introduction to Java Applets 12 Introduction to Java Applets 12 Course Map This module discusses the support for applets by the JDK, and how applets differ from applications in terms of program form, operating context, and how they are

More information

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming Frameworks 1 Framework Set of cooperating classes/interfaces Structure essential mechanisms of a problem domain Programmer can extend framework classes, creating new functionality Example: Swing package

More information

An applet is called from within an HTML script with the APPLET tag, such as: <applet code="test.class" width=200 height=300></applet>

An applet is called from within an HTML script with the APPLET tag, such as: <applet code=test.class width=200 height=300></applet> 6 Java Applets 6.1 Introduction As has been previously discussed a Java program can either be run as an applet within a WWW browser (such as Microsoft Internet Explorer or Netscape Communicator) or can

More information

SNS COLLEGE OF ENGINEERING, Coimbatore

SNS COLLEGE OF ENGINEERING, Coimbatore SNS COLLEGE OF ENGINEERING, Coimbatore 641 107 Accredited by NAAC UGC with A Grade Approved by AICTE and Affiliated to Anna University, Chennai IT6503 WEB PROGRAMMING UNIT 04 APPLETS Java applets- Life

More information

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 9: Writing Java Applets. Introduction

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 9: Writing Java Applets. Introduction INTRODUCTION TO COMPUTER PROGRAMMING Richard Pierse Class 9: Writing Java Applets Introduction Applets are Java programs that execute within HTML pages. There are three stages to creating a working Java

More information

CS2 Advanced Programming in Java note 8

CS2 Advanced Programming in Java note 8 CS2 Advanced Programming in Java note 8 Java and the Internet One of the reasons Java is so popular is because of the exciting possibilities it offers for exploiting the power of the Internet. On the one

More information

Graphics Applets. By Mr. Dave Clausen

Graphics Applets. By Mr. Dave Clausen Graphics Applets By Mr. Dave Clausen Applets A Java application is a stand-alone program with a main method (like the ones we've seen so far) A Java applet is a program that is intended to transported

More information

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application Last Time v We created our first Java application v What are the components of a basic Java application? v What GUI component did we use in the examples? v How do we write to the standard output? v An

More information

(Refer Slide Time: 02:01)

(Refer Slide Time: 02:01) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #29 Java Applets Part: 2 In this lecture we shall be continuing

More information

G51PRG: Introduction to Programming Second semester Applets and graphics

G51PRG: Introduction to Programming Second semester Applets and graphics G51PRG: Introduction to Programming Second semester Applets and graphics Natasha Alechina School of Computer Science & IT nza@cs.nott.ac.uk Previous two lectures AWT and Swing Creating components and putting

More information

PESIT Bangalore South Campus

PESIT Bangalore South Campus INTERNAL ASSESSMENT TEST II Date : 20-09-2016 Max Marks: 50 Subject & Code: JAVA & J2EE (10IS752) Section : A & B Name of faculty: Sreenath M V Time : 8.30-10.00 AM Note: Answer all five questions 1) a)

More information

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages. 1 CS257 Computer Science I Kevin Sahr, PhD Lecture 14: Graphical User Interfaces Command-Line Applications 2 The programs we've explored thus far have been text-based applications A Java application is

More information

PESIT Bangalore South Campus

PESIT Bangalore South Campus PESIT Bangalore South Campus 15CS45 : OBJECT ORIENTED CONCEPTS Faculty : Prof. Sajeevan K, Prof. Hanumanth Pujar Course Description: No of Sessions: 56 This course introduces computer programming using

More information

Chapter 7 Applets. Answers

Chapter 7 Applets. Answers Chapter 7 Applets Answers 1. D The drawoval(x, y, width, height) method of graphics draws an empty oval within a bounding box, and accepts 4 int parameters. The x and y coordinates of the left/top point

More information

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Graphics & Applets CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Back to Chapter

More information

HTML Links Tutorials http://www.htmlcodetutorial.com/ http://www.w3.org/markup/guide/ Quick Reference http://werbach.com/barebones/barebones.html Applets A Java application is a stand-alone program with

More information

Graphics Applets. By Mr. Dave Clausen

Graphics Applets. By Mr. Dave Clausen Graphics Applets By Mr. Dave Clausen Applets A Java application is a stand-alone program with a main method (like the ones we've seen so far) A Java applet is a program that is intended to transported

More information

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics Topic 9: Swing Outline Swing = Java's GUI library Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 7: Expand moving shapes from Assignment 4 into game. "Programming

More information

Windows and Events. created originally by Brian Bailey

Windows and Events. created originally by Brian Bailey Windows and Events created originally by Brian Bailey Announcements Review next time Midterm next Friday UI Architecture Applications UI Builders and Runtimes Frameworks Toolkits Windowing System Operating

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware

More information

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Using the API: Introductory Graphics Java Programming 1 Lesson 8 Using the API: Introductory Graphics Java Programming 1 Lesson 8 Using Java Provided Classes In this lesson we'll focus on using the Graphics class and its capabilities. This will serve two purposes: first

More information

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1,

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1, Java - Applets C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1, 5.3.2. Java is not confined to a DOS environment. It can run with buttons and boxes in a Windows

More information

Chapter 3 - Introduction to Java Applets

Chapter 3 - Introduction to Java Applets 1 Chapter 3 - Introduction to Java Applets 2 Introduction Applet Program that runs in appletviewer (test utility for applets) Web browser (IE, Communicator) Executes when HTML (Hypertext Markup Language)

More information

Java Applets / Flash

Java Applets / Flash Java Applets / Flash Java Applet vs. Flash political problems with Microsoft highly portable more difficult development not a problem less so excellent visual development tool Applet / Flash good for:

More information

Programming In Java Prof. Debasis Samanta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming In Java Prof. Debasis Samanta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming In Java Prof. Debasis Samanta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 06 Demonstration II So, in the last lecture, we have learned

More information

Prashanth Kumar K(Head-Dept of Computers)

Prashanth Kumar K(Head-Dept of Computers) B.Sc (Computer Science) Object Oriented Programming with Java and Data Structures Unit-IV 1 1. What is Thread? Thread is a task or flow of execution that can be made to run using time-sharing principle.

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware

More information

MULTIMEDIA PROGRAMMING IN JAVA. Prof.Asoc. Alda Kika Department of Informatics Faculty of Natural Sciences University of Tirana

MULTIMEDIA PROGRAMMING IN JAVA. Prof.Asoc. Alda Kika Department of Informatics Faculty of Natural Sciences University of Tirana MULTIMEDIA PROGRAMMING IN JAVA Prof.Asoc. Alda Kika Department of Informatics Faculty of Natural Sciences University of Tirana Objectives Applets in Java Getting, displaying and scaling the image How to

More information

Computer Science 210: Data Structures. Intro to Java Graphics

Computer Science 210: Data Structures. Intro to Java Graphics Computer Science 210: Data Structures Intro to Java Graphics Summary Today GUIs in Java using Swing in-class: a Scribbler program READING: browse Java online Docs, Swing tutorials GUIs in Java Java comes

More information

Programming graphics

Programming graphics Programming graphics Need a window javax.swing.jframe Several essential steps to use (necessary plumbing ): Set the size width and height in pixels Set a title (optional), and a close operation Make it

More information

Java History. Java History (cont'd)

Java History. Java History (cont'd) Java History Created by James Gosling et. al. at Sun Microsystems in 1991 "The Green Team" Investigate "convergence" technologies Gosling created a processor-independent language for StarSeven, a 2-way

More information

CSD Univ. of Crete Fall Java Applets

CSD Univ. of Crete Fall Java Applets Java Applets 1 Applets An applet is a Panel that allows interaction with a Java program Typically embedded in a Web page and can be run from a browser You need special HTML in the Web page to tell the

More information

Applets as front-ends to server-side programming

Applets as front-ends to server-side programming Applets as front-ends to server-side programming Objectives Introduce applets Examples of Java graphical programming How-to put an applet in a HTML page The HTML Applet tag and alternatives Applet communication

More information

Page 1 of 7. public class EmployeeAryAppletEx extends JApplet

Page 1 of 7. public class EmployeeAryAppletEx extends JApplet CS 209 Spring, 2006 Lab 9: Applets Instructor: J.G. Neal Objectives: To gain experience with: 1. Programming Java applets and the HTML page within which an applet is embedded. 2. The passing of parameters

More information

Here is a list of a few of the components located in the AWT and Swing packages:

Here is a list of a few of the components located in the AWT and Swing packages: Inheritance Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. Programming In A Graphical Environment Java is specifically designed

More information

UCLA PIC 20A Java Programming

UCLA PIC 20A Java Programming UCLA PIC 20A Java Programming Instructor: Ivo Dinov, Asst. Prof. In Statistics, Neurology and Program in Computing Teaching Assistant: Yon Seo Kim, PIC University of California, Los Angeles, Summer 2002

More information

Summary. 962 Chapter 23 Applets and Java Web Start

Summary. 962 Chapter 23 Applets and Java Web Start 962 Chapter 23 Applets and Java Web Start Summary Section 23.1 Introduction Applets (p. 942) are Java programs that are typically embedded in HTML (Extensible Hyper- Text Markup Language) documents also

More information

Chapter 14: Applets and More

Chapter 14: Applets and More Chapter 14: Applets and More Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 14 discusses the following main topics: Introduction to

More information

8/23/2014. Chapter Topics. Introduction to Applets. Introduction to Applets. Introduction to Applets. Applet Limitations. Chapter 14: Applets and More

8/23/2014. Chapter Topics. Introduction to Applets. Introduction to Applets. Introduction to Applets. Applet Limitations. Chapter 14: Applets and More Chapter 14: Applets and More Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 14 discusses the following main topics: Introduction to

More information

User interfaces and Swing

User interfaces and Swing User interfaces and Swing Overview, applets, drawing, action listening, layout managers. APIs: java.awt.*, javax.swing.*, classes names start with a J. Java Lectures 1 2 Applets public class Simple extends

More information

Part 3: Graphical User Interface (GUI) & Java Applets

Part 3: Graphical User Interface (GUI) & Java Applets 1,QWURGXFWLRQWR-DYD3URJUDPPLQJ (( Part 3: Graphical User Interface (GUI) & Java Applets EE905-GUI 7RSLFV Creating a Window Panels Event Handling Swing GUI Components ƒ Layout Management ƒ Text Field ƒ

More information

SELF-STUDY. Glossary

SELF-STUDY. Glossary SELF-STUDY 231 Glossary HTML (Hyper Text Markup Language - the language used to code web pages) tags used to embed an applet. abstract A class or method that is incompletely defined,

More information

public static void main(string[] args) { GTest mywindow = new GTest(); // Title This program creates the following window and makes it visible:

public static void main(string[] args) { GTest mywindow = new GTest(); // Title This program creates the following window and makes it visible: Basics of Drawing Lines, Shapes, Reading Images To draw some simple graphics, we first need to create a window. The easiest way to do this in the current version of Java is to create a JFrame object which

More information

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing Introduction to Graphical Interface Programming in Java Introduction to AWT and Swing GUI versus Graphics Programming Graphical User Interface (GUI) Graphics Programming Purpose is to display info and

More information

Chapter 14: Applets and More

Chapter 14: Applets and More Chapter 14: Applets and More Starting Out with Java: From Control Structures through Objects Fourth Edition by Tony Gaddis Addison Wesley is an imprint of 2010 Pearson Addison-Wesley. All rights reserved.

More information

Chapter 13. Applets and HTML. HTML Applets. Chapter 13 Java: an Introduction to Computer Science & Programming - Walter Savitch 1

Chapter 13. Applets and HTML. HTML Applets. Chapter 13 Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 13 Applets and HTML HTML Applets Chapter 13 Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Overview Applets: Java programs designed to run from a document on the Internet

More information

Programming: You will have 6 files all need to be located in the dir. named PA4:

Programming: You will have 6 files all need to be located in the dir. named PA4: PROGRAMMING ASSIGNMENT 4: Read Savitch: Chapter 7 and class notes Programming: You will have 6 files all need to be located in the dir. named PA4: PA4.java ShapeP4.java PointP4.java CircleP4.java RectangleP4.java

More information

A socket is a software endpoint that establishes bidirectional communication between a server program and one or more client programs.

A socket is a software endpoint that establishes bidirectional communication between a server program and one or more client programs. PART 24 Java Network Applications 24.1 Java Socket Programming A socket is a software endpoint that establishes bidirectional communication between a server program and one or more client programs. A server

More information

Java - Applets. public class Buttons extends Applet implements ActionListener

Java - Applets. public class Buttons extends Applet implements ActionListener Java - Applets Java code here will not use swing but will support the 1.1 event model. Legacy code from the 1.0 event model will not be used. This code sets up a button to be pushed: import java.applet.*;

More information

Programmierpraktikum

Programmierpraktikum Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 18 17/01/13 11:46 Java Applets 2 of 18 17/01/13 11:46 Java applets embedding Java applications

More information

China Jiliang University Java. Programming in Java. Java Applets. Java Web Applications, Helmut Dispert

China Jiliang University Java. Programming in Java. Java Applets. Java Web Applications, Helmut Dispert Java Programming in Java Java Applets Java Applets applet = app = application snippet = (German: Anwendungsschnipsel) An applet is a small program that is intended not to be run on its own, but rather

More information

(0,0) (600, 400) CS109. PictureBox and Timer Controls

(0,0) (600, 400) CS109. PictureBox and Timer Controls CS109 PictureBox and Timer Controls Let s take a little diversion and discuss how to draw some simple graphics. Graphics are not covered in the book, so you ll have to use these notes (or the built-in

More information

(Refer Slide Time: 01:40)

(Refer Slide Time: 01:40) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #25 Javascript Part I Today will be talking about a language

More information

Understanding How Java Programs Work

Understanding How Java Programs Work HOUR 4 Understanding How Java Programs Work An important distinction to make in Java programming is where your program is supposed to be running. Some programs are intended to work on your computer; you

More information

Outline. Introduction to Java. What Is Java? History. Java 2 Platform. Java 2 Platform Standard Edition. Introduction Java 2 Platform

Outline. Introduction to Java. What Is Java? History. Java 2 Platform. Java 2 Platform Standard Edition. Introduction Java 2 Platform Outline Introduction to Java Introduction Java 2 Platform CS 3300 Object-Oriented Concepts Introduction to Java 2 What Is Java? History Characteristics of Java History James Gosling at Sun Microsystems

More information

Introduction to the Java T M Language

Introduction to the Java T M Language Introduction to the Java T M Language Jan H. Meinke July 1, 2000 1 Introduction Since its introduction in 1995 Java has become one of the most popular programming language. At first powered by the popularity

More information

Graphics -- To be discussed

Graphics -- To be discussed Graphics -- To be discussed 1 Canvas Class... 1 2 Graphics Class... 1 3 Painting... 1 4 Color Models... 4 5 Animation's Worst Enemy: Flicker... 4 6 Working with Java Images... 5 6.1 Image Loading Chain

More information

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2, Java Mouse Actions C&G criteria: 5.2.1, 5.4.1, 5.4.2, 5.6.2. The events so far have depended on creating Objects and detecting when they receive the event. The position of the mouse on the screen can also

More information

Advanced Internet Programming CSY3020

Advanced Internet Programming CSY3020 Advanced Internet Programming CSY3020 Java Applets The three Java Applet examples produce a very rudimentary drawing applet. An Applet is compiled Java which is normally run within a browser. Java applets

More information

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Graphics. Lecture 18 COP 3252 Summer June 6, 2017 Graphics Lecture 18 COP 3252 Summer 2017 June 6, 2017 Graphics classes In the original version of Java, graphics components were in the AWT library (Abstract Windows Toolkit) Was okay for developing simple

More information

ASSIGNMENT NO 14. Objectives: To learn and demonstrated use of applet and swing components

ASSIGNMENT NO 14. Objectives: To learn and demonstrated use of applet and swing components Create an applet with three text Fields and four buttons add, subtract, multiply and divide. User will enter two values in the Text Fields. When any button is pressed, the corresponding operation is performed

More information

Packages: Putting Classes Together

Packages: Putting Classes Together Packages: Putting Classes Together 1 Introduction 2 The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance) Extending interfaces The features in basic

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI Statics and GUI Dynamics 2 Statics: what s drawn on the screen Components buttons, labels, lists, sliders, menus,... Containers: components that contain

More information

CS335 Graphics and Multimedia

CS335 Graphics and Multimedia CS335 Graphics and Multimedia Fuhua (Frank) Cheng Department of Computer Science University of Kentucky Lexington, KY 40506-0046 -2-1. Programming Using JAVA JAVA history: WHY JAVA? Simple Objected-oriented

More information

Chapter 12 Advanced GUIs and Graphics

Chapter 12 Advanced GUIs and Graphics Chapter 12 Advanced GUIs and Graphics Chapter Objectives Learn about applets Explore the class Graphics Learn about the classfont Explore the classcolor Java Programming: From Problem Analysis to Program

More information

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 5: Will be an open-ended Swing project. "Programming Contest"

More information

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun! Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Why are we studying Swing? 1. Useful & fun! 2. Good application of OOP techniques

More information

Applets and the Graphics class

Applets and the Graphics class Applets and the Graphics class CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Some slides in this presentation are adapted from the slides accompanying

More information

Data Representation and Applets

Data Representation and Applets Data Representation and Applets CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Overview Binary representation Data types revisited

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) 1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

In this lecture we will briefly examine a few new controls, introduce the concept of scope, random numbers, and drawing simple graphics.

In this lecture we will briefly examine a few new controls, introduce the concept of scope, random numbers, and drawing simple graphics. Additional Controls, Scope, Random Numbers, and Graphics CS109 In this lecture we will briefly examine a few new controls, introduce the concept of scope, random numbers, and drawing simple graphics. Combo

More information

The AWT Package, Graphics- Introduction to Images

The AWT Package, Graphics- Introduction to Images Richard G Baldwin (512) 223-4758, baldwin@austin.cc.tx.us, http://www2.austin.cc.tx.us/baldwin/ The AWT Package, Graphics- Introduction to Images Java Programming, Lecture Notes # 170, Revised 09/23/98.

More information

EE219 Object Oriented Programming I (2005/2006) SEMESTER 1 SOLUTIONS

EE219 Object Oriented Programming I (2005/2006) SEMESTER 1 SOLUTIONS Q1(a) Corrected code is: EE219 Object Oriented Programming I (2005/2006) SEMESTER 1 SOLUTIONS 01 #include 02 using namespace std; 03 04 class Question1 05 06 int a,b,*p; 07 08 public: 09 Question1(int

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS4: Intro to CS in Java, Spring 25 Lecture #8: GUIs, logic design Janak J Parekh janak@cs.columbia.edu Administrivia HW#2 out New TAs, changed office hours How to create an Applet Your class must extend

More information

Chapter 1 GUI Applications

Chapter 1 GUI Applications Chapter 1 GUI Applications 1. GUI Applications So far we've seen GUI programs only in the context of Applets. But we can have GUI applications too. A GUI application will not have any of the security limitations

More information

Goals. Java - An Introduction. Java is Compiled and Interpreted. Architecture Neutral & Portable. Compiled Languages. Introduction to Java

Goals. Java - An Introduction. Java is Compiled and Interpreted. Architecture Neutral & Portable. Compiled Languages. Introduction to Java Goals Understand the basics of Java. Introduction to Java Write simple Java Programs. 1 2 Java - An Introduction Java is Compiled and Interpreted Java - The programming language from Sun Microsystems Programmer

More information

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introducing Object Oriented Programming... 2 Explaining OOP concepts... 2 Objects...3

More information

CT 229 Arrays in Java

CT 229 Arrays in Java CT 229 Arrays in Java 27/10/2006 CT229 Next Weeks Lecture Cancelled Lectures on Friday 3 rd of Nov Cancelled Lab and Tutorials go ahead as normal Lectures will resume on Friday the 10 th of Nov 27/10/2006

More information

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Starting Out with Java: From Control Structures Through Objects Sixth Edition Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 12 A First Look at GUI Applications Chapter Topics 12.1 Introduction 12.2 Creating Windows 12.3 Equipping GUI Classes

More information