1 / 107

GUI Programming, Building Applets and Introduction to Annotations:

GUI Programming, Building Applets and Introduction to Annotations: . Unit-5 By: Vishal Rajput Narmada College of Computer Application-523.

debbie
Télécharger la présentation

GUI Programming, Building Applets and Introduction to Annotations:

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. GUI Programming, Building Applets and Introduction to Annotations: Unit-5 By: VishalRajput Narmada College of Computer Application-523 Mr. Vishal Rajput

  2. An applet is a special kind of java program that is designed to be transmitted over the internet and automatically executed by a java-compatible web browser. • Furthermore, an applet is downloaded on demand, just like an image, sound file, or video clip. • The important difference is that an applet is an intelligent program, not just an animation or media file. • The Applet class is contained in the java.applet package. Applet contains several methods that give you detailed control over the execution of your applet. • Java.applet also defines 3 interfaces: AppletContext, AudioClip and AppletStub. • All applets are subclasses of Applet. Thus, all applets must import java.applet. Applet must also import java.awt (abstract window toolkit). Since all applets run in a window, it is necessary to include support for that window. Mr. Vishal Rajput

  3. Applets are not executed by the console based java run-time interpreter. Rather they are executed by either a web browser or an applet viewer called appletviewer, provided by the JDK. • Once an applet has been compiled, it is included in an HTML file using APPLET tag. The applet will be executed by a java-enabled web-browser when it encounters the APPLET tag within the HTML file. • This requires that the applet code imports the java.awt package that contains the Graphics class. All output operations of an applet are performed using the methods defined in the Graphics class. • A main() method is not invoked on an applet, and an applet class will not define main(). Mr. Vishal Rajput

  4. Demo Program import java.applet.Applet; import java.awt.Graphics; /* <applet code="FirstApplet" width=200 height=200> </applet> */ public class FirstApplet extends Applet { public void paint(Graphics g) { g.drawString("This is my first applet.",20,100); } } Mr. Vishal Rajput

  5. <html> <body> <applet code="SecondApplet.java" width=200 height=200> </applet> </body> </html> Mr. Vishal Rajput

  6. Javac FirstApplet.java • Appletviewer FirstApplet.java • The 1st and 2nd lines import the java.applet.Applet and java.awt.Graphics classes. • Applet class is the superclass of all applets. The Graphics class is provided by the awt. • The next lines define a java comment. That comment is HTML source code. The applet tag specifies which class contains the code for this applet. • It also defines the width and height in pixels of the display area. Applet viewer reads the HTML and interprets the info that is contained between the applet tags. • The HTML is not part of the applet and is not used by a web browser. It is used only by the applet viewer. • The next line declares that firstApplet extends Applet. Each applet that you create must extends this class. Mr. Vishal Rajput

  7. Paint() is responsible for generating the output of the applet. It accepts a Graphics object as its one argument. It is automatically invoked whenever the applet needs to be displayed. • The actual output of the string is done by calling the drawString() method of the Graphics object. x,y coordinate – at which to begin the string. • Applet viewer executes an applet by using the HTML source code. Width and height attributes of the applet tag define the dimensions of the applet display area. • Applet may also be executed by a web browser. Mr. Vishal Rajput

  8. Applet Life Cycle Born and initialization state • Applet enters the initialization state when it is first loaded. This is achieved by calling the init() method of Applet class. The applet is born. At this stage we may do the following if required: 1. Create objects needed by the applet 2. Set up initial values 3. Load images or fonts 4. Set up colors The initialization occurs only once in the applet’s life cycle. To provide any of the behaviors mentioned above, we must override the init() method. public void init() { Action } Mr. Vishal Rajput

  9. Running state(Start) • Applet enters the running state when the system calls the start() method of Applet class. • This occurs automatically after the applet is initialized. • Starting can also occur if the applet is already in “stopped” (idle) state. For example, we may leave the web page containing the applet temporarily to another page and return back to the page. This again starts the applet running. Unlike init() method, the start() method may be called more than once. We may override the start() method to create a thread to control the applet. public void start() { Action } Mr. Vishal Rajput

  10. Idle or Stopped state • An applet becomes idle when it is stopped from running stopping occurs automatically when we leave the page containing the currently running applet. We can also do so by calling the stop() method explicitly. If we use a thread to run the applet, then we must use stop() method to terminate the thread. We can achieve by overriding the stop() method. public void stop() { Action } When the browser moves to another page. You can use this method to stop additional execution threads Mr. Vishal Rajput

  11. Dead state(destroy) • An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy() method when we quit the browser. Like initialization, destroying stage occurs only once in the applet’s life cycle. If the applet has created any resources, like threads, we may override the destroy() method to clean up these resources. public void destroy() { Action } Mr. Vishal Rajput

  12. Display state • Applet moves to the display state whenever it has to perform some output operations on the screen. This happens immediately after the applet enters into the running state. The paint() method is called to accomplish this task. Almost every applet will have a paint() method. public void paint( Graphics g) { Display statement; } • It is to be noted that the display state is not considered as a part of the applet’s life cycle. In fact, the paint() method is defined in the Applet class. It is inherited form the component class, a super class of Applet. Mr. Vishal Rajput

  13. Graphics Class • A Graphics object encapsulates a set of methods that can perform graphics output. • Specifically, it allows you to draw lines, ovals, rectangles, strings, images, characters, and arcs. Mr. Vishal Rajput

  14. //Demo program of Graphics class import java.applet.*; import java.awt.*; /*<applet code="b.class" height="250" width="400"></applet>*/ public class b extends Applet { public void paint(Graphics g) { g.setColor(Color.red); g.drawLine(5,30,350,30); g.setColor(Color.blue); g.drawRect(5,40,90,55); g.fillRect(100,40,90,55); g.setColor(Color.cyan); g.fillRoundRect(195,40,90,55,50,50); g.drawRoundRect(290,40,90,55,20,20); g.setColor(Color.yellow); g.draw3DRect(5,100,90,55,true); g.fill3DRect(100,100,90,55,false); g.setColor(Color.magenta); g.drawOval(195,100,90,55); g.fillOval(290,100,90,55); } } Mr. Vishal Rajput

  15. AWT v/s Swing Component Mr. Vishal Rajput

  16. Event Handling • Delegation Event Model • The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. • The delegation event model provides a standard mechanism for a source to generate an event and send it to a set of listeners. Mr. Vishal Rajput

  17. Event • An event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. • Some of the activities that causes events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list and clicking the mouse. • Events may also occur that are not directly interact with a user interface. For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed. We are free to define events that are appropriate for our application. Mr. Vishal Rajput

  18. Event Sources • A source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. • A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method. Mr. Vishal Rajput

  19. Event Listner • A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. • The method that receive and process events are defined in a set of interfaces found in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. Any object may receive and process one or both of these events if it provides an implementation of this interface. Mr. Vishal Rajput

  20. Event Object • At the root of the Java event class hierarchy is EventObject, which is in java.util. it is the superclass for all events. Its one constructor is shown here: • EventObject(Object src) • here, src is the object that generates this event. • EventObject contains two methods: • getSource() • toString() • The getSource() method returns the source of the event. Its general form is shown here: • Object.getSource() • toString() returns the string equivalent of the event. Mr. Vishal Rajput

  21. Mr. Vishal Rajput

  22. Mr. Vishal Rajput

  23. ActionListener • This interface defines the actionPerformed( ) method that is invoked when an action event occurs. Its general form is shown here: • void actionPerformed(ActionEventae) Mr. Vishal Rajput

  24. import java.awt.event.*; import java.awt.*; import java.applet.Applet; /* <applet code=appl4.class height=200 width=300> </applet> */ public class appl4 extends Applet implements ActionListener { Label l1,l2; Button b1; TextField t1,t2,r; Panel p1,p2; public void init() { l1=new Label("Enter the Number"); l2=new Label("Result"); t1=new TextField(5); t2=new TextField(5); r=new TextField(5); b1=new Button("Submit"); p1=new Panel(); p2=new Panel(); b1.addActionListener(this); p1.setBackground(Color.pink); p2.setBackground(Color.green); add(p1); add(p2); p1.add(l1); p1.add(t1); p1.add(t2); p2.add(l2); p2.add(r); p2.add(b1); } public void actionPerformed(ActionEventae) { int n1,n2; n1=Integer.parseInt(t1.getText()); n2=Integer.parseInt(t2.getText()); r.setText(""+(n1+n2)); } } Mr. Vishal Rajput

  25. Mr. Vishal Rajput

  26. The KeyListener Interface • This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked when a key is pressed and released, respectively. The keyTyped( ) method is invoked when a character has been entered. • For example, if a user presses and releases the A key, three events are generated in sequence: key pressed, typed, and released. If a user presses and releases the HOME key, two key events are generated in sequence: key pressed and released. Mr. Vishal Rajput

  27. MouseListener Interface • This interface defines five methods. If the mouse is pressed and released at the same point, mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method is called. When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is pressed and released, respectively. • The general forms of these methods are shown here: • void mouseClicked(MouseEventme) • void mouseEntered(MouseEventme) • void mouseExited(MouseEventme) • void mousePressed(MouseEventme) • void mouseReleased(MouseEventme) Mr. Vishal Rajput

  28. MouseMotionListener Interface • This interface defines two methods. The mouseDragged( ) method is called multiple times as the mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved. Their general forms are shown here: • void mouseDragged(MouseEventme) • void mouseMoved(MouseEventme) Mr. Vishal Rajput

  29. ItemListener Interface • This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes. Its general form is shown here: • void itemStateChanged(ItemEventie) • Eg: CheckBox Mr. Vishal Rajput

  30. WindowListener Interface • This interface defines seven methods. The windowActivated( ) and windowDeactivated( ) methods are invoked when a window is activated or deactivated, respectively. If a window is iconified, the windowIconified( ) method is called. When a window is deiconified, the windowDeiconified( ) method is called. When a window is opened or closed, the windowOpened( ) or windowClosed( ) methods are called, respectively. The windowClosing( ) method is called when a window is being closed. • The general forms of these methods are • voidwindowActivated(WindowEvent e)Invoked when the Window is set to be the active Window. • voidwindowClosed(WindowEvent e)Invoked when a window has been closed as the result of calling dispose on the window. • voidwindowClosing(WindowEvent e)Invoked when the user attempts to close the window from the window's system menu. • voidwindowDeactivated(WindowEvent e)Invoked when a Window is no longer the active Window. • voidwindowDeiconified(WindowEvent e)Invoked when a window is changed from a minimized to a normal state. • voidwindowIconified(WindowEvent e)Invoked when a window is changed from a normal to a minimized state. • voidwindowOpened(WindowEvent e)Invoked the first time a window is made visible. Mr. Vishal Rajput

  31. Focus Listeners • Focus listeners listen for a component gaining or losing keyboard focus. Usually there are visual clues as to which component has the focus, such as an active cursor in a text field. The FocusListener interface has two methods, whose signatures are: • public void focusGained(FocusEvent e) • public void focusLost(FocusEvent e) Mr. Vishal Rajput

  32. Adapter Class • If you implement Listener interface then obviously you must have to override all the methods declare in an interface. • Suppose in special case you want to just need one or two method among given set of methods then what? If you are implementing listener interface then you can not omit any method. • Adapter class implements listener interface and contains empty implementation of each method declared in the listener interface, when you extends these Adapter class you need to implement only those methods that you want. • When we are dealing with Listener interface we are implementing listeners while we working with adapter class we have to extends adapter class and override methods which we need. Mr. Vishal Rajput

  33. List of Adapter class and its Listener Interface:ComponentAdapter - ComponentAdapterContainerAdapter - ContainerListenerFocusAdapter - FocusListenerKeyAdapter - KeyListenerMouseAdapter - MouseListenerMouseMotionAdapter - MouseMotionListenerWindowAdapter - WindowListener Mr. Vishal Rajput

  34. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="AdapterDemo" width=300 height=100> </applet> */ public class AdapterDemo extends Applet { public void init() { addMouseListener(new MyMouseAdapter(this)); addMouseMotionListener(new MyMouseMotionAdapter(this)); } } class MyMouseAdapter extends MouseAdapter //extends the MouseAdapter class instead of Interface { AdapterDemoadapterDemo;//Create object of main class to recive the value. public MyMouseAdapter(AdapterDemoadapterDemo) { this.adapterDemo = adapterDemo;// constructor Initialize the value to the main class obj } // Handle mouse clicked. public void mouseClicked(MouseEvent me) { adapterDemo.showStatus("Mouse clicked"); } } class MyMouseMotionAdapter extends MouseMotionAdapter { AdapterDemoadapterDemo; public MyMouseMotionAdapter(AdapterDemoadapterDemo) { this.adapterDemo = adapterDemo; } // Handle mouse dragged. public void mouseDragged(MouseEvent me) { adapterDemo.showStatus("Mouse dragged"); } } Mr. Vishal Rajput

  35. Introduction to layouts • components are placed on a form is controlled by a "layout manager" that decides how the components lie based on the order that you add( ) them. • The size, shape, and placement of components will be remarkably different from one layout manager to another. In addition, the layout managers adapt to the dimensions of your applet or application window, so if that window dimension is changed (for example, in the HTML page’s applet specification) the size, shape, and placement of the components could change. • This section gives you an overview of some layout managers that the Java platform provides, gives you some general rules for using layout managers. Mr. Vishal Rajput

  36. Some layouts provided by JAVA • Flow Layout (Default Layout) • Border Layout • Grid Layout • Card Layout Mr. Vishal Rajput

  37. Using Flow Layout • Default layout scheme: the FlowLayout. This simply "flows" the components onto the form, from left to right until the top space is full, then moves down a row and continues flowing the components. Mr. Vishal Rajput

  38. import java.awt.*; import java.awt.event.*; import java.applet.*; public class flowlayout extends Applet implements ItemListener { String msg=" "; Checkbox Win98,winNT,solaris,mac; public void init() { setLayout(new FlowLayout(FlowLayout.LEFT)); Win98=new Checkbox("Windows 98",null,true); winNT=new Checkbox("Windows NT"); solaris=new Checkbox("MacOS"); add(Win98); add(winNT); add(solaris); add(mac); Win98.addItemListener(this); winNT.addItemListener(this); solaris.addItemListener(this); mac.addItemListener(this); } public void itemStateChanged(ItemEvent id) {repaint();} public void paint(Graphics g) { msg="Current state : "; g.drawString(msg,6,80); msg="Windows 98 : " + Win98.getState(); g.drawString(msg,6,100); msg="Windows NT : " + winNT.getState(); g.drawString(msg,6,120); msg="Solaris : " + solaris.getState(); g.drawString(msg,6,140); msg="Mac : " + mac.getState(); g.drawString(msg,6,160); } } Mr. Vishal Rajput

  39. Using Border Layout • This layout manager has the concept of four border regions and a center area. When you add something to a panel that’s using a BorderLayout you must use an add( ) method that takes a String object as its first argument, and that string must specify (with proper capitalization) "North" (top), "South" (bottom), "East" (right), "West" (left), or "Center." If you misspell or miss-capitalize, you won’t get a compile-time error, but the applet simply won’t do what you expect. Mr. Vishal Rajput

  40. import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class border extends Applet { Scrollbar hscr1,hscr2,vscr1,vscr2; TextFieldtxtbox; public void init() { setLayout(new BorderLayout()); hscr1 = new Scrollbar(Scrollbar.HORIZONTAL,1,10,1,200); hscr2 = new Scrollbar(Scrollbar.HORIZONTAL,1,10,1,200); vscr1 = new Scrollbar(Scrollbar.VERTICAL,1,10,1,200); vscr2 = new Scrollbar(Scrollbar.VERTICAL,1,10,1,200); txtbox = new TextField("Welcome to Border Layout"); add("North",hscr1); add("West",vscr1); add("South",hscr2); add("East",vscr2); add("Center",txtbox); } } Mr. Vishal Rajput

  41. GridLayout • A GridLayout allows you to build a table of components, and as you add them they are placed left-to-right and top-to-bottom in the grid. In the constructor you specify the number of rows and columns that you need and these are laid out in equal size. Mr. Vishal Rajput

  42. import java.awt.*; import java.applet.*; public class gridlayout extends Applet { static final int n=4; public void init() { setLayout(new GridLayout(n,n)); setFont(new Font("SansSerif",Font.BOLD,24)); for(inti=0;i<n;i++) { for(int j=0;j<n;j++) { int k=i*n+j; if(k>0) add(new Button(" " +k)); } } } } Mr. Vishal Rajput

  43. Using Card Layout • The CardLayout allows you to create the rough equivalent of a "tabbed dialog," which in more sophisticated environments has actual file-folder tabs running across one edge, and all you have to do is press a tab to bring forward a different dialog. Not so in the AWT: The CardLayout is simply a blank space and you’re responsible for bringing forward new cards Mr. Vishal Rajput

  44. import java.awt.*; import java.awt.event.*; import java.applet.*; public class cardlayout extends Applet implements ActionListener, MouseListener { Checkbox Win98,winNT,solaris,mac; Panel oscards; CardLayoutcardlo; Button win,other; public void init() { win=new Button("Windows"); other=new Button("Other"); add(win); add(other); cardlo=new CardLayout(); oscards=new Panel(); oscards.setLayout(cardlo); Win98=new Checkbox("Windows 98",null,true); winNT=new Checkbox("Windows NT"); solaris=new Checkbox("Solaris"); mac=new Checkbox("MacOS"); Panel winpan=new Panel(); winpan.add(Win98); winpan.add(winNT); Panel otherpan=new Panel(); otherpan.add(solaris); otherpan.add(mac); oscards.add(winpan,"Windows"); oscards.add(otherpan,"Other"); add(oscards); win.addActionListener(this); other.addActionListener(this); addMouseListener(this); } public void mousePressed(MouseEvent me) { cardlo.next(oscards); } public void mouseClicked(MouseEvent me) { } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mouseReleased(MouseEvent me) { } public void actionPerformed(ActionEventae) { if(ae.getSource() == win) { cardlo.show(oscards,"Windows"); } else { cardlo.show(oscards,"Other"); } } } Mr. Vishal Rajput

  45. PARAM Teg • The PARAM tag allows you to specify applet-specific arguments in an HTML page. Applets access their attributes with the getParameter( ) method. • It returns the value of the specified parameter in the form of a String object. Thus, for numeric and boolean values, you will need to convert their string representations into their internal formats. Mr. Vishal Rajput

  46. /* <applet code="MyApplet2.class" width = 600 height= 450> <param name = "t1" value="Shree Ganesh"> <param name = "t2" value ="1985"> </applet> */ import java.applet.*; import java.awt.*; public class MyApplet2 extends Applet { String n; String id; public void init() { n = getParameter("t1"); id = getParameter("t2"); } public void paint(Graphics g) { g.drawString("Name is : " + n, 100,100); g.drawString("Id is : "+ id, 100,150); } } Mr. Vishal Rajput

  47. AWT Component Properties Mr. Vishal Rajput

  48. Buttons • Properties of Button • To create push button: Button b1 =new Button("label"); • To get the label of the button: String l = b1.getLabel(); • To set the label of the button: b1.setLabel("label"); • To get the label of the button clicked: String str = ae.getActionCommand(); Mr. Vishal Rajput

  49. CheckBox • A Checkbox is a square shaped box which provides a set of options to the user. • To create a Checkbox: Checkbox cb = new Checkbox ("label"); • To create a checked Checkbox: Checkbox cb = new Checkbox ("label", true); • To get the state of a Checkbox: boolean b = cb.getState (); • To set the state of a Checkbox: cb.setState (true); • To get the label of a Checkbox: String s = cb.getLabel (); Mr. Vishal Rajput

  50. Radio button • A Radio button represents a round shaped button such that only one can be selected from a panel. Radio button can be created using CheckboxGroup class and Checkbox classes. • To create a radio button: CheckboxGroupcbg = new CheckboxGroup (); • Checkbox cb = new Checkbox ("label", cbg, true); • To know the selected checkbox: Checkbox cb = cbg.getSelectedCheckbox (); • To know the selected checkbox label: String label = cbg.getSelectedCheckbox ().getLabel (); Mr. Vishal Rajput

More Related