<title>Hello-World Applet</title> </head> <body> <h3>My first Java applet says:</h3> <applet code=\"HelloApplet.class\" width=\"400\" height=\"150\" alt=\"Error loading applet!\"> </applet> </body> </html> Figure: 10.1: Applet output You can run the applet by loading the HTML file into a web browser. Double-click the \"HelloApplet.html\" in Windows Explorer (or from the browser, select \"file\" menu ⇒ \"open\" ⇒ \"browse\" and select \"HelloApplet.html\", or drag the HTML file into the browser). Applet Security Starting from JRE 1.8.0, you need to configure the \"Java security\" to run the applets: Control Panel ⇒ Java ⇒ Security. Check \"Enable Java content in the browser\". CU IDOL SELF LEARNING MATERIAL (SLM) 251
Set the security level to high. Add site to \"Exception Site List\": Click \"Edit Site List\" ⇒ Add ⇒ Enter site URL, e.g., file:///D:/ (for local D drive), https://www.myhsts.org/ (our site). 10.4 APPLET V/S APPLICATIONS Java Application: Java Application is just like a Java program that runs on an underlying operating system with the support of a virtual machine. It is also known as an application program. The graphical user interface is not necessary to execute the java applications; it can be run with or without it. Java Applet: An applet is a Java program that can be embedded into a web page. It runs inside the web browser and works at client side. An applet is embedded in an HTML page using the APPLET or OBJECT tag and hosted on a web server. Applets are used to make the web site more dynamic and entertaining. 10.4.1 Difference between Application and Applet Difference between Application and Applet: Java Application Java Applet Applications are just like a Java programs Applets are small Java programs that are that can be execute independently without designed to be included with the HTML using the web browser. web document. They require a Java-enabled web browser for execution. Application program requires a main Applet does not require a main function for function for its execution. its execution. Java application programs have the full Applets don’t have local disk and network access to the local file system and network. access. Applications can access all kinds of Applets can only access the browser specific resources available on the system. services. They don’t have access to the local system. Applications can executes the programs Applets cannot execute programs from the from the local system. local machine. CU IDOL SELF LEARNING MATERIAL (SLM) 252
An application program is needed to An applet program is needed to perform perform some task directly for the user. small tasks or the part of it. 10.5 SUMMARY An applet is a Java program that can be embedded into a web page. It runs inside the web browser and works at client side. An applet is embedded in an HTML page using the APPLET or OBJECT tag and hosted on a web server. Java applets are like Java applications; their creation follows the same three-step process of write, compile and run. The difference is, instead of running on your desktop, they run as part of a web page. Java Application is just like a Java program that runs on an underlying operating system with the support of a virtual machine. It is also known as an application program. The graphical user interface is not necessary to execute the java applications; it can be run with or without it. You CANNOT run the applet using JDK's Runtime \"java.exe\". Applet is a graphic program that runs inside a web browser, using the web browser's Java plug-in JRE. Applet is embedded in an HTML page (in much the same way as images, audios, videos and other programs are embedded in an HTML file). To run an applet, you need to create a HTML file, which embeds the applet. Use a text editor to create the following HTML file and save it as \"HelloApplet.html\" (or any filename of your choice). Note that HTML, unlike Java, is not case sensitive, and places no restriction on the filename. 10.6 KEYWORDS Source code: In simple, we can say source code is a set of instructions/commands and statements which is written by a programmer by using a computer programming language like C, C++, Java, Python, Assembly language, etc. So the statements written in any programming language is termed as source code. Compiling: Compiling a Java program means taking the programmer-readable text in your program file (also called source code) and converting it to bytecodes, which are platform-independent instructions for the Java VM. Directory: Directory is an organizing unit in a computer's file system for storing and locating files. Directories are hierarchically organized into a tree of directories. Directories have parent-child relationships. CU IDOL SELF LEARNING MATERIAL (SLM) 253
JDK: Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other tools needed in Java development. JRE:The Java Runtime Environment, or JRE, is a software layer that runs on top of a computer's operating system software and provides the class libraries and other resources that a specific Java program needs to run. 10.7 LEARNING ACTIVITY 1. Create an applet and run using any of the browser. ________________________________________________________________________ __________________________________________________________________ 2. Discuss the deference between applet and application. ________________________________________________________________________ __________________________________________________________________ 10.8 UNIT END QUESTIONS A. Descriptive Questions Short Questions: 1. What is an Applet? 2. How will you initialize an applet? 3. How do you set security in applets? 4. Which method is called by applet class to load an image? 5. How does applet recognize the height and width? Long Questions: 1. How to create an applet? Explain. 2. What is the difference between an Applet and a Java Application? 3. Create and run an applet using any of the browsers? 4. What is the order of method invocation in an Applet? 5. What is the sequence of interpretation, compilation of a java applet? B. Multiple Choice Questions 1. What does an applet is a Java class that extends? CU IDOL SELF LEARNING MATERIAL (SLM) 254
a. java.Applet class b. java class c. Applet class d. java.applet.Applet class 2. What does an applets are designed to be embedded within an? a. Javascript b. CSS c. HTML d. SQL 3. Which of the following is required to view an applet? a. JCM b. JDM c. JVM d. Java class 4. Which method is automatically called after the browser calls the init method? a. Start b. Stop c. Destroy d. Paint 5. Which method is only called when the browser shuts down normally? a. Start b. Stop c. Destroy d. Paint Answers 1-a, 2-c, 3-c, 4-a, 5-c 10.9 REFERENCES References CU IDOL SELF LEARNING MATERIAL (SLM) 255
Srinivas, Raghavan N. (6 July 2001). \"Java Web Start to the rescue\". Zukowski, John (1 October 1997). \"What does Sun's lawsuit against Microsoft mean for Java developers?\" Srinivas, Raghavan N. (6 July 2001). \"Java Web Start to the rescue\". Textbooks Bill Venners; Bruce Eckel (August 18, 2003). \"The Trouble with Checked Exceptions: A Conversation with Anders Hejlsberg, Part II\". p. 2. \"Unchecked Exceptions – The Controversy (The Java™ Tutorials: Essential Classes : Exceptions)\". Goodenough, John B. (1975a). Structured exception handling. Proceedings of the 2nd ACM SIGACT-SIGPLAN Website https://www.mygreatlearning.com https://www.w3schools.com https://beginnersbook.com CU IDOL SELF LEARNING MATERIAL (SLM) 256
UNIT – 11: ABSTRACT WINDOWS TOOLKIT 1 STRUCTURE 11.0 Learning Objectives 11.1 Introduction 11.2 Introducing Abstract Windows Toolkit 11.3 Containers 11.4 Frames and Panels 11.4.1 Frames 11.4.2 Panels 11.5 Layout Managers 11.5.1 Border layout 11.5.2 Flow layout 11.5.3 Grid layout 11.4 Summary 11.5 Keywords 11.6 Learning Activity 11.7 Unit End Questions 11.8 References 11.0 LEARNING OBJECTIVES After studying this unit, you will be able to: Explain Abstract Windows Toolkit Describe Containers, frames and Panels Illustrate layout Managers 11.1 INTRODUCTION The Java programming language class library provides a user interface toolkit called the Abstract Windowing Toolkit, or the AWT. The AWT is both powerful and flexible. Newcomers, however, often find that its power is veiled. The class and method descriptions found in the distributed documentation provide little guidance for the new programmer. CU IDOL SELF LEARNING MATERIAL (SLM) 257
Furthermore, the available examples often leave many important questions unanswered. Of course, newcomers should expect some difficulty. Effective graphical user interfaces are inherently challenging to design and implement, and the sometimes complicated interactions between classes in the AWT only make this task more complex. However, with proper guidance, the creation of a graphical user interface using the AWT is not only possible, but relatively straightforward. This article covers some of the philosophy behind the AWT and addresses the practical concern of how to create a simple user interface for an applet or application. The user interface is that part of a program that interacts with the user of the program. User interfaces take many forms. These forms range in complexity from simple command-line interfaces to the point-and-click graphical user interfaces provided by many modern applications. At the lowest level, the operating system transmits information from the mouse and keyboard to the program as input, and provides pixels for program output. The AWT was designed so that programmers don't have worry about the details of tracking the mouse or reading the keyboard, nor attend to the details of writing to the screen. The AWT provides a well- designed object-oriented interface to these low-level services and resources. Because the Java programming language is platform-independent, the AWT must also be platform-independent. The AWT was designed to provide a common set of tools for graphical user interface design that work on a variety of platforms. The user interface elements provided by the AWT are implemented using each platform's native GUI toolkit, thereby preserving the look and feel of each platform. This is one of the AWT's strongest points. The disadvantage of such an approach is the fact that a graphical user interface designed on one platform may look different when displayed on another platform. 11.2 INTRODUCING ABSTRACT WINDOWS TOOLKIT Java Abstract window tool kit package is used for displaying the data within a GUI Environment. Features of AW T Package are as Followings: It provides us a set of user interface components including windows buttons text fields scrolling list etc. It provides us the way to laying out these above components. It provides to create the events upon these components. The main purpose for using the AWT is using for all the components displaying on the screen. Awt defines all the windows according to a class hierarchy those are useful at a specific level or we can say arranged according to their functionality. CU IDOL SELF LEARNING MATERIAL (SLM) 258
The most commonly used interface is the panels those are used by applets and those are derived from frame which creates a standard window. The hierarchy of this Awt is:- Figure 11.1: hierarchy of Awt As you see this Figure this Hierarchical view displays all the classes and also their Sub Classes. All the Classes are Contained as a Multi-Level inheritance , As You see that Component Class contains a Panel Class which again Contains a Applet Class so that in the AWT Package are Stored in the form of Multi-values inheritance. Component Class This is the super class which defines all the methods for developing the methods those are related with the components and the methods those are related with the Actual Position of the Control and this also provides the various methods to Setup the Sized, Colors either this may a Background or a Foreground Color. It includes all the components those are displayed on the screen and it also defines various types of public methods for managing events such as mouse and keyboard window etc. the Various Methods those are Contained in the Component Class are :- Void SetSize(int Width, int Height) : this Method is used to Set the Size by taking the height and width of a Control for Example height of Textbox and width of Textbox. With this Method we Can set height and width of any Control. Void SetLocation (int x,int y): Used to Set the location on the Applet and this will take the Coordinates in the Form of x and y. CU IDOL SELF LEARNING MATERIAL (SLM) 259
Void setBounds(int x,int y,int width,int height) : this Method will also set the Acual Loction in the Applet by Specifying the X and y Coordinate and also Specify the Width and Height of the Control. Void setForeground(Color c) : this Method is used to set the Font Color or Text Color of a Control. Void setBackground(Color c) : This Method is used to set the Background Color of a Control whether this may a Control or any Window Like an Applet,Panel etc. 11.3 CONTAINERS It is subclass of components which Inherits the various Properties from that Class and it provides to laying out the component , that are contains by using the various layout managers, Means how the Components will be displayed in the applet and in which Manner the Components will be displayed in the window. or Position of the Controls without setting the X and y Axis is determined by the Layout Manager and. The Container provides very important Methods to add or Remove the Components from the Applet or from any other Window. The various Methods those are Contained in the Container class are : Void add (object o):this Method id used to Add a Control in the Applet of in any Container. Void remove (object o) : This is used if a user wants to Remove an Control from a Container For Example if a user wants to Remove the Control from a Applet then he may uses this Method. VoidremoveAll () : This Method doesn't take any argument and this will remove all the Controls from the Container. 11.4 FRAMES AND PANELS Below are the sergreation of Frames and panels. 11.4.1 Frame Frame Class is also a Sub Class of Window Class and frame class allows Creating a pop- Menus. And Frame Class Provides a Special Type of Window which has a title bar, menu bar , border. Resizing corners and it is a subclass of window class when we creates A frame object within a applet, will display a warning message that a frame window is created by an applet not by any software. But when a frame window is created by a program other than an applet then a normal window is created. The Various Methods those are provided by the Frame Class are as follows:- CU IDOL SELF LEARNING MATERIAL (SLM) 260
Frame() : This is name of Class and used for Creating an object of this Class and this will not display any title on the title bar of Frame. Frame(String Title) : This will also create an object of Frame Class and this will also Display a Title on the Title bar of the Window. Void setsize() : this is Method of Frame Class which will be Accessed by the object of Frame Class and this will takes two Arguments to set the Size in the Form of width and Height . Void show() : This is used for displaying or showing a Frame from a Main Window. Void setBackground(Color c) : This is used to set the Background Color of the frame. Void setLocation(int x,int y) : This Method will display the frame on the window according to the values of x and y coordinates those are Specified Always Remember that For Displaying a Frame you have to set the Layout and the default Layout of the Frame is Border Layout. 11.4.2Panels It is a subclass of container and it is the super class of Applet. It is a window that does not have a title bar menu bar or border. Generally a Panel is used for displaying Multiple Windows in a Single Window and a Panel may have any Layout. And for Adding any Control in the Panel we have to use the Add Method and there are also some important Methods those are Provided by the Panel Class those are Explained below :- Panel () : This is the Name of Class For Using you have to Create the object first. Void set Location: Method is used to set the Location of a control in the Panel. Void set Size () : This will takes two Arguments and those Arguments will Specify the Width and Height of the Panel. Void set Bounds: This Method is used to set the Bounds of an Control in the Panel For Example X and y Axis and Width and Height of a Control. Window Window is also a Sub Class of a Container and window class creates a top level window. These are not directly created, for this the subclass of window name frame is used and dialogs are used . This is used for displaying a Sub Windows from a Main Window and the various Methods of Window are as follows:- Void Pack() : This Method is used for adjusting the Size of Window according to the number of Controls in the Container or in the Applet or in the other window. Void show() : This Method is used for displaying a Window. CU IDOL SELF LEARNING MATERIAL (SLM) 261
Void dispose() : This Method is used for de-allocate the Memory Space which is Consumed by the Controls of the Window. 11.5 LAYOUT MANAGERS In Java, Layout Managers is used for arranging the components in order. LayoutMananger is an interface which implements the classes of the layout manager. Below are some of the class which are used for the representation of layout manager. 1. java.awt.BorderLayout 2. java.awt.FlowLayout 3. java.awt.GridLayout 4. java.awt.CardLayout 5. javax.swing.BoxLayout 11.5.1 Border layout BorderLayout is used, when we want to arrange the components in five regions. The five regions can be north, south, east, west and the centre. There are 5 types of constructor in Border Layout. They are as following: 1. public static final int NORTH 2. public static final int SOUTH 3. public static final int EAST 4. public static final int WEST 5. public static final int CENTER Example: import java.awt.*; import javax.swing.*; public class BorderDemo1 { JFrame frame; BorderDemo1() { frame=new JFrame(); JButton box1=new JButton(\"**NORTH**\");; CU IDOL SELF LEARNING MATERIAL (SLM) 262
JButton box2=new JButton(\"**SOUTH**\");; JButton box3=new JButton(\"**EAST**\");; JButton box4=new JButton(\"**WEST**\");; JButton box5=new JButton(\"**CENTER**\");; frame.add(box1,BorderLayout.NORTH); frame.add(box2,BorderLayout.SOUTH); frame.add(box3,BorderLayout.EAST); frame.add(box4,BorderLayout.WEST); frame.add(box5,BorderLayout.CENTER); frame.setSize(400,400); frame.setVisible(true); } public static void main(String[] args) { new BorderDemo1(); } } Output: CU IDOL SELF LEARNING MATERIAL (SLM) 263
Figure 11.2: Border layout 11.5.2 Flow layout Flow Layout is used, when we want to arrange the components in a sequence one after another. There are 3 types of constructor in the Flow Layout. They are as following: FlowLayout() FlowLayout(int align) FlowLayout(int align, inthgap, intvgap) import java.awt.*; import javax.swing.*; public class FlowDemo1{ JFrame frame1; CU IDOL SELF LEARNING MATERIAL (SLM) 264
FlowDemo1(){ frame1=new JFrame(); JButton box1=new JButton(\"1\"); JButton box2=new JButton(\"2\"); JButton box3=new JButton(\"3\"); JButton box4=new JButton(\"4\"); JButton box5=new JButton(\"5\"); JButton box6=new JButton(\"6\"); JButton box7=new JButton(\"7\"); JButton box8=new JButton(\"8\"); JButton box9=new JButton(\"9\"); JButton box10=new JButton(\"10\"); frame1.add(box1); frame1.add(box2); frame1.add(box3); frame1.add(box4); frame1.add(box5); frame1.add(box6); frame1.add(box7); frame1.add(box8); frame1.add(box9); frame1.add(box10); frame1.setLayout(new FlowLayout(FlowLayout.LEFT)); frame1.setSize(400,400); frame1.setVisible(true); } public static void main(String[] args) { CU IDOL SELF LEARNING MATERIAL (SLM) 265
new FlowDemo1(); } } Output: Figure 11.3: Flow layout 11.5.3 Grid layout Grid Layout is used, when we want to arrange the components in a rectangular grid. There are 3 types of constructor in Grid Layout. They are as following: GridLayout() GridLayout(int rows, int columns) GridLayout(int rows, int columns, inthgap, int vgap) import java.awt.*; import javax.swing.*; public class GridDemo1{ JFrame frame1; CU IDOL SELF LEARNING MATERIAL (SLM) 266
GridDemo1(){ frame1=new JFrame(); JButton box1=new JButton(\"*1*\"); JButton box2=new JButton(\"*2*\"); JButton box3=new JButton(\"*3*\"); JButton box4=new JButton(\"*4*\"); JButton box5=new JButton(\"*5*\"); JButton box6=new JButton(\"*6*\"); JButton box7=new JButton(\"*7*\"); JButton box8=new JButton(\"*8*\"); JButton box9=new JButton(\"*9*\"); frame1.add(box1); frame1.add(box2); frame1.add(box3); frame1.add(box4); frame1.add(box5); frame1.add(box6); frame1.add(box7); frame1.add(box8); frame1.add(box9); frame1.setLayout(new GridLayout(3,3)); frame1.setSize(500,500); frame1.setVisible(true); } public static void main(String[] args) { new GridDemo1(); CU IDOL SELF LEARNING MATERIAL (SLM) 267
} } Output: Figure 11.4: Grid Layout 11.6 SUMMARY The Java programming language class library provides a user interface toolkit called the Abstract Windowing Toolkit, or the AWT. The AWT is both powerful and flexible. Newcomers, however, often find that its power is veiled. The main purpose for using the AWT is using for all the components displaying on the screen. Awt defines all the windows according to a class hierarchy those are useful at a specific level or we can say arranged according to their functionality. Component Class is the super class which defines all the methods for developing the methods those are related with the components and the methods those are related with the Actual Position of the Control and this also provides the various methods to Setup the Sized, Colors either this may a Background or a Foreground Color. CU IDOL SELF LEARNING MATERIAL (SLM) 268
Components are subclass of components which Inherits the various Properties from that Class and it provides to laying out the component, that are contains by using the various layout managers. Frame Class is also a Sub Class of Window Class and frame class allows Creating a pop-Menus. And Frame Class Provides a Special Type of Window which has a title bar, menu bar, border. 11.7 KEYWORDS AWT: The Abstract Window Toolkit is Java's original platform-dependent windowing, graphics, and user-interface widget toolkit, preceding Swing. The AWT is part of the Java Foundation Classes (the standard API for providing a graphical user interface for a Java program. Containers: Containers are the interface between a component and the low-level, platform-specific functionality that supports the component. Before it can be executed, a web, enterprise bean, or application client component must be assembled into a Java EE module and deployed into its container. Frame: In Java, a frame is a window that has nice borders, various buttons along the top border, and other features. What you usually call a \"window\" Java calls a \"frame\". A frame is a container object, so GUI components can be placed in it. ... GUI application programs are usually organized around one or more frames. Panel: Panel is the simplest container class. A panel provides space in which an application can attach any other component, including other panels. The default layout manager for a panel is the FlowLayout layout manager. Layout Manager: Layout Manager in Java. A layout manager is an object that controls the size and position of the components in the container. Every container object has a layout manager object that controls its layout. Actually, layout managers are used to arrange the components in a specific manner. 11.8 LEARNING ACTIVITY 1. Discuss the topic abstract window toolkit. ________________________________________________________________________ __________________________________________________________________ 2. Conduct a seminar on layout managers. ________________________________________________________________________ __________________________________________________________________ CU IDOL SELF LEARNING MATERIAL (SLM) 269
11.9 UNIT END QUESTIONS A. Descriptive Questions Short Questions: 1. What are AWT peers? 2. What are the different types of controls in AWT? 3. What is the use of the window class? 4. What are panels? 5. What are frames? Long Questions: 1. What is AWT? Explain in detail. 2. What are containers? Explain. 3. What are frames? Explain. 4. What are panels? Explain. 5. Explain layout managers in detail? B. Multiple Choice Questions 1. Which is the container that doesn't contain title bar and MenuBars but it can have other components like button, textfield etc? a. Window b. Frame c. Panel d. Container 2. What is the abbreviation of AWT? a. Applet Windowing Toolkit b. Abstract Windowing Toolkit c. Absolute Windowing Toolkit d. None of these 3. Which object can be constructed to show any number of choices in the visible window? a. Labels CU IDOL SELF LEARNING MATERIAL (SLM) 270
b. Choice c. List d. Checkbox 4. Which is used to store data and partial results, as well as to perform dynamic linking, return values for methods, and dispatch exceptions? a. Window b. Panel c. Frame d. Container 5. Which is a component in AWT that can contain another component like buttons, text fields, labels etc.? a. Window b. Container c. Panel d. Frame Answers 1-c, 2-b, 3-c, 4-c, 5-b 11.10 REFERENCES References Fowler, Amy (1994). \"Mixing heavy and light components\". Sun Microsystems. Archived from the original on 23 December 2011.. Torre, Mario (2 March 2008). \"FINAL PROPOSAL: Portable GUI backends\". Archived from the original on 19 March 2012. Kennke, Roman (3 September 2008). \"Cacio Swing AWT peers\". Archived from the original on 13 March 2012. Textbooks Kennke, Roman (28 July 2011). \"JDK7 and Cacio coolness\". Retrieved 8 August 2011. CU IDOL SELF LEARNING MATERIAL (SLM) 271
Eisserer, Clemens. \"HTML5/Canvas backend for Caciocavallo (GNU-Classpath)\". Archived from the original on 21 March 2012. Retrieved 8 August 2011. John Zukowski, Java AWT Reference, O'Reilly, 1997. Website https://www.mygreatlearning.com https://www.w3schools.com https://beginnersbook.com CU IDOL SELF LEARNING MATERIAL (SLM) 272
UNIT – 12:ABSTRACT WINDOWS TOOLKIT 2 STRUCTURE 12.0 Learning Objectives 12.1 Introduction 12.2 AWT all components 12.3Event delegation Model 12.3.1 Events 12.3.2 Event Sources 12.3.3 Event Listeners 12.4 Swing Components 12.4.1 Introducing Swing 12.4.2 The Origins of Swing 12.4.3 Swing is built on the AWT 12.4.4 Two Key Swing Features 12.4.5 The MVC Connection 12.4.6 Components and Containers 12.4.7 The Swing Packages 12.4.8 A Simple Swing Application 12.4.9 Event Handling 12.4.10 Create a Swing Applet 12.4.11 Painting in Swing 12.5 Summary 12.6 Keywords 12.7 Learning Activity 12.8Unit End Questions 12.9 References 12.0 LEARNING OBJECTIVES After studying this unit, you will be able to: CU IDOL SELF LEARNING MATERIAL (SLM) 273
Illustrate AWT all components Explain event delegation Model Describe Swing Components Explain Event Sourcesand Event Listeners 12.1 INTRODUCTION Java is one of the most in-demand programming languages for developing a variety of applications. The popularity of Java can be attributed to its versatility as it can be used to design customized applications that are light and fast and serve a variety of purposes ranging from web services to android applications. Java is fast, reliable and secure. There are multiple ways to develop GUI based applications in java, out of which the most popular ones are AWT and Swing. Before getting into the differences, let us first understand what each of them actually is. 1. AWT AWT stands for Abstract Window Toolkit. It is a platform-dependent API to develop GUI (Graphical User Interface) or window-based applications in Java. It was developed by Sun Microsystems In 1995. It is heavy-weight in use because it is generated by the system’s host operating system. It contains a large number of classes and methods, which are used for creating and managing GUI. 2. Swing: Swing is a lightweight Java graphical user interface (GUI) that is used to create various applications. Swing has components which are platform-independent. It enables the user to create buttons and scroll bars. Swing includes packages for creating desktop applications in Java. Swing components are written in Java language. It is a part of Java Foundation Classes(JFC). 12.2 AWT ALL COMPONENTS In this section you will learn about the different components available in the Java AWT package for developing user interface for your program. Following some components of Java AWT are explained: Labels: This is the simplest component of Java Abstract Window Toolkit. This component is generally used to show the text or string in your application and label CU IDOL SELF LEARNING MATERIAL (SLM) 274
never perform any type of action. Syntax for defining the label only and with justification : Label label_name = new Label (\"This is the label text.\"); Above code simply represents the text for the label. Label label_name = new Label (\"This is the label text.\", Label.CENTER); Justification of label can be left, right or centered. Above declaration used the center justification of the label using the Label.CENTER. Buttons: This is the component of Java Abstract Window Toolkit and is used to trigger actions and other events required for your application. The syntax of defining the button is as follows Button button_name = new Button (\"This is the label of the button.\"); You can change the Button's label or get the label's text by using the Button.setLabel(String) and Button.getLabel() method. Buttons are added to its container using the add (button_name) method. Check Boxes: This component of Java AWT allows you to create check boxes in your applications. The syntax of the definition of Checkbox is as follows : CheckBox checkbox_name = new Checkbox (\"Optional check box 1\", false); Above code constructs the unchecked Checkbox by passing the boolean valued argument false with the Checkbox label through the Checkbox() constructor. Defined Checkbox is added to its container using add (checkbox_name) method. You can change and get the checkbox's label using the setLabel (String) and getLabel() method. You can also set and get the state of the checkbox using the setState(boolean) and getState() method provided by the Checkbox class. Radio Button: This is the special case of the Checkbox component of Java AWT package. This is used as a group of checkboxes which group name is same. Only one Checkbox from a Checkbox Group can be selected at a time. Syntax for creating radio buttons is as follows : CheckboxGroup chkgp = new CheckboxGroup(); add (new Checkbox (\"One\", chkgp, false); add (new Checkbox (\"Two\", chkgp, false); add (new Checkbox (\"Three\",chkgp, false); In the above code we are making three check boxes with the label \"One\", \"Two\" and “Three\". If you mention more than one true valued for checkboxes then your program takes the last true and shows the last check box as checked. CU IDOL SELF LEARNING MATERIAL (SLM) 275
Text Area: This is the text container component of Java AWT package. The Text Area contains plain text. TextArea can be declared as follows: TextArea txtArea_name = new TextArea (); You can make the Text Area editable or not using the setEditable (Boolean) method. If you pass the Boolean valued argument false then the text area will be non-editable otherwise it will be editable. The text area is by default in editable mode. Text is set in the text area using the setText (string) method of the TextArea class. Text Field: This is also the text container component of Java AWT package. This component contains single line and limited text information. This is declared as follows: TextField txtfield = new TextField (20); You can fix the number of columns in the text field by specifying the number in the constructor. In the above code we have fixed the number of columns to 20. 12.3 EVENT DELEGATION MODEL The Delegation Event model is defined to handle events in GUI programming languages. The GUI stands for Graphical User Interface, where a user graphically/visually interacts with the system. The GUI programming is inherently event-driven; whenever a user initiates an activity such as a mouse activity, clicks, scrolling, etc., each is known as an event that is mapped to a code to respond to functionality to the user. This is known as event handling. In this section, we will discuss event processing and how to implement the delegation event model in Java. We will also discuss the different components of an Event Model. Event Processing in Java Java support event processing since Java 1.0. It provides support for AWT ( Abstract Window Toolkit), which is an API used to develop the Desktop application. In Java 1.0, the AWT was based on inheritance. To catch and process GUI events for a program, it should hold subclass GUI components and override action() or handleEvent() methods. The below image demonstrates the event processing. CU IDOL SELF LEARNING MATERIAL (SLM) 276
Figure 12.1: Event processing But, the modern approach for event processing is based on the Delegation Model. It defines a standard and compatible mechanism to generate and process events. In this model, a source generates an event and forwards it to one or more listeners. The listener waits until it receives an event. Once it receives the event, it is processed by the listener and returns it. The UI elements are able to delegate the processing of an event to a separate function. The key advantage of the Delegation Event Model is that the application logic is completely separated from the interface logic. In this model, the listener must be connected with a source to receive the event notifications. Thus, the events will only be received by the listeners who wish to receive them. So, this approach is more convenient than the inheritance-based event model (in Java 1.0). In the older model, an event was propagated up the containment until a component was handled. This needed components to receive events that were not processed, and it took lots of time. The Delegation Event model overcame this issue. Basically, an Event Model is based on the following three components: Events Events Sources Events Listeners CU IDOL SELF LEARNING MATERIAL (SLM) 277
12.3.1 Events The Events are the objects that define state change in a source. An event can be generated as a reaction of a user while interacting with GUI elements. Some of the event generation activities are moving the mouse pointer, clicking on a button, pressing the keyboard key, selecting an item from the list, and so on. We can also consider many other user operations as events. The Events may also occur that may be not related to user interaction, such as a timer expires, counter exceeded, system failures, or a task is completed, etc. We can define events for any of the applied actions. 12.3.2 Event Sources A source is an object that causes and generates an event. It generates an event when the internal state of the object is changed. The sources are allowed to generate several different types of events. A source must register a listener to receive notifications for a specific event. Each event contains its registration method. Below is an example: public void addTypeListener (TypeListener e1) From the above syntax, the Type is the name of the event, and e1 is a reference to the event listener. For example, for a keyboard event listener, the method will be called as addKeyListener (). For the mouse event listener, the method will be called as addMouseMotionListener (). When an event is triggered using the respected source, all the events will be notified to registered listeners and receive the event object. This process is known as event multicasting. In few cases, the event notification will only be sent to listeners that register to receive them. Some listeners allow only one listener to register. Below is an example: Public void addTypeListener(TypeListener e2) throws java.util.TooManyListenersException From the above syntax, the Type is the name of the event, and e2 is the event listener's reference. When the specified event occurs, it will be notified to the registered listener. This process is known as unicasting events. A source should contain a method that unregisters a specific type of event from the listener if not needed. Below is an example of the method that will remove the event from the listener. Public void removeTypeListener (TypeListener e2?) From the above syntax, the Type is an event name, and e2 is the reference of the listener. For example, to remove the keyboard listener, the removeKeyListener () method will be called. CU IDOL SELF LEARNING MATERIAL (SLM) 278
The source provides the methods to add or remove listeners that generate the events. For example, the Component class contains the methods to operate on the different types of events, such as adding or removing them from the listener. 12.3.3 Event Listeners An event listener is an object that is invoked when an event triggers. The listeners require two things; first, it must be registered with a source; however, it can be registered with several resources to receive notification about the events. Second, it must implement the methods to receive and process the received notifications. The methods that deal with the events are defined in a set of interfaces. These interfaces can be found in the java.awt.event package. For example, the MouseMotionListener interface provides two methods when the mouse is dragged and moved. Any object can receive and process these events if it implements the MouseMotionListener interface. 12.4 SWING COMPONENTS Swing components are the basic building blocks of an application. We know that Swing is a GUI widget toolkit for Java. Every application has some basic interactive interface for the user. For example, a button, check-box, radio-button, text-field, etc. These together form the components in Swing. So, to summarise, Swing components are the interactive elements in a Java application. We will see various Swing Components in this article and see a few examples. Note that the examples are simple code snippets. You can use them in your application and tailor them to suit your application architecture. 12.4.1 Introducing Swing Although the AWT is still a crucial part of Java, its component set is no longer widely used to create graphical user interfaces. Today, most programmers use Swing or JavaFX for this purpose. JavaFX is discussed in Part IV. Here, Swing is introduced. Swing is a framework that provides more powerful and flexible GUI components than does the AWT. As a result, it is the GUI that has been widely used by Java programmers for more than a decade. 12.4.2 The Origins of Swing Swing did not exist in the early days of Java. Rather, it was a response to deficiencies present in Java’s original GUI subsystem: the Abstract Window Toolkit. The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but limited graphical interface. One reason for the limited nature of the AWT is that it translates its various visual components into their corresponding, platform-specific equivalents, or peers. This means that CU IDOL SELF LEARNING MATERIAL (SLM) 279
the look and feel of a component is defined by the platform, not by Java. Because the AWT components use native code resources, they are referred to as heavyweight. The use of native peers led to several problems. First, because of variations between operating systems, a component might look, or even act, differently on different platforms. This potential variability threatened the overarching philosophy of Java: write once, run anywhere. Second, the look and feel of each component was fixed (because it is defined by the platform) and could not be (easily) changed. Third, the use of heavyweight components caused some frustrating restrictions. For example, a heavyweight component was always opaque. Not long after Java’s original release, it became apparent that the limitations and restrictions present in the AWT were sufficiently serious that a better approach was needed. The solution was Swing. Introduced in 1997, Swing was included as part of the Java Foundation Classes (JFC). Swing was initially available for use with Java 1.1 as a separate library. However, beginning with Java 1.2, Swing (and the rest of the JFC) was fully integrated into Java. 12.4.3 Swing is built on the AWT Before moving on, it is necessary to make one important point: although Swing eliminates a number of the limitations inherent in the AWT, Swing does not replace it. Instead, Swing is built on the foundation of the AWT. This is why the AWT is still a crucial part of Java. Swing also uses the same event handling mechanism as the AWT. Therefore, a basic understanding of the AWT and of event handling is required to use Swing. 12.4.4 Two Key Swing Features As just explained, Swing was created to address the limitations present in the AWT. It does this through two key features: lightweight components and a pluggable look and feel. Together they provide an elegant, yet easy-to-use solution to the problems of the AWT. More than anything else, it is these two features that define the essence of Swing. Each is examined here. Swing Components Are Lightweight With very few exceptions, Swing components are lightweight. This means that they are written entirely in Java and do not map directly to platform-specific peers. Thus, lightweight components are more efficient and more flexible. Furthermore, because lightweight components do not translate into native peers, the look and feel of each component is determined by Swing, not by the underlying operating system. As a result, each component will work in a consistent manner across all platforms. Swing Supports a Pluggable Look and Feel CU IDOL SELF LEARNING MATERIAL (SLM) 280
Swing supports a pluggable look and feel (PLAF). Because each Swing component is rendered by Java code rather than by native peers, the look and feel of a component is under the control of Swing. This fact means that it is possible to separate the look and feel of a component from the logic of the component, and this is what Swing does. Separating out the look and feel provides a significant advantage: it becomes possible to change the way that a component is rendered without affecting any of its other aspects. In other words, it is possible to “plug in” a new look and feel for any given component without creating any side effects in the code that uses that component. Moreover, it becomes possible to define entire sets of look-and-feels that represent different GUI styles. To use a specific style, its look and feel is simply “plugged in.” Once this is done, all components are automatically rendered using that style. Pluggable look-and-feels offer several important advantages. It is possible to define a look and feel that is consistent across all platforms. Conversely, it is possible to create a look and feel that acts like a specific platform. For example, if you know that an application will be running only in a Windows environment, it is possible to specify the Windows look and feel. It is also possible to design a custom look and feel. Finally, the look and feel can be changed dynamically at run time. Java 8 provides look-and-feels, such as metal and Nimbus, that are available to all Swing users. The metal look and feel is also called the Java look and feel. It is platform-independent and available in all Java execution environments. It is also the default look and feel. Windows environments also have access to the Windows look and feel. This book uses the default Java look and feel (metal) because it is platform independent. 12.4.5 The MVC Connection In general, a visual component is a composite of three distinct aspects: The way that the component looks when rendered on the screen The way that the component reacts to the user The state information associated with the component No matter what architecture is used to implement a component, it must implicitly contain these three parts. Over the years, one component architecture has proven itself to be exceptionally effective: Model-View-Controller or MVC for short. The MVC architecture is successful because each piece of the design corresponds to an aspect of a component. In MVC terminology, the model corresponds to the state information associated with the component. For example, in the case of a check box, the model contains a field that indicates if the box is checked or unchecked. The view determines how the component is displayed on the screen, including any aspects of the view that are affected by the current state of the model. The controller determines how the component reacts to the CU IDOL SELF LEARNING MATERIAL (SLM) 281
user. For example, when the user clicks a check box, the controller reacts by changing the model to reflect the user’s choice (checked or unchecked). This then results in the view being updated. By separating a component into a model, a view, and a controller, the specific implementation of each can be changed without affecting the other two. For instance, different view implementations can render the same component in different ways without affecting the model or the controller. Although the MVC architecture and the principles behind it are conceptually sound, the high level of separation between the view and the controller is not beneficial for Swing components. Instead, Swing uses a modified version of MVC that combines the view and the controller into a single logical entity called the UI delegate. For this reason, Swing’s approach is called either the Model-Delegate architecture or the Separable Model architecture. Therefore, although Swing’s component architecture is based on MVC, it does not use a classical implementation of it. Swing’s pluggable look and feel is made possible by its Model-Delegate architecture. Because the view (look) and controller (feel) are separate from the model, the look and feel can be changed without affecting how the component is used within a program. Conversely, it is possible to customize the model without affecting the way that the component appears on the screen or responds to user input. To support the Model-Delegate architecture, most Swing components contain two objects. The first represents the model. The second represents the UI delegate. Models are defined by interfaces. For example, the model for a button is defined by the ButtonModel interface. UI delegates are classes that inherit ComponentUI. For example, the UI delegate for a button is ButtonUI. Normally, your programs will not interact directly with the UI delegate. 12.4.6 Components and Containers A Swing GUI consists of two key items: components and containers. However, this distinction is mostly conceptual because all containers are also components. The difference between the two is found in their intended purpose: As the term is commonly used, a component is an independent visual control, such as a push button or slider. A container holds a group of components. Thus, a container is a special type of component that is designed to hold other components. Furthermore, in order for a component to be displayed, it must be held within a container. Thus, all Swing GUIs will have at least one container. Because containers are components, a container can also hold other containers. This enables Swing to define what is called a containment hierarchy, at the top of which must be a top- level container. Let’s look a bit more closely at components and containers. Components CU IDOL SELF LEARNING MATERIAL (SLM) 282
In general, Swing components are derived from the JComponent class. (The only exceptions to this are the four top-level containers, described in the next section.) JComponent provides the functionality that is common to all components. For example, JComponent supports the pluggable look and feel. JComponent inherits the AWT classes Container and Component. Thus, a Swing component is built on and compatible with an AWT component. All of Swing’s components are represented by classes defined within the package javax.swing. The following table shows the class names for Swing components (including those used as containers). JApplet JFileChooser JSplitPane JViewport JColorChooser JTextField JButton JDialog JToolTip JComboBox JFrame JCheckBoxMenuItem JEditorPane JLayeredPane JDesktopPane JInternalFrame JMenuItem JFormattedTextField JList JPopupMenu JLayer JOptionPane JRootPane JMenuBar JProgressBar JSlider JPasswordField JScrollBar JTable JRadioButtonMenuItem JSpinner JTogglebutton JSeparator JTextArea JLabel JTabbedPane JToolBar JMenu JTextPane JWindow JPanel JTree JCheckBox JRadioButton JComponent JScrollPane Notice that all component classes begin with the letter J. For example, the class for a label is JLabel; the class for a push button is JButton; and the class for a scroll bar is JScrollBar. Containers Swing defines two types of containers. The first are top-level containers: JFrame, JApplet, JWindow, and JDialog. These containers do not inherit JComponent. They do, however, inherit the AWT classes Component and Container. Unlike Swing’s other components, which CU IDOL SELF LEARNING MATERIAL (SLM) 283
are lightweight, the top-level containers are heavyweight. This makes the top-level containers a special case in the Swing component library. As the name implies, a top-level container must be at the top of a containment hierarchy. A top-level container is not contained within any other container. Furthermore, every containment hierarchy must begin with a top-level container. The one most commonly used for applications is JFrame. The one used for applets is JApplet. The second type of containers supported by Swing is lightweight containers. Lightweight containers do inherit JComponent. An example of a lightweight container is JPanel, which is a general-purpose container. Lightweight containers are often used to organize and manage groups of related components because a lightweight container can be contained within another container. Thus, you can use lightweight containers such as JPanel to create subgroups of related controls that are contained within an outer container. The Top-Level Container Panes Each top-level container defines a set of panes. At the top of the hierarchy is an instance of JRootPane. JRootPane is a lightweight container whose purpose is to manage the other panes. It also helps manage the optional menu bar. The panes that comprise the root pane are called the glass pane, the content pane, and the layered pane. The glass pane is the top-level pane. It sits above and completely covers all other panes. By default, it is a transparent instance of JPanel. The glass pane enables you to manage mouse events that affect the entire container (rather than an individual control) or to paint over any other component, for example. In most cases, you won’t need to use the glass pane directly, but it is there if you need it. The layered pane is an instance of JLayeredPane. The layered pane allows components to be given a depth value. This value determines which component overlays another. (Thus, the layered pane lets you specify a Z-order for a component, although this is not something that you will usually need to do.) The layered pane holds the content pane and the (optional) menu bar. Although the glass pane and the layered panes are integral to the operation of a top-level container and serve important purposes, much of what they provide occurs behind the scene. The pane with which your application will interact the most is the content pane, because this is the pane to which you will add visual components. In other words, when you add a component, such as a button, to a top-level container, you will add it to the content pane. By default, the content pane is an opaque instance of JPanel. 12.4.7 The Swing Packages Swing is a very large subsystem and makes use of many packages. At the time of this writing, these are the packages defined by Swing. CU IDOL SELF LEARNING MATERIAL (SLM) 284
javax.swing javax.swing.plaf.metal javax.swing.text.html.par javax.swing.border javax.swing.plaf.multi ser javax.swing.colorchooser javax.swing.plaf.nimbus javax.swing.text.rtf javax.swing.event javax.swing.plaf.synth javax.swing.tree javax.swing.filechooser javax.swing.table javax.swing.undo javax.swing.plaf javax.swing.text javax.swing.plaf.basic javax.swing.text.html The main package is javax.swing. This package must be imported into any program that uses Swing. It contains the classes that implement the basic Swing components, such as push buttons, labels, and check boxes. 12.4.8 A Simple Swing Application Swing programs differ from both the console-based programs and the AWT-based programs shown earlier in this book. For example, they use a different set of components and a different container hierarchy than does the AWT. Swing programs also have special requirements that relate to threading. The best way to understand the structure of a Swing program is to work through an example. There are two types of Java programs in which Swing is typically used. The first is a desktop application. The second is the applet. This section shows how to create Application In the process, it demonstrates several key features of Swing. It uses two Swing components: JFrame and JLabel. JFrame is the top-level container that is commonly used for Swing applications. JLabel is the Swing component that creates a label, which is a component that displays information. The label is Swing’s simplest component because it is passive. That is, a label does not respond to user input. It just displays output. The program uses a JFrame container to hold an instance of a JLabel. The label displays a short text message. // A simple Swing application. import javax.swing.*; class SwingDemo { SwingDemo() { // Create a new JFrame container. JFramejfrm = new JFrame(\"A Simple Swing Application\"); Give the frame an initial size. jfrm.setSize(275, 100); CU IDOL SELF LEARNING MATERIAL (SLM) 285
Terminate the program when the user closes the application. jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Create a text-based label. JLabeljlab = new JLabel(\" Swing means powerful GUIs.\"); Add the label to the content pane. jfrm.add(jlab); Display the frame. jfrm.setVisible(true); } public static void main(String args[]) { // Create the frame on the event dispatching thread. SwingUtilities.invokeLater(new Runnable() { public void run() { new SwingDemo(); } }); } } Swing programs are compiled and run in the same way as other Java applications. Thus, to compile this program, you can use this command line: javac SwingDemo.java To run the program, use this command line: java SwingDemo When the program is run, it will produce a window similar to that shown in Figure 12.1 Because the SwingDemo program illustrates several core Swing concepts, we willexamine it carefully, line by line. The program begins by importing javax.swing. As mentioned, this package contains the components and models defined by Swing. For example, javax.swing defines classes that implement labels, buttons, text controls, and menus. It will be included in all programs that use Swing. Figure12.2: The window produced by the SwingDemo program CU IDOL SELF LEARNING MATERIAL (SLM) 286
12.4.9 Event Handling The preceding example showed the basic form of a Swing program, but it left out one important part: event handling. Because JLabel does not take input from the user, it does not generate events, so no event handling was needed. However, the other Swing components do respond to user input and the events generated by those interactions need to be handled. Events can also be generated in ways not directly related to user input. For example, an event is generated when a timer goes off. Whatever the case, event handling is a large part of any Swing-based application. The event handling mechanism used by Swing is the same as that used by the AWT. This approach is called the delegation event model. In many cases, Swing uses the same events as does the AWT, and these events are packaged in java.awt.event. Events specific to Swing are stored in javax.swing.event. Although events are handled in Swing in the same way as they are with the AWT, it is still useful to work through a simple example. The following program handles the event generated by a Swing push button. Sample output is shown in Figure 12.3. Figure 12.3: Event demo program output // Handle an event in a Swing program. import java.awt.*; import java.awt.event.*; import javax.swing.*; class EventDemo { JLabeljlab; EventDemo() { // Create a new JFrame container. JFramejfrm = new JFrame(\"An Event Example\"); //Specify FlowLayout for the layout manager. jfrm.setLayout(new FlowLayout()); //Give the frame an initial size. jfrm.setSize(220, 90); //Terminate the program when the user closes the application. CU IDOL SELF LEARNING MATERIAL (SLM) 287
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Make two buttons. JButtonjbtnAlpha = new JButton(\"Alpha\"); JButtonjbtnBeta = new JButton(\"Beta\"); //Add action listener for Alpha. jbtnAlpha.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { jlab.setText(\"Alpha was pressed.\"); } }); //Add action listener for Beta. jbtnBeta.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { jlab.setText(\"Beta was pressed.\"); } }); //Add the buttons to the content pane. jfrm.add(jbtnAlpha); jfrm.add(jbtnBeta); //Create a text-based label. jlab = new JLabel(\"Press a button.\"); //Add the label to the content pane. jfrm.add(jlab); //Display the frame. jfrm.setVisible(true); } public static void main(String args[]) { // Create the frame on the event dispatching thread. SwingUtilities.invokeLater(new Runnable() { public void run() { new EventDemo(); } }); CU IDOL SELF LEARNING MATERIAL (SLM) 288
} } 12.4.10 Create a Swing Applet The second type of program that commonly uses Swing is the applet. Swing-based applets are similar to AWT-based applets, but with an important difference: A Swing applet extends JApplet rather than Applet. JApplet is derived from Applet. Thus, JApplet includes all of the functionality found in Applet and adds support for Swing. JApplet is a top-level Swing container, which means that it is not derived from JComponent. Because JApplet is a top- level container, it includes the various panes described earlier. This means that all components are added to JApplet’s content pane in the same way that components are added to JFrame’s content pane. Swing applets use the same four life-cycle methods init( ), start( ), stop( ), and destroy( ). Of course, you need override only those methods that are needed by your applet. Painting is accomplished differently in Swing than it is in the AWT, and a Swing applet will not normally override the paint( ) method. Figure 12.4: Output example for swing applet // A simple Swing-based applet import javax.swing.*; import java.awt.*; import java.awt.event.*; /* This HTML can be used to launch the applet: <applet code=\"MySwingApplet\" width=220 height=90></applet> */ public class MySwingApplet extends JApplet { JButtonjbtnAlpha; JButtonjbtnBeta; JLabeljlab; CU IDOL SELF LEARNING MATERIAL (SLM) 289
// Initialize the applet. public void init() { try { SwingUtilities.invokeAndWait(new Runnable () { public void run() { makeGUI(); // initialize the GUI } }); } catch(Exception exc) { System.out.println(\"Can’t create because of \"+ exc); } } //This applet does not need to override start(), stop(), //or destroy(). //Set up and initialize the GUI. private void makeGUI() { //Set the applet to use flow layout. setLayout(new FlowLayout()); //Make two buttons. jbtnAlpha = new JButton(\"Alpha\"); jbtnBeta = new JButton(\"Beta\"); Add action listener for Alpha. jbtnAlpha.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent le) { jlab.setText(\"Alpha was pressed.\"); } }); //Add action listener for Beta. jbtnBeta.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent le) { jlab.setText(\"Beta was pressed.\"); } }); //Add the buttons to the content pane. CU IDOL SELF LEARNING MATERIAL (SLM) 290
add(jbtnAlpha); add(jbtnBeta); //Create a text-based label. jlab = new JLabel(\"Press a button.\"); // Add the label to the content pane. add(jlab); } } There are two important things to notice about this applet. First, MySwingApplet extends JApplet. As explained, all Swing-based applets extend JApplet rather than Applet. Second, the init( ) method initializes the Swing components on the event dispatching thread by setting up a call to makeGUI( ). Notice that this is accomplished through the use of invokeAndWait ( ) rather than invokeLater( ). Applets must use invokeAndWait ( ) because the init( ) method must not return until the entire initialization process has been completed. In essence, the start( ) method cannot be called until after initialization, which means that the GUI must be fully constructed. Inside makeGUI( ), the two buttons and label are created, and the action listeners are added to the buttons. Finally, the components are added to the content pane. Although this example is quite simple, this same general approach must be used when building any Swing GUI that will be used by an applet. 12.4.11 Painting in Swing Although the Swing component set is quite powerful, you are not limited to using it because Swing also lets you write directly into the display area of a frame, panel, or one of Swing’s other components, such as JLabel. Although many (perhaps most) uses of Swing will not involve drawing directly to the surface of a component, it is available for those applications that need this capability. To write output directly to the surface of a component, you will use one or more drawing methods defined by the AWT, such as drawLine( ) or drawRect( ). However, there are also some very important differences, and the process is discussed in detail in this section. Painting Fundamentals Swing’s approach to painting is built on the original AWT-based mechanism, but Swing’s implementation offers more finally grained control. Before examining the specifics of Swing- based painting, it is useful to review the AWT-based mechanism that underlies it. CU IDOL SELF LEARNING MATERIAL (SLM) 291
The AWT class Component defines a method called paint( ) that is used to draw output directly to the surface of a component. For the most part, paint( ) is not called by your program. (In fact, only in the most unusual cases should it ever be called by your program.) Rather, paint( ) is called by the run-time system whenever a component must be rendered. This situation can occur for several reasons. For example, the window in which the component is displayed can be overwritten by another window and then uncovered. Or, the window might be minimized and then restored. The paint( ) method is also called when a program begins running. When writing AWT-based code, an application will override paint( ) when it needs to write output directly to the surface of the component. Because JComponent inherits Component, all Swing’s lightweight components inherit the paint( ) method. However, you will not override it to paint directly to the surface of a component. The reason is that Swing uses a bit more sophisticated approach to painting that involves three distinct methods: paintComponent( ), paintBorder( ), and paintChildren( ). These methods paint the indicated portion of a component and divide the painting process into its three distinct, logical actions. In a lightweight component, the original AWT method paint( ) simply executes calls to these methods, in the order just shown. To paint to the surface of a Swing component, you will create a subclass of the component and then override its paintComponent( ) method. This is the method that paints the interior of the component. You will not normally override the other two painting methods. When overriding paintComponent( ), the first thing you must do is call super.paintComponent( ), so that the superclass portion of the painting process takes place. (The only time this is not required is when you are taking complete, manual control over how a component is displayed.) After that, write the output that you want to display. The paintComponent( ) method is shown here: protected void paintComponent(Graphics g) The parameter g is the graphics context to which output is written. To cause a component to be painted under program control, call repaint( ). It works in Swing just as it does for the AWT. The repaint( ) method is defined by Component. Calling it causes the system to call paint( ) as soon as it is possible to do so. Because painting is a time- consuming operation, this mechanism allows the run-time system to defer painting momentarily until some higher-priority task has completed, for example. Of course, in Swing the call to paint( ) results in a call to paintComponent( ). Therefore, to output to the surface of a component, your program will store the output until paintComponent( ) is called. Inside the overridden paintComponent ( ), you will draw the stored output. CU IDOL SELF LEARNING MATERIAL (SLM) 292
12.5 SUMMARY Java is one of the most in-demand programming languages for developing a variety of applications. The popularity of Java can be attributed to its versatility as it can be used to design customized applications that are light and fast and serve a variety of purposes ranging from web services to android applications. AWT stands for Abstract Window Toolkit. It is a platform-dependent API to develop GUI or window-based applications in Java. It was developed by Sun Microsystems In 1995. It is heavy-weight in use because it is generated by the system’s host operating system. It contains a large number of classes and methods, which are used for creating and managing GUI. Swing is a lightweight Java graphical user interface that is used to create various applications. Swing has components which are platform-independent. It enables the user to create buttons and scroll bars. Swing includes packages for creating desktop applications in Java. Swing components are written in Java language. It is a part of Java Foundation Classes. The Delegation Event model is defined to handle events in GUI programming languages. The GUI stands for Graphical User Interface, where a user graphically/visually interacts with the system. The Events are the objects that define state change in a source. An event can be generated as a reaction of a user while interacting with GUI elements. Some of the event generation activities are moving the mouse pointer, clicking on a button, pressing the keyboard key, selecting an item from the list, and so on. We can also consider many other user operations as events. 12.6 KEYWORDS AWT:The Abstract Window Toolkit is Java's original platform-dependent windowing, graphics, and user-interface widget toolkit, preceding Swing. The AWT is part of the Java Foundation Classes the standard API for providing a graphical user interface for a Java program. Containers: Containers are the interface between a component and the low-level, platform-specific functionality that supports the component. Before it can be executed, a web, enterprise bean, or application client component must be assembled into a Java EE module and deployed into its container. Frame: In Java, a frame is a window that has nice borders, various buttons along the top border, and other features. What you usually call a \"window\" Java calls a \"frame\". CU IDOL SELF LEARNING MATERIAL (SLM) 293
A frame is a container object, so GUI components can be placed in it. GUI application programs are usually organized around one or more frames Swing: Swing is a set of program component s for Java programmes that provide the ability to create graphical user interface components, such as buttons and scroll bars that are independent of the windowing system for specific operating system. Swing components are used with the Java Foundation Classes. Event source: A source is an object that causes and generates an event. It generates an event when the internal state of the object is changed. The sources are allowed to generate several different types of events. 12.7 LEARNING ACTIVITY 1. Conduct a seminar on swing components. ________________________________________________________________________ __________________________________________________________________ 2. Create a simple swing application. ________________________________________________________________________ __________________________________________________________________ 12.8 UNIT END QUESTIONS A. Descriptive Questions Short Questions: 1. What is java swing? 2. What do you mean by events? 3. What do you mean by events source? 4. What do you mean by events listeners? 5. List any of the three awt components? Long Questions: 1. What are AWT components? Explain in detail. 2. Explain the two key swing features. 3. What are swing components? Explain. 4. Create and run a simple swing application? 5. Explain event delegation model. CU IDOL SELF LEARNING MATERIAL (SLM) 294
B. Multiple Choice Questions 1. Which is a component in AWT that can contain other components like buttons, textfields, labels etc.? a. Window b. Container c. Panel d. Frame 2. Which of the following specifieslightweight as the advantages of below application? a. Swing b. AWT c. Event sources d. None of these 3. Which class provides many methods for graphics programming? a. Java.awt b. Java.Graphics c. Java.awt.Graphics d. None of these 4. Identify the places in which we can put the event handling code. a. Same class b. Other class c. Annonymous class d. All of these 5. What is the ActionListener interface is used for handling action events? a. JButton b. JCheckbox c. JMenuItem d. All of these Answers 1-b, 2-a, 3-c, 4-d, 5-d CU IDOL SELF LEARNING MATERIAL (SLM) 295
12.9 REFERENCES References Fowler, Amy (1994). \"Mixing heavy and light components\". Sun Microsystems. Torre, Mario (2 March 2008). \"FINAL PROPOSAL: Portable GUI backends\". Kennke, Roman (3 September 2008). \"Cacio Swing AWT peers\". Textbooks Kennke, Roman (28 July 2011). \"JDK7 and Cacio coolness\". Retrieved 8 August 2011. Eisserer, Clemens. \"HTML5/Canvas backend for Caciocavallo (GNU-Classpath)\". John Zukowski, Java AWT Reference, O'Reilly, 1997. Website https://www.mygreatlearning.com https://www.w3schools.com https://beginnersbook.com CU IDOL SELF LEARNING MATERIAL (SLM) 296
UNIT – 13: JAVA DATABASE CONNECTIVITY STRUCTURE 13.0 Learning Objectives 13.1 Introduction 13.2 Java Database Connectivity 13.3 Establishing a Connection 13.4 Transactions with Database 13.5 Summary 13.6 Keywords 13.7 Learning Activity 13.8 Unit End Questions 13.9 References 13.0 LEARNING OBJECTIVES After studying this unit, you will be able to: Illustrate Java Database Connectivity Explain establishing a Connection Decsribe transactions with Database 13.1 INTRODUCTION JDBC or Java Database Connectivity is a specification from Sun microsystems that provides a standard abstraction (that is API or Protocol) for java applications to communicate with various databases. It provides the language with java database connectivity standard. It is used to write programs required to access databases. JDBC along with the database driver is capable of accessing databases and spreadsheets. The enterprise data stored in a relational database (RDB) can be accessed with the help of JDBC APIs. Definition of JDBC (Java Database Connectivity) JDBC is an API (Application programming interface) which is used in java programming to interact with databases. The classes and interfaces of JDBC allow application to send request made by users to the specified database. CU IDOL SELF LEARNING MATERIAL (SLM) 297
Purpose of JDBC Enterprise applications that are created using the JAVA EE technology need to interact with databases to store application-specific information. So, interacting with a database requires efficient database connectivity which can be achieved by using the ODBC (Open database connectivity) driver. This driver is used with JDBC to interact or communicate with various kinds of databases such as Oracle, MS Access, Mysql and SQL server database. 13.2 JAVA DATABASE CONNECTIVITY JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database. There are four types of JDBC drivers: JDBC-ODBC Bridge Driver, Native Driver, Network Protocol Driver, and Thin Driver We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API, we can save, update, delete and fetch data from the database. It is like Open Database Connectivity (ODBC) provided by Microsoft. The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces for JDBC API. A list of popular interfaces of JDBC API is given below: Driver interface Connection interface Statement interface PreparedStatement interface CallableStatement interface ResultSet interface ResultSetMetaData interface DatabaseMetaData interface RowSet interface A list of popular classes of JDBC API is given below: DriverManager class CU IDOL SELF LEARNING MATERIAL (SLM) 298
Blob class Clob class Types class Why Should We Use JDBC? Before JDBC, ODBC API was the database API to connect and execute the query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language). We can use JDBC API to handle database using Java program and can perform the following activities: Connect to the database Execute queries and update statements to the database Retrieve the result received from the database. 13.3 ESTABLISHING A CONNECTION Before establishing a connection between front end i.e your Java Program and back end i.e the database we should learn what precisely a JDBC is and why it came to existence. What is JDBC? JDBC is an acronym for Java Database Connectivity. It’s advancement for ODBC (Open Database Connectivity). JDBC is a standard API specification developed in order to move data from frontend to backend. This API consists of classes and interfaces written in Java. It basically acts as an interface (not the one we use in Java) or channel between your Java program and databases i.e it establishes a link between the two so that a programmer could send data from Java code and store it in the database for future use. Why JDBC came into existence? As previously told JDBC is advancement for ODBC, ODBC being platform dependent had a lot of drawbacks. ODBC API was written in C, C++, Python, Core Java and as we know above languages (except Java and some part of Python) are platform dependent . Therefore to remove dependence, JDBC was developed by database vendor which consisted of classes and interfaces written in Java. Steps for connectivity between Java program and database 1. Loading the Driver CU IDOL SELF LEARNING MATERIAL (SLM) 299
To begin with, you first need load the driver or register it before using it in the program . Registration is to be done once in your program. You can register a driver in one of two ways mentioned below: Class.forName (): Here we load the driver’s class file into memory at the runtime. No need of using new or creation of object .The following example uses Class.forName() to load the Oracle driver – Class.forName (“oracle.jdbc.driver.OracleDriver”); DriverManager.registerDriver (): DriverManager is a Java inbuilt class with a static member register. Here we call the constructor of the driver class at compile time. The following example uses DriverManager.registerDriver()to register the Oracle driver DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver ()) 2. Create the connections After loading the driver, establish connections using : Connection con = DriverManager.getConnection (url,user,password) user – username from which your sql command prompt can be accessed. password – password from which your sql command prompt can be accessed. con: is a reference to Connection interface. url : Uniform Resource Locator. It can be created as follows: String url = “ jdbc:oracle:thin:@localhost:1521:xe” Where oracle is the database used, thin is the driver used , @localhost is the IP Address where database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above are of String type and are to be declared by programmer before calling the function. Use of this can be referred from final code. 3. Create a statement Once a connection is established you can interact with the database. The JDBCStatement, CallableStatement, and PreparedStatement interfaces define the methods that enable you to send SQL commands and receive data from your database. Use of JDBC Statement is as follows: Statement st = con.createStatement(); Here, con is a reference to Connection interface used in previous step. 4. Execute the query CU IDOL SELF LEARNING MATERIAL (SLM) 300
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334