Programming in JAVAII 1 Chapter 1 AWT Swing

  • Slides: 30
Download presentation
Programming in JAVA-II 1

Programming in JAVA-II 1

Chapter# 1 AWT & Swing 2

Chapter# 1 AWT & Swing 2

What is Java AWT? Java AWT (Abstract Windowing Toolkit) is an API to develop

What is Java AWT? Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application 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 uses the resources of system. The java. awt package provides classes for AWT api such as Text. Field, Label, Text. Area, Radio. Button, Check. Box, Choice, List etc. AWT contains large number of classes and methods. AWT is the foundation upon which Swing is made. It is used for GUI programming in Java. But now a days it is merely used because most GUI java programs are implemented using Swing because of its rich implementation of GUI controls and light-weighted nature. 3

Java AWT Hierarchy Component class is at the top of AWT hierarchy. Component is

Java AWT Hierarchy Component class is at the top of AWT hierarchy. Component is an abstract class that encapsulates all attribute of visual component. A component object is responsible for remembering the current foreground and background colors and the currently selected text font. 4

Java AWT Hierarchy Container is a component in AWT that contains another component like

Java AWT Hierarchy Container is a component in AWT that contains another component like button, text field, tables etc. Container is a subclass of component class. Conatiner class keeps track of components that are added to another component. Panel The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc. Window class creates a top level window. Window does not have borders and menubar. 5

Java AWT Hierarchy Frame is a sub class of Window and have resizing canvas.

Java AWT Hierarchy Frame is a sub class of Window and have resizing canvas. It is a container that contain several different components like button, title bar, textfield, label etc. In Java, most of the AWT applications are created using Frame window. Frame class has two different constructors, Frame() throws Headless. Exception Frame(String title) throws Headless. Exception 6

Creating a Frame There are two ways to create a Frame. They are, 1.

Creating a Frame There are two ways to create a Frame. They are, 1. By Instantiating Frame class 2. By extending Frame class 7

Creating Frame Window by Instantiating Frame class import java. awt. *; public class Testawt

Creating Frame Window by Instantiating Frame class import java. awt. *; public class Testawt { Testawt() { Frame fm=new Frame(); //Creating a frame. Label lb = new Label("welcome to java graphics"); //Creating a label fm. add(lb); //adding label to the frame. fm. set. Size(300, 300); //setting frame size. fm. set. Visible(true); //set frame visibilty true. } public static void main(String args[]) { Testawt ta = new Testawt(); } } 8

Creating Frame window by extending Frame package testawt; class import java. awt. *; import

Creating Frame window by extending Frame package testawt; class import java. awt. *; import java. awt. event. *; public class Testawt extends Frame { public Testawt() { Button btn=new Button("Hello World"); add(btn); //adding a new Button. set. Size(400, 500); //setting size. set. Title("Study. Tonight"); //setting title. set. Layout(new Flow. Layout()); //set default layout for frame. set. Visible(true); //set frame visibilty true. } public static void main (String[] args) { Testawt ta = new Testawt(); //creating a frame. } } 9

Swing Framework contains a set of classes that provides more powerful and flexible GUI

Swing Framework contains a set of classes that provides more powerful and flexible GUI components than those of AWT. Swing provides the look and feel of modern Java GUI. Swing library is an official Java GUI tool kit released by Sun Microsystems. It is used to create graphical user interface with Java. It is build upon top of AWT API and acts as replacement of AWT API as it has almost every control corresponding to AWT controls. 10

Introduction to Swing Classes JPanel : JPanel is Swing's version of AWT class Panel

Introduction to Swing Classes JPanel : JPanel is Swing's version of AWT class Panel and uses the same default layout, Flow. Layout. JPanel is descended directly from JComponent. JFrame : JFrame is Swing's version of Frame and is descended directly from Frame class. The component which is added to the Frame, is refered as its Content. JWindow : This is Swing's version of Window and hass descended directly from Window class. Like Windowit uses Border. Layout by default. JLabel : JLabel descended from Jcomponent, and is used to create text labels. JButton : JButton class provides the functioning of push button. JButton allows an icon, string or both associated with a button. JText. Field : JText. Fields allow editing of a single line of text. 11

Creating a JFrame There are two way to create a JFrame Window. 1. By

Creating a JFrame There are two way to create a JFrame Window. 1. By instantiating JFrame class. 2. By extending JFrame class. 12

Creating JFrame window by Instantiating JFrame class import javax. swing. *; import java. awt.

Creating JFrame window by Instantiating JFrame class import javax. swing. *; import java. awt. *; public class First { JFrame jf; public First() { jf = new JFrame("My. Window"); //Creating a JFrame with name My. Window. JButton btn = new JButton("Say Hello"); //Creating a Button. jf. add(btn); //adding button to frame. jf. set. Layout(new Flow. Layout()); //setting layout using Flow. Layout object. jf. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); //setting close operation. jf. set. Size(400, 400); //setting size jf. set. Visible(true); //setting frame visibilty } public static void main(String[] args) { new First(); } } 13

Creating JFrame window by extending JFrame class import javax. swing. *; import java. awt.

Creating JFrame window by extending JFrame class import javax. swing. *; import java. awt. event. *; import java. awt. *; public class Second extends JFrame { public Second() { set. Title("My. Window"); JLabel lb = new JLabel("Welcome to My Second Window"); //Creating a label. add(lb); //adding label to frame. set. Layout(new Flow. Layout()); //setting layout using Flow. Layout object. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); //setting close operation. set. Size(400, 400); //setting size set. Visible(true); //setting frame visibilty } public static void main(String[] args) { new Second(); } } 14

Layout Manager Layout means the arrangement of components within the container. In other way

Layout Manager Layout means the arrangement of components within the container. In other way we can say that placing the components at a particular position within the container. The task of layouting the controls is done automatically by the Layout Manager. The layout manager automatically positions all the components within the container. If we do not use layout manager then also the components are positioned by the default layout manager. It is possible to layout the controls by hand but it becomes very difficult because of the following two reasons. ◦ It is very tedious to handle a large number of controls within the container. ◦ Oftenly the width and height information of a component is not given when we need to arrange them. 15

Layout Manager To change the layout manager for a container, use the set. Layout()

Layout Manager To change the layout manager for a container, use the set. Layout() method. Ø Syntax: set. Layout(Layout. Manager obj) Ø The predefined managers are listed below: 1. 2. 3. 4. 5. 6. Flow. Layout Border. Layout Grid. Layout Box. Layout Card. Layout Grid. Bag. Layout 16

AWT Layout Manager Classes: Ø Border. Layout: The borderlayout arranges the components to fit

AWT Layout Manager Classes: Ø Border. Layout: The borderlayout arranges the components to fit in the five regions: east, west, north, south and center. Ø Card. Layout: The Card. Layout object treats each component in the container as a card. Only one card is visible at a time. Ø Flow. Layout: The Flow. Layout is the default layout. It layouts the components in a directional flow. Ø Grid. Layout: The Grid. Layout manages the components in form of a rectangular grid. Ø Grid. Bag. Layout: This is the most flexible layout manager class. The object of Grid. Bag. Layout aligns the component vertically, horizontally or along their baseline without requiring the components of same size. Ø Group. Layout: The Group. Layout hierarchically groups components in order to position them in a Container. 17

AWT Layout Manager Classes: 1 NORTH 2 3 4 5 6 WEST CENTER EAST

AWT Layout Manager Classes: 1 NORTH 2 3 4 5 6 WEST CENTER EAST Flow. Layout 1 2 3 4 5 6 7 8 9 10 11 12 SOUTH Border. Layout 1 1 2 3 1 3 2 3 Box. Layout 2 2 Grid. Layout 3 4 1 2 3 5 6 8 9 4 7 4 Grid. Bag. Layout Card. Layout 18

AWT Layout Manager Classes: Examples: JPanel p 1=new JPanel(); p 1. set. Layout(new Flow.

AWT Layout Manager Classes: Examples: JPanel p 1=new JPanel(); p 1. set. Layout(new Flow. Layout()); p 1. set. Layout(new Border. Layout()); p 1. set. Layout(new Grid. Layout(3, 4)); 19

JFrame Container JFrame : This is a top-level container which can hold components and

JFrame Container JFrame : This is a top-level container which can hold components and containers like panels. Constructors: JFrame() JFrame(String title) Important Methods set. Size(int width, int height) – Specifies size of the frame in pixels set. Location(int x, int y) - Specifies upper left corner set. Visible(boolean visible) - Set true to display the frame set. Title(String title) - Sets the frame title set. Defualt. Close. Operation(int mode) - Specifies the operation when frame is closed. The modes are: JFrame. EXIT_ON_CLOSE JFrame. DO_NOTHING_ON_CLOSE JFrame. HIDE_ON_CLOSE JFrame. . DISPOSE_ON_CLOSE pack() - Sets frame size to minimum size required to hold components 20

Important Components JButton : A swing button can display both text and an image.

Important Components JButton : A swing button can display both text and an image. The underlined letter in each button’s text shows the mnemonic which is the keyboard alternative. Constructors: JButton(Icon I) JButton(String s, Icon I) 21

Program to demonstrate Jpanel as a subcontainer import java. awt. *; import javax. swing.

Program to demonstrate Jpanel as a subcontainer import java. awt. *; import javax. swing. *; public class swing. Frame extends JFrame { swing. Frame() { JButton jb 1=new JButton("Oky"); JButton jb 2=new JButton("Cancel"); set. Size(300, 200); set. Layout(new Border. Layout()); JPanel jp 1=new JPanel(new Grid. Layout(4, 3)); for(int i=1; i<=9; i++) { jp 1. add(new JButton(""+i)); } jp 1. add(new JButton(""+0)); jp 1. add(new JButton("C")); jp 1. add(new JButton("CE")); JPanel jp 2=new JPanel(new Border. Layout()); jp 2. add(new JText. Field("Enter"), Border. Layout. NORTH); jp 2. add(jp 1, Border. Layout. CENTER); add(new JButton("="), Border. Layout. EAST); add(jp 2, Border. Layout. CENTER); set. Title("Calculator"); set. Visible(true); } public static void main(String args[]) { new swing. Frame(); } } 22

Program to demonstrate Button and text field. import java. awt. *; import javax. swing.

Program to demonstrate Button and text field. import java. awt. *; import javax. swing. *; import java. awt. event. *; public class test extends JFrame implements Action. Listener { JText. Field jtf; JButton jb; public test() { set. Layout(new Flow. Layout()); jtf=new JText. Field(15); add(jtf); jb=new JButton("Click Me"); jb. add. Action. Listener(this); add(jb); set. Size(200, 200); set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); set. Visible(true); } public void action. Performed(Action. Event ae) { jtf. set. Text(ae. get. Action. Command()); } public static void main(String[] args) { new test(); } } 23

Explanation of previous program Ø Components such as the Button and JButton fire off.

Explanation of previous program Ø Components such as the Button and JButton fire off. Action. Events to indicate some kind of component-defined action. For example, the Button fires off an Action. Event whenever the user presses it. Ø The entire point of an event is to inform a listener that something has happened to a component in the GUI. Ø An event includes all of the information that a listener needs to figure out what happened and to whom it happened (the what and who of the event). Ø An event must give enough information to fully describe itself. That way, a listener can figure out what exactly happened and respond in a meaningful way. Ø The Action. Event includes methods for learning the action's command string, modifiers, and identification string. The get. Action. Command() method returns the command string that indicates the event's intended action, such as print or copy (the what). 24

Program to demonstrate JCheck. Box. import java. awt. *; import java. awt. event. *;

Program to demonstrate JCheck. Box. import java. awt. *; import java. awt. event. *; import javax. swing. *; public class frame. Demo extends JFrame implements Item. Listener { JText. Field j. Txt; JCheck. Box jcb 1, jcb 2; frame. Demo() { set. Layout(new Flow. Layout()); jcb 1=new JCheck. Box("Swing Demo s"); jcb 1. add. Item. Listener(this); add(jcb 1); jcb 2=new JCheck. Box("Java Demos s"); jcb 2. add. Item. Listener(this); add(jcb 2); public void item. State. Changed(Item. Event ie) { String text=""; if(jcb 1. is. Selected()) text=text+jcb 1. get. Text()+""; if(jcb 2. is. Selected()) text=text+jcb 2. get. Text(); j. Txt. set. Text(text); j. Txt=new JText. Field(15); add(j. Txt); set. Size(200, 300); set. Visible(true); set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); } public static void main(String args[]) { } new frame. Demo(); } } 25

Program to demonstrate JRadio. Button. class My. Java. Porgrams extends JFrame implements Action. Listener

Program to demonstrate JRadio. Button. class My. Java. Porgrams extends JFrame implements Action. Listener { JRadio. Button male, female; My. Java. Porgrams () { male = new JRadio. Button("male"); male. add. Action. Listener(this); female = new JRadio. Button("Female"); female. add. Action. Listener(this); Button. Group b. G = new Button. Group(); b. G. add(male); b. G. add(female); set. Size(300, 400); set. Location. Relative. To(null); set. Layout( new Flow. Layout()); add(male); add(female); male. set. Selected(true); this. set. Visible(true); } public void action. Performed(Action. Event evt) { JRadio. Button rbn=(JRadio. Button)evt. get. Source(); if(rbn==male) { JOption. Pane. show. Message. Dialog(this, "Male is selected"); } if(rbn==female) { JOption. Pane. show. Message. Dialog(this, "Female is selected"); } } public static void main(String args[]) { My. Java. Porgrams j = new My. Java. Porgrams(); } } 26

import java. awt. *; import java. awt. event. *; import javax. swing. *; public

import java. awt. *; import java. awt. event. *; import javax. swing. *; public class My. Java. Programs extends JFrame { My. Java. Programs() { set. Layout(new Flow. Layout()); JLabel lbl=new JLabel("Colors: "); add(lbl); JCombo. Box jcb=new JCombo. Box(); jcb. add. Item("Red"); jcb. add. Item("Green"); jcb. add. Item("Blue"); add(jcb); set. Size(200, 300); set. Location. Relative. To(null); set. Visible(true); set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); Program to demonstrate JCombo. Box. } public static void main(String args[]) { new My. Java. Programs(); } } 27

User Login with username and password import java. awt. *; import java. awt. event.

User Login with username and password import java. awt. *; import java. awt. event. *; import javax. swing. *; class Invalid. Password. Exception extends Exception {} public class Name. Password extends JFrame implements Action. Listener { JLabel name, pass; JText. Field name. Text; JPassword. Field pass. Text; JButton login, end; static int attempt=0; public Name. Password() { name = new JLabel("Name: ", JLabel. RIGHT); pass = new JLabel("Password: ", JLabel. RIGHT); Container c = get. Content. Pane(); c. set. Layout(new Grid. Layout(3, 2)); c. add(name. Text); c. add(pass. Text); c. add(login); c. add(end); name. Text = new JText. Field(20); pass. Text = new JPassword. Field(20); login = new JButton("Login"); end = new JButton("End"); set. Title("Login Check"); set. Size(250, 150); set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); set. Visible(true); login. add. Action. Listener(this); end. add. Action. Listener(this); } 28

User Login with username and password public void action. Performed(Action. Event ae) { JButton

User Login with username and password public void action. Performed(Action. Event ae) { JButton btn = (JButton)ae. get. Source(); if(btn == end) { System. exit(0); } if(btn == login) { try { String user = name. Text. get. Text(); String pass = new String(pass. Text. get. Password()); if(user. compare. To(pass)==0) { JOption. Pane. show. Message. Dialog(null, "Login Successful", "Login", JOption. Pane. INFORMATION_MESSAGE); System. exit(0); } else { throw new Invalid. Password. Exception(); } } 29

User Login with username and password catch(Exception e) { attempt++; JOption. Pane. show. Message.

User Login with username and password catch(Exception e) { attempt++; JOption. Pane. show. Message. Dialog(null, "Login Failed", "Login", JOption. Pane. ERROR_MESSAGE); pass. Text. request. Focus(); pass. Text. set. Text(""); if(attempt == 3) { JOption. Pane. show. Message. Dialog(null, "3 Attempts Over", "Login", JOption. Pane. ERROR_MESSAGE); System. exit(0); } } public static void main(String args[]) { new Name. Password(); } } 30