GUI Programming With Swing Introduction - BVRIT Hyderabad

Transcription

1GUI Programming with Swing – IntroductionGUI ( Graphical User Interface) , Here the user interact with any application by clicking onsome images or graphics.Example: if the user wants to print a file, he can click on the printer images and the rest of thethings will be taken care of by the application.Like magnifying glass symbol for searching, a briefcase symbol for a directory etc.Hence, the environment where the user can interact with the application through graphics orimages is called GUI (Graphical User Interface) GUI is user friendlyIt gives attraction and beauty to any application by adding pictures, colors, menus,animation etc.It is possible to simulate a real life objects using GUIGUI helps to create graphical components like push buttons, radio buttons, checkboxes etc.Java AWT (Abstract Window Toolkit)Java AWT is an API to develop GUI (Graphical User Interface) or window-basedapplications in java represents a class library to develop application using GUI Java.awt package got classes and interfacesJava AWT components are platform-dependentComponents are displayed according to the view of operating system.AWT is heavyweight i.e. its components are using the resources of OS.The java.awt package provides classes for AWT API such as ce,ListButton

2Java AWT HierarchyThe hierarchy of Java AWT classes are given below.Components:A component represents an object which is displayed pictorially on the screen. For example,we create an object of Button class as:Button b new Button();Now, b is object of Button class, If we display this b on the screen, it displays a push button.Therefore, the object b, on going to the screen is becoming a component called ‘PushButton’.In the same way any component is a graphical representation of an object. Push Buttons,radio buttons, check boxes etc are all components

3ContainerThe Container is a component in AWT that can contain another components like Buttons,Textfields, labels etc. The classes that extend Container class are known as container such asFrame, Dialog and Panel.WindowThe window is the container that have no borders and menu bars. You must use frame, dialogor another window for creating a window.PanelThe Panel is the container that doesn't contain title bar and menu bars. It can have othercomponents like button, textfield etc.FrameThe Frame is the container that contain title bar and can have menu bars. It can have othercomponents like button, textfield etc.Useful Methods of Component ClassMethodpublic void add(Component c)public void setSize (int width, int height)public void setLayout(LayoutManager m)public void setVisible(boolean status)Descriptioninserts a component on this component.sets the size (width and height) of thecomponent.defines the layout manager for the component.changes the visibility of the component, bydefault false.Java AWT ExampleTo create simple awt example, you need a frame. There are two ways to create a frame inAWT. By extending Frame class (inheritance)By creating the object of Frame class (association)

4AWT Example by InheritanceProgram1: Example program to create a frameimport java.awt.Frame;public class FirstFrame {public static void main(String[] args) {Frame f new Frame ("My First tput:AWT Example by AssociationLet's see a simple example of AWT where we are creating instance of Frame class. Here, weare showing Button component on the Frame.import java.awt.*;class First2{First2(){Frame f new Frame();Button b new Button("BVRIT HYDERABAD");b.setBounds(30,50,80,30);f.add(b);

(true);}public static void main(String args[]){First2 f new First2();}}After executing this program we observe that the frame can be minimized, maximizedand resized but cannot be closed. Even if we click on the close button of the frame, itwill not perform any closing action.Then how to close the frame?Closing a frame means attaching action to the component. To attach action to the framewe need “EVENT DELIGATION MODEL”

6EVENT DELIGATION MODELAn event represents a specific action done on the component ClickingDouble ClickingTyping data inside the componentMouse over etcWhen an event is generated on the component, the component will not know about it becauseit cannot listen to the event. To let the component understand that an event occurred on it, weshould add some listeners to the components.A listener is an interface which listens to an event coming from a component.A listener will have some abstract methods which need to be implemented by theprogrammer.When an even is generated by the user on the component, the event is not handled bythe component; on the other hand, the component sends (delegate) the event to thelistener attached to it. The listener will not handle the event. It hands over (Delegates)the event to an appropriate method. Finally, the method is executed and the event ishandled. This is called ‘Event Delegation Model’Steps involved in the Event Delegation Model are: We should attach an appropriate listener to a component. This is done usingaddxxxListener() method. Similarly, to remove a listener from a component, we canuse removexxxListener() methodImplement the methods of the listener, especially the method which handles the event.When an event is generated on the component, then the method in step2 will beexecuted and the event is handled.

7Closing the Frame:We know frame is also a component. We want to close the frame by clicking on its closebutton. Let us follow these steps to see how to use event delegation model to do this.We should attach a listener to the frame component. Remember, all listeners are available injava.awt.event package.The most suitable listener to the frame is ‘window listener’ it can be attached using addWindowListener() method as;f.addWindowListener(WindowListener obj);Note that, the addWindowListerner() method has a parameter that is expecting object ofWindowListener interface. Since it is not possible to create an object to an interface, weshould create an object to the implemented class of the interface and pass it to the method.Implement all the methods of the WindowListener interface. The following methods arefound in WindowListener interface.public void windowActivated(WindowEvent e)public void windowClosed(WindowEvent e)public void windowClosing(WindowEvent e)public void windowDeactivated(WindowEvent e)public void windowDeiconified(WindowEvent e)public void windowOpened(WindowEvent e)In all the preceding methods, WindowListener interface calls the public voidWindowClosing() method when the frame is being closed. So, implementing this methodalone is enough as:Public void windowClosing(WindowEvent e) {System.exit(0); // closing the application}For the remaining methods, we can provide empty body.So, when the frame is closed, the body of this method is executed and the application getsclosed. In this way we can handle the frame closing event.

8Write a program to create a frame and then close it on clicking the close buttonimport java.awt.*;import java.awt.event.*;class MyFrame extends Frame{public static void main(String args[]) {MyFrame f new MyFrame();f.setTitle("My AWT Frame");f.setSize(400, 250);f.setVisible(true);f.addWindowListener(new MyClass());}}class MyClass implements WindowListener{public void windowActivated(WindowEvent e) { }public void windowClosed(WindowEvent e) { }public void windowClosing(WindowEvent e){System.exit(0);}public void windowDeactivated(WindowEvent e) { }public void windowIconified(WindowEvent e) { }public void windowDeiconified(WindowEvent e) { }public void windowOpened(WindowEvent e) { }}Output:Now this window is able to close

9In the above program we not only create a frame but also close the frame when the userclicks on the close button.In the above example, we had to mention all the methods of WindowListener interface, justfor the sake of one method.There is another way to do this. There is a class WindowAdapter in java.awt.event package. That contains all themethods of the WindowListener interface with an empty implementation.If we extend MyClass from this WindowAdapter class, then we need not write all themethods with emply implementation.We can write only that method which we need.// Program: Frame closing with WindowAdapter classimport java.awt.*;import java.awt.event.*;class MyFrame1 extends Frame {public static void main(String args[]){MyFrame1 f new MyFrame1();f.setTitle("My AWT dWindowListener(new MyClass());}}class MyClass extends WindowAdapter{public void windowClosing(WindowEvent e){System.exit(0);}}Output:

10What is an adapter class?An adapter class is an implementation class of a listener interface which contains all methodsimplemented with empty body. For example, WindowAdapter is an adapter class ofWindowListener interface.In the above program, the code of MyClass can be copied directly into addWIndowListener()method asf.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});In this code, we cannot find the name of MyClass anywhere in the code. It means the name ofMyClass is hidden in MyFrame class and hence MyClass is an inner class in MyFrame classwhose name is not mentioned. Such inner class is called ‘anonymous inner class’;What is anonymous inner class?Anonymous inner class is an inner class whose name is not mentioned, and for which onlyone object is created.Program to close the frame using an Anonymous inner class.// Frame closing with WindowAdapter classimport java.awt.*;import java.awt.event.*;class MyFrame2 extends Frame {public static void main(String args[]){MyFrame2 f new MyFrame2();f.setTitle("My AWT dWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}}

11Output:Program: Displaying text message in the frame using drawstring() Methodimport java.awt.*;import java.awt.event.*;class Message extends Frame {Message(){addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public void paint(Graphics g) {this.setBackground(new Color(100,20,20));Font f new Font ("Arial", Font.BOLD ow);g.drawString("Hello Gabber! How are you?", 50,100);}public static void main(String args[]){Message m new Message();

12m.setSize(400,250);m.setTitle("This is my Text");m.setVisible(true);}}Output:Program2: to create frame and adding a buttonLet's see a simple example of AWT where we are inheriting Frame class. Here, we areshowing Button component on the Frame.import java.awt.Button;import java.awt.Frame;class FirstFrameAndButton extends Frame{public static void main(String args[]){Frame f new Frame();Button b new Button("click me");b.setBounds(30,100,80,30);// setting button positionf.add(b);//adding button into framef.setSize(300,300);//frame size 300 width and 300 heightf.setLayout(null);//no layout managerf.setVisible(true);//now frame will be visible, by default notvisible}}

13OutputThe setBounds(int xaxis, int yaxis, int width, int height) method is used in the aboveexample that sets the position of the awt button.Event and Listener (Java Event Handling)Changing the state of an object is known as an event. For example, click on button,dragging mouse etc. The java.awt.event package provides many event classes and Listenerinterfaces for event handling.Java Event classes and Listener interfacesEvent ClassesListener Listener and er

stenerSteps to perform Event HandlingFollowing steps are required to perform event handling:1. Register the component with the ListenerRegistration MethodsFor registering the component with the Listener, many classes provide the registrationmethods. For example:oButtonooMenuItemooopublic void addActionListener(ActionListener a){}TextFieldopublic void addActionListener(ActionListener a){}opublic void addTextListener(TextListener a){}TextAreaoopublic void addActionListener(ActionListener a){}public void addTextListener(TextListener a){}Checkbox

15ooChoiceoopublic void addItemListener(ItemListener a){}public void addItemListener(ItemListener a){}Listopublic void addActionListener(ActionListener a){}opublic void addItemListener(ItemListener a){}Java Event Handling CodeWe can put the event handling code into one of the following places:1. Within class2. Other class3. Anonymous classJava event handling by implementing ActionListenerimport java.awt.*;import java.awt.event.*;class AEvent extends Frame implements ActionListener{TextField tf;AEvent(){//create componentstf new TextField();tf.setBounds(60,50,170,20);Button b new Button("click me");b.setBounds(100,120,80,30);//register listenerb.addActionListener(this);//passing current instance//add components and set size, layout and t(null);setVisible(true);addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public void actionPerformed(ActionEvent e){tf.setText("BVRIT HYDERABAD");

16}public static void main(String args[]){new AEvent();}}Output:public void setBounds(int xaxis, int yaxis, int width, int height); have been used in theabove example that sets the position of the component it may be button, textfield etc.

17Java AWT ButtonThe button class is used to create a labeled button that has platform independentimplementation. The application result in some action when the button is pushed.AWT Button Class declarationpublic class Button extends Component implements AccessibleJava AWT Button Example//AWT Button Class declarationimport java.awt.*;import java.awt.event.*;public class ButtonExample {public static void main(String[] args) {Frame f new Frame("Button Example");Button b new Button("Goto ;f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}}Output:

18Java AWT LabelThe object of Label class is a component for placing text in a container. It is used to display asingle line of read only text. The text can be changed by an application but a user cannot editit directly.AWT Label Class Declarationpublic class Label extends Component implements AccessibleJava Label Example//AWT Label Class declarationimport java.awt.*;import java.awt.event.*;class LabelExample{public static void main(String args[]){Frame f new Frame("Label Example");Label l1,l2;l1 new Label("User Name");l1.setBounds(50,100, 100,30);l2 new Label("Password");l2.setBounds(50,150, 100,30);f.add(l1); etVisible(true);f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}}Output:

19Java AWT TextFieldThe object of a TextField class is a text component that allows the editing of a single linetext. It inherits TextComponent class.AWT TextField Class Declarationpublic class TextField extends TextComponentJava AWT TextField Exampleimport java.awt.*;import java.awt.event.*;class TextFieldExample{public static void main(String args[]){Frame f new Frame("TextField Example");TextField t1,t2;t1 new TextField("Anil Kumar");t1.setBounds(50,100, 200,30);t2 new TextField("Hyderabad");t2.setBounds(50,150, 200,30);f.add(t1); etVisible(true);f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}}Output:

20Java AWT TextAreaThe object of a TextArea class is a multi line region that displays text. It allows the editing ofmultiple line text. It inherits TextComponent class.AWT TextArea Class Declarationpublic class TextArea extends TextComponentJava AWT TextArea Exampleimport java.awt.*;import java.awt.event.*;public class TextAreaExample{TextAreaExample(){Frame f new Frame();TextArea area new TextArea("Welcome to BVRIT HYDERABAD");area.setBounds(50,100, t(null);f.setVisible(true);f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String args[]){new TextAreaExample();}}Output:

21Java AWT CheckboxThe Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off(false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".AWT Checkbox Class Declarationpublic class Checkbox extends Component implements ItemSelectable, AccessibleJava AWT Checkbox Exampleimport java.awt.*;import java.awt.event.*;public class CheckboxExample{CheckboxExample(){Frame f new Frame("Checkbox Example");Checkbox checkbox1 new Checkbox("C ");checkbox1.setBounds(100,100, 50,50);Checkbox checkbox2 new Checkbox("Java", true);checkbox2.setBounds(100,150, 50,50);Checkbox checkbox3 new Checkbox("Python");checkbox3.setBounds(100,200, 70,50);Checkbox checkbox4 new Checkbox("Haskell", tVisible(true);f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String args[]){new CheckboxExample();}}

22Output:Java AWT CheckboxGroupThe object of CheckboxGroup class is used to group together a set of Checkbox. At a timeonly one check box button is allowed to be in "on" state and remaining check box button in"off" state. It inherits the object class.Note: CheckboxGroup enables you to create radio buttons in AWT. There is no specialcontrol for creating radio buttons in AWT.AWT CheckboxGroup Class Declarationpublic class CheckboxGroup extends Object implements SerializableJava AWT CheckboxGroup Exampleimport java.awt.*;import java.awt.event.*;public class CheckboxGroupExample{CheckboxGroupExample(){Frame f new Frame("CheckboxGroup Example");CheckboxGroup cbg new CheckboxGroup();Checkbox checkBox1 new Checkbox("C ", cbg, false);checkBox1.setBounds(100,100, 50,50);Checkbox checkBox2 new Checkbox("Java", cbg, true);checkBox2.setBounds(100,150, (400,400);f.setLayout(null);f.setVisible(true);

23f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String args[]){new CheckboxGroupExample();}}Output:

24Java AWT ChoiceThe object of Choice class is used to show popup menu of choices. Choice selected by user isshown on the top of a menu. It inherits Component class.AWT Choice Class Declarationpublic class Choice extends Component implements ItemSelectable, AccessibleJava AWT Choice Exampleimport java.awt.*;import java.awt.event.*;public class ChoiceExample{ChoiceExample(){Frame f new Frame();Choice c new Choice();c.setBounds(100,100, 75,75);c.add("C r(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String args[]){new ChoiceExample();}}Output:

25Java AWT ListThe object of List class represents a list of text items. By the help of list, user can chooseeither one item or multiple items. It inherits Component class.AWT List class Declarationpublic class List extends Component implements ItemSelectable, AccessibleJava AWT List Exampleimport java.awt.*;import java.awt.event.*;public class ListExample{ListExample(){Frame f new Frame();List l1 new List(5);l1.setBounds(100,100, (true);f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String args[]){new ListExample();}}Output:

26Java AWT CanvasThe Canvas control represents a blank rectangular area where the application can draw or trapinput events from the user. It inherits the Component class.AWT Canvas class Declarationpublic class Canvas extends Component implements AccessibleJava AWT Canvas Exampleimport java.awt.*;import java.awt.event.*;public class CanvasExample{public CanvasExample(){Frame f new Frame("Canvas Example");f.add(new MyCanvas());f.setLayout(null);f.setSize(400, 400);f.setVisible(true);f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String args[]){new CanvasExample();}}class MyCanvas extends Canvas{public MyCanvas() {setBackground (Color.GRAY);setSize(300, 200);}public void paint(Graphics g){g.setColor(Color.blue);g.fillOval(75, 75, 150, 75);}}Output:

27Java AWT ScrollbarThe object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar isa GUI component allows us to see invisible number of rows and columns.AWT Scrollbar class declarationpublic class Scrollbar extends Component implements Adjustable, AccessibleJava AWT Scrollbar Exampleimport java.awt.*;import java.awt.event.*;class ScrollbarExample{ScrollbarExample(){Frame f new Frame("Scrollbar Example");Scrollbar s new Scrollbar();s.setBounds(100,100, ll);f.setVisible(true);f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String args[]){new ScrollbarExample();

28}}Output:Java AWT MenuItem and MenuThe object of MenuItem class adds a simple labeled menu item on menu. The items used in amenu must belong to the MenuItem or any of its subclass.The object of Menu class is a pull down menu component which is displayed on the menubar. It inherits the MenuItem class.AWT MenuItem class declarationpublic class MenuItem extends MenuComponent implements AccessibleAWT Menu class declarationpublic class Menu extends MenuItem implements MenuContainer, AccessibleJava AWT MenuItem and Menu Exampleimport java.awt.*;import java.awt.event.*;class MenuExample{MenuExample(){Frame f new Frame("Menu and MenuItem Example");MenuBar mb new MenuBar();Menu menu new Menu("File");

29Menu submenu new Menu("Save As");MenuItem i1 new MenuItem("New");MenuItem i2 new MenuItem("Open");MenuItem i3 new MenuItem("Save");MenuItem i4 new MenuItem("Text File");MenuItem i5 new MenuItem("Word tener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String args[]){new MenuExample();}}Output:

30Java AWT PopupMenuPopupMenu can be dynamically popped up at specific position within a component. Itinherits the Menu class.AWT PopupMenu class declarationpublic class PopupMenu extends Menu implements MenuContainer, AccessibleJava AWT PopupMenu Exampleimport java.awt.*;import java.awt.event.*;class PopupMenuExample{PopupMenuExample(){final Frame f new Frame("PopupMenu Example");final PopupMenu popupmenu new PopupMenu("Edit");MenuItem cut new em copy new uItem paste new dd(paste);f.addMouseListener(new MouseAdapter() {public void mouseClicked(MouseEvent e) {popupmenu.show(f , e.getX(), stener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String args[]){new PopupMenuExample();}}

31Output:Java AWT PanelThe Panel is a simplest container class. It provides space in which an application can attachany other component. It inherits the Container class.It doesn't have title bar.AWT Panel class declarationpublic class Panel extends Container implements AccessibleJava AWT Panel Exampleimport java.awt.*;import java.awt.event.*;public class PanelExample {PanelExample(){Frame f new Frame("Panel Example");Panel panel new ckground(Color.gray);Button b1 new Button("Button lor.yellow);Button b2 new Button("Button 2");b2.setBounds(100,100,80,30);

32b2.setBackground(Color.green);panel.add(b1); er(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String args[]){new PanelExample();}}Output:

33Java AWT DialogThe Dialog control represents a top level window with a border and a title used to take someform of input from the user. It inherits the Window class.Unlike Frame, it doesn't have maximize and minimize buttons.Frame vs DialogFrame and Dialog both inherits Window class. Frame has maximize and minimize buttonsbut Dialog doesn't have.AWT Dialog class declarationpublic class Dialog extends WindowJava AWT Dialog Exampleimport java.awt.*;import java.awt.event.*;public class DialogExample {private static Dialog d;DialogExample() {Frame f new Frame();d new Dialog(f , "Dialog Example", true);d.setLayout( new FlowLayout() );Button b new Button ("OK");b.addActionListener ( new ActionListener(){public void actionPerformed( ActionEvent e ){DialogExample.d.setVisible(false);}});d.add( new Label ("Click button to ble(true);}public static void main(String args[]){new DialogExample();}}Output:

34

GUI ( Graphical User Interface) , Here the user interact with any application by clicking on some images or graphics. Example: if the user wants to print a file, he can click on the printer images and the rest of the . Java AWT is an API to develop GUI (Graphical User Interface) or window-based applications in java represents a class library .