Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Abstract Windowing Toolkit (AWT) & Swings

Similar presentations


Presentation on theme: "Introduction to Abstract Windowing Toolkit (AWT) & Swings"— Presentation transcript:

1 Introduction to Abstract Windowing Toolkit (AWT) & Swings
CHAPTER 1 Introduction to Abstract Windowing Toolkit (AWT) & Swings Objectives -> To design and develop GUI programs using AWT and swing component -> To arrange the GUI components using different layout managers

2 Abstract Window Toolkit
Java’s Abstract Window Toolkit provides classes and other tools for building programs that have a graphical user interface. The term “Abstract” refers to the AWT’s ability to run on multiple platforms. AWT components are platform dependent. Building a GUI involves creating “abstract” components such as buttons and windows, which are then mapped to “concrete” components for a specific platform.

3 AWT (Abstract Windowing Toolkit)
The AWT is roughly broken into three categories Components Layout Managers Graphics Many AWT components have been replaced by Swing components Package required to import is java.awt It is generally not considered a good idea to mix Swing components and AWT components. Choose to use one or the other.

4 Swing Java has a newer library for building graphical user interfaces, known as “Swing.” Swing is more powerful and sophisticated than the AWT. Swing is built around the existing AWT, so it helps to understand the AWT first. Swing is similar enough to the AWT that it’s relatively easy to switch if the need arises. Many Swing classes correspond to AWT classes. For example, Swing’s JButton class corresponds to the AWT’s Button class.

5 AWT Class Hierarchy This slide shows the hierarchy of classes which will be covered in this chapter. If you check the Java API documentation, you will note that there are many more classes in the java.awt package.

6 Component Components are generally the things that the user interacts with. List of common Components List Scrollbar TextArea TextField Choice Button Label ... All containers The Component class contains the common features to all items which can be displayed in a GUI. Often, these items are called “widgets”. In the AWT, all widgets are components and, as such, inherit all the data and methods of the Component class.

7 Useful Methods of Component class
Description public void add(Component c) inserts a component on this component. public void setSize(int width,int height) sets the size (width and height) of the component. public void setLayout(LayoutManager m) defines the layout manager for the component. public void setVisible(boolean status) changes the visibility of the component, by default false.

8 Container Container is a subclass of Component. (ie. All containers are themselves, Components) Containers contain components such as buttons, textfields, labels etc For a component to be placed on the screen, it must be placed within a Container The classes that extends Container class are known as container such as Frame, Dialog and Panel. The Container class defined all the data and methods necessary for managing groups of Components add getComponent getMaximumSize getMinimumSize getPreferredSize remove removeAll The Container class is an abstract class which encapsulates the logic for managing Components. Note that Containers are, themselves, Components which means that Containers can be placed within other Containers

9 Windows and Frames The Window class defines a top-level Window with no Borders or Menu bar. You must use frame, dialog or another window for creating a window. Frame defines a top-level Window with Borders, Title and Menu Bar Frames are more commonly used than Windows Once defined, a Frame is a Container which can contain Components Frame aFrame = new Frame(“Hello World”); aFrame.setSize(100,100); aFrame.setLocation(10,10); aFrame.setVisible(true); Generally speaking, the Window class is not used very often. The Frame class, on the other hand, is used quite extensively for GUI based applications. Another subclass of Window, which is not described here, I the Dialog class. It is used to display Dialog Boxes. Dialog Boxes are generally used to convey important information to the user, and must be dismissed by the user before the application can continue. It should be noted that dialog boxes disrupt the flow of an application and can cause great user frustration if not used appropriately.

10 Creating a Graphical User Interface
GUI programming in Java is based on three concepts: Components. A component is an object that the user can see on the screen and—in most cases—interact with. Containers. A container is a component that can hold other components. Events. An event is an action triggered by the user, such as a key press or mouse click. Designing a graphical user interface involves creating components, putting them into containers, and arranging for the program to respond to events.

11 Creating a Graphical User Interface
Components are objects, so they’re created by invoking a constructor. A button would be created by using a constructor belonging to the Button class. The most commonly used constructor has one argument (the button’s label): Button b = new Button("Testing"); For a component to be visible, it must be added to a container (typically a frame) by the add method.

12 Creating a Graphical User Interface
To detect when an event occurs, a special “listener” object can be attached to a component. When the user performs an action that involves the component, a method belonging to the listener object will be called automatically.

13 12.2 Frames In Java terminology, a frame is a window with a title and a border. A frame may also have a menu bar. Frames play an important role in the AWT because a GUI program normally displays a frame when it’s executed.

14 The Frame Class Frames are created using one of the constructors in the Frame class. One constructor takes a single argument (the title to be displayed at the top of the frame): Frame f = new Frame("Title goes here"); Although the Frame object now exists, it’s not visible on the screen. Before making the frame visible, a method should be called to set the size of the frame. If desired, the frame’s location can also be specified.

15 Frame Methods Many methods used with Frame objects are inherited from Window (Frame’s superclass) or from Component (Window’s superclass). The setSize method sets the width and height of a frame: f.setSize(width, height); If a program fails to call setSize or pack before displaying a frame, it will assume a default size.

16 Frame Methods The size of a frame can change during the execution of a program. The getSize method returns a frame’s current width and height: Dimension frameSize = f.getSize(); frameSize.width will contain f’s width. frameSize.height will contain f’s height.

17 Frame Methods The setVisible method controls whether or not a frame is currently visible on the screen. Calling setVisible with true as the argument makes a frame visible: f.setVisible(true); Calling it with false as the argument makes the frame disappear from the screen: f.setVisible(false); The Frame object still exists; it can be made to reappear later by calling setVisible again.

18 Creating a Frame The FrameTest program creates a Frame object and displays it on the screen. This program illustrates three key steps: 1. Using the Frame constructor to create a frame. 2. Setting the size of the frame. 3. Displaying the frame on the screen.

19 FrameTest.java import java.awt.*; public class FrameTest {
// Displays a frame on the screen. import java.awt.*; public class FrameTest { public static void main(String[] args) { Frame f = new Frame("Frame Test"); f.setSize(150, 100); f.setVisible(true); }

20 Creating a Frame Frame created by the FrameTest program:
As with the other AWT components, the appearance of a frame depends on the platform.

21 Creating a Frame Clicking on the Close button has no effect, because there’s no action associated with that button. The frame will have be closed the hard way, by killing the program. In Windows, click on the DOS window from which the program was launched, hold down the Ctrl key, and press the letter C.

22 Setting the Location of a Frame
By default, all windows (including frames) are displayed in the upper-left corner of the screen, which has coordinates (0, 0). The setLocation method can be used to specify a different location: f.setLocation(50, 75); To find the current location of a frame, call getLocation: Point frameLocation = f.getLocation(); The coordinates of f’s upper-left corner will be stored in frameLocation.x and frameLocation.y.

23 Adding Components to a Frame
To add a component to a frame (or any kind of container), the add method is used. add belongs to the Container class, so it’s inherited by Frame and the other container classes. An example of adding a button to a frame: Button b = new Button("Testing"); add(b);

24 Creating Frame by Extending Frame class
import java.awt.*;   class First extends Frame {   First() {  Button b=new Button("click me");   b.setBounds(30,100,80,30);// setting button position   add(b);//adding button into frame   setSize(300,300);//frame size 300 width and 300 height   setLayout(null);//no layout manager   setVisible(true);//now frame will be visible, by default not visible   }   public static void main(String args[]) First f=new First();   }

25

26 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.setSize(300, 300); //setting frame size. fm.setVisible(true); //set frame visibilty true. } public static void main(String args[]) Testawt ta = new Testawt();

27

28 Panels Panel aPanel = new Panel(); aPanel.add(new Button("Ok")); aPanel.add(new Button("Cancel")); Frame aFrame = new Frame("Button Test"); aFrame.setSize(100,100); aFrame.setLocation(10,10); aFrame.add(aPanel); The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc. The Panel class is probably the most important class within the AWT. Panels can contain Components (which includes other Panels). It allows the GUI screen to be partitioned into manageable pieces. Panels should contain Components which are functionally related. For example, if an application wished to allow the user to input their name, address, phone number and other relevant contact information, it would be good design to place all of the necessary GUI Components on a Panel. That panel can be then added to and removed from other Containers within the application.

29 Buttons This class represents a push-button which displays some specified text. Constructors 1) Button() Constructs a button with an empty string for its label. 2) Button(String text) Constructs a new button with specified label. Panel aPanel = new Panel(); Button okButton = new Button("Ok"); Button cancelButton = new Button("Cancel"); aPanel.add(okButton)); aPanel.add(cancelButton)); All GUI systems offer some form of push button. The Button class in Java represents that functionality. Buttons are typically single purpose (ie. Their function does not change).

30 Labels This class is a Component which displays a single line of text.
Labels are read-only. That is, the user cannot click on a label to edit the text it displays. Text can be aligned within the label Constructors 1) Label() Constructs an empty label. 2)Label(String text) Constructs a new label with the specified string of text, left justified. 3)Label(String text, int alignment) Constructs a new label that presents the specified string of text with the specified alignment. Many GUI applications require users to input data within TextFields, TextAreas, dropdown boxes, etc. However, presenting the user with an series of TextFields without any description would provide a great deal of confusion to the user. All GUI systems allow for the addition of Labels to the interface which provide textual information which aids in the description of the interface itself.

31 Ll.setAlignment(Label.RIGHT); Ll.add(aLabel);
Label Ll = new Label("Enter password:"); Ll.setAlignment(Label.RIGHT); Ll.add(aLabel);

32 List This class is a Component which displays a list of Strings.
The list is scrollable, if necessary. Sometimes called Listbox in other languages. Lists can be set up to allow single or multiple selections. The list will return an array indicating which Strings are selected Constructors 1) List() Creates a new scrolling list. 2) List(int rows) Creates a new scrolling list initialized with the specified number of visible lines. 3List(int rows, boolean multipleMode) Creates a new scrolling list initialized to display the specified number of rows. The List class comes under many names in different GUI systems. Lists provide a list of strings (which is scrollable space the strings take up exceeds the allotted screen real estate) which can be selected by the user. The programmer may allow the user to select multiple strings within the list.

33 List L1 = new List(); L1.add(“India"); L1.add(“UK"); L1t.add(“USA");

34 Checkbox This class represents a GUI checkbox with a textual label.
The Checkbox maintains a boolean state indicating whether it is checked or not. If a Checkbox is added to a CheckBoxGroup, it will behave like a radio button. Constructors 1) Checkbox() Creates a check box with an empty string for its label. 2) Checkbox(String label) Creates a check box with the specified label. 3)Checkbox(String label, boolean state) Creates a check box with the specified label and sets the specified state. Checkboxes allow for yes/no selections by the user. Each checkbox maintains an internal state indicating whether it is selected or not. If it is selected, it will display itself in such a manner as to indicate it is selected. The state of a checkbox can be queried through the getState method. Multiple checkboxes will all behave independently of one another meaning each one can be individually checked or unchecked. However, if a group of checkboxes are associated with a CheckBoxGroup object, then only one of the checkboxes can be selected at any one time. It is through the use of CheckBoxGroup that the AWT provides “RadioButton” functionality.

35 4) Checkbox(String label, boolean state, CheckboxGroup group)
Constructs a Checkbox with the specified label, set to the specified state, and in the specified check box group. 5)Checkbox(String label, CheckboxGroup group, boolean state) Creates a check box with the specified label, in the specified check box group, and set to the specified state. Checkbox creamCheckbox = new CheckBox("Cream"); Checkbox sugarCheckbox = new CheckBox("Sugar"); if (creamCheckbox.getState()) { coffee.addCream(); }

36 Choice This class represents a dropdown list of Strings.
Similar to a list in terms of functionality, but displayed differently. Only one item from the list can be selected at one time and the currently selected element is displayed. Choice C1 = new Choice(); C1.add(“India"); C1.add(“UK"); C1.add(“USA"); This class provides a list of strings to choose from (just like a list does) but the list is not displayed to the user at all times. Instead, the user must click the Choice to reveal the list. Once revealed, the user may select one of the items within the list. The currently selected item is displayed.

37 TextField This class displays a single line of optionally editable text. This class inherits several methods from TextComponent. This is one of the most commonly used Components in the AWT TextField TextField = new TextField(); TextField passwordTextField = new TextField(); passwordTextField.setEchoChar("*"); String user = TextField.getText(); String userpassword = passwordTextField.getText(); A TextField provides the user with a location that he/she may input a single line of text. Most TextFields are used in conjunction with a Label. The text provided by the label should describe the purpose (and thus, the expected input for) the TextField.

38 TextArea This class displays multiple lines of optionally editable text. This class inherits several methods from TextComponent. TextArea also provides the methods: appendText(), insertText() and replaceText() // 5 rows, 80 columns TextArea fullAddressTextArea = new TextArea(5, 80); String userFullAddress= fullAddressTextArea.getText(); If the user is to input multiple lines of text, a TextArea is used instead of a TextField.

39 Layout Managers Since the Component class defines the setSize() and setLocation() methods, all Components can be sized and positioned with those methods. Problem: the parameters provided to those methods are defined in terms of pixels. Pixel sizes may be different (depending on the platform) so the use of those methods tends to produce GUIs which will not display properly on all platforms. Solution: Layout Managers. Layout managers are assigned to Containers. When a Component is added to a Container, its Layout Manager is consulted in order to determine the size and placement of the Component.

40 Layout Managers (cont)
Every container has a default layout manager, but we can explicitly set the layout manager as well Each layout manager has its own particular rules governing how the components will be arranged Some layout managers pay attention to a component's preferred size or alignment, while others do not A layout manager attempts to adjust the layout as components are added and as containers are resized

41 Layout Managers (cont)
There are several different LayoutManagers, each of which sizes and positions its Components based on an algorithm: FlowLayout BorderLayout GridLayout CardLayout GridBagLayout For Windows and Frames, the default LayoutManager is BorderLayout. For Panels, the default LayoutManager is FlowLayout.

42 Flow Layout The algorithm used by the FlowLayout is to lay out Components like words on a page: Left to right, top to bottom. It fits as many Components into a given row before moving to the next row. Rows are created as needed to accommodate all of the components Components are displayed in the order they are added to the container Each row of components is centered horizontally in the window by default, but could also be aligned left or right Also, the horizontal and vertical gaps between the components can be explicitly set Flow layout is the default layout manager for Panels

43 FlowLayout class contains three constants you can use to align Components
FlowLayout.LEFT FlowLayout.CENTER FlowLayout.RIGHT If you do not specify alignment, Components are center-aligned in a FlowLayout Container by default

44 Flow Layout Constructors
1)FlowLayout(align, hgap, vgap) align – alignment used by the manager hgap – horizontal gaps between components vgap – vertical gaps between components 2)FlowLayout(align) A default 5-unit horizontal and vertical gap. 3)FlowLayout() A centered alignment and a default 5-unit horizontal and vertical gap.

45 import java.awt.*; import java.applet.*; public class Flowdemo extends Applet { public void init() // Default for Applet is FlowLayout Button b1=new Button("One"); Button b2= new Button("Two"); Button b3=new Button("Three"); Button b4= new Button("Four"); Button b5=new Button("Five"); add(b1); add(b2); add(b3); add(b4); add(b5); } /* <applet code="Flowdemo.class" width=500 height=600></applet>*/

46

47 Border Layout The BorderLayout Manager breaks the Container into 5 regions (North, South, East, West, and Center). When you add a component to a container that uses BorderLayout, the add() method uses two arguments the component and the region to which the component is added Frame aFrame = new Frame(); aFrame.add("North", new Button("Ok")); aFrame.add("South", new Button("Add")); aFrame.add("East", new Button("Delete")); aFrame.add("West", new Button("Cancel")); Border Layout is the default layout for Frames and Windows

48 Border Layout (cont) The regions of the BorderLayout are defined as follows: North Center West East South

49 Border Layout Constructors
1)BorderLayout(hgap, vgap) hgap – horizontal gaps between components vgap – vertical gaps between components 2)BorderLayout() No vertical or horizontal gaps.

50 import java.awt.*; import java.applet.*; public class Borderdemo extends Applet { public void init() setLayout( new BorderLayout()); add( new Button("ONE"), "North" ); add( new Button("TWO"), "East" ); add( new Button("THREE"), "South" ); add( new Button("FOUR"), "West" ); add( new Button("Five"), "Center" ); } /*<applet code="Borderdemo.class" width=600 height=500></applet>*/

51

52 Grid Layout The GridLayout class divides the region into a grid of equally sized rows and columns. Components are added left-to-right, top-to-bottom. The number of rows and columns is specified in the constructor for the LayoutManager. You cannot skip a position or specify an exact position for a component You can add a blank label to a grid position and give the illusion of skipping a position

53 Grid Layout Constructors
1)GridLayout(r, c, hgap, vgap) r – number of rows in the layout c – number of columns in the layout hgap – horizontal gaps between components vgap – vertical gaps between components 2)GridLayout(r, c) No vertical or horizontal gaps. 3)GridLayout() A single row and no vertical or horizontal gaps.

54 import java.awt.*; import java.applet.*; public class Griddemo extends Applet { public void init() setLayout( new GridLayout( 3, 2 )); add( new Button("One") ); add( new Button("Two") ); add( new Button("Three") ); add( new Button("Four") ); add( new Button("Five") ); } /*<applet code="Griddemo.class" width=500 height=600></applet>*/

55

56 Card Layout You use CardLayout when you want multiple compnoents to share the same display space If multiple containers exist in the application but only one is to be displayed at a time, you could use CardLayout The CardLayout manager generates a stack of containers or components, one on top of another Each component is a ‘card’ and each ‘card’ can be any component type ex., JButton, JLabel, or JPanel

57 Card Layout Constructors
CardLayout(): creates a card layout with zero horizontal and vertical gap. 2.CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap. -> The CardLayout class manages two or more components (usually JPanel instances) that share the same display space. -> When using the CardLayout class, the user choose between the components by using a combo box. Another way to accomplish the same task is to use a tabbed pane.

58 import java.awt.*; import java.applet.*; public class carddemo extends Applet { CardLayout cards = new CardLayout(); public void init() { setLayout( cards ); add( new Button("one"), "one" ); add( new Button("two"), "two" ); add( new Button("three"), "three" ); } public boolean action( Event e, Object arg) cards.next( this ); return true; /* <applet code= "carddemo.class" width= 400 height=600></applet>*/

59

60 GridBag Layout The GridBagLayout is one of the most complex and flexible layout managers There is a grid of rows and columns, but the heights and widths do not have to be the same. Components can take up multiple cells as well GridBagLayout tries to acknowledge the preferred height and width of the components Each component gets added to the grid with a GridBagConstraints object to set the parameters for the component

61 GridBagContraints Object
▪ Constructor of GridbagLayout GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); GridBagConstraints object has the following properties 1) gridx, gridy Specify the row and column at the upper left corner of the component.The leftmost column has address gridx=0 and the top row has address gridy=0.  2) gridwidth, gridheight Specify the number of rows or columns in the component’s display area. These constraints specify the number of cells the component uses, not the number of pixels it uses. The default value is 1.

62 GridBagContraints Object
3) Fill Used when the component’s display area is larger than the component’s preferred size to determine whether and how to resize the component. Valid values (defined as GridBagConstraints constants) include NONE (the default),HORIZONTAL (make the component wide enough to fill its display area horizontally, but do not change its height),VERTICAL (make the component tall enough to fill its display area vertically, but do not change its width), and BOTH (make the component fill its display area entirely). 4)ipadx, ipady Specifies the internal padding of the component. The width of the component will be at least its minimum width plus ipadx pixels. Similarly, the height of the component will be at least the minimum height plus ipady pixels.

63 GridBagContraints Object
5) insets Specifies the external padding of the component. The minimum amount of space between the component and the edges of its display area. The value is specified as an Insets object. By default, each component has no external padding. 6)weightx, weighty Weights are used to determine how to distribute space among columns and rows, specified between 0.0 and 1.0

64 GridBagContraints Object
7)Anchor Used when the component is smaller than its display area to determine where to place the component. Valid values (defined as GridBagConstraints constants) are CENTER (the default) , PAGE_START, PAGE_END,LINE_START, LINE_END, FIRST_LINE_START, FIRST_LINE_END, LAST_LINE_END, and LAST_LINE_START.Here is a picture of how these values are interpreted in a container that has the default, left-to-right component orientation. FIRST_LINE_START PAGE_START FIRST_LINE_END LINE_START CENTER LINE_END LAST_LINE_START PAGE_END LAST_LINE_END

65 import java.awt.*; import java.applet.*; public class GridBagEx1 extends Applet { protected void makebutton(String name,GridBagLayout gridbag,GridBagConstraints c) Button button = new Button(name); gridbag.setConstraints(button, c); add(button); } public void init() { GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setFont(new Font("Arial", Font.BOLD, 14)); setLayout(gridbag); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; makebutton("Button1", gridbag, c); makebutton("Button2", gridbag, c); makebutton("Button3", gridbag, c); c.gridwidth = GridBagConstraints.REMAINDER; //end row makebutton("Button4", gridbag, c);

66 makebutton("Button5", gridbag, c); //another row
c.weightx = 0.0; //reset to the default makebutton("Button5", gridbag, c); //another row c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last in row makebutton("Button6", gridbag, c); c.gridwidth = GridBagConstraints.REMAINDER; //end row makebutton("Button7", gridbag, c); c.gridwidth = 1; //reset to the default c.gridheight = 2; c.weighty = 1.0; makebutton("Button8", gridbag, c); c.weighty = 0.0; //reset to the default c.gridheight = 1; //reset to the default makebutton("Button9", gridbag, c); makebutton("Button10", gridbag, c); setSize(600, 600); } public static void main(String args[]) { Frame f = new Frame("GridBag Layout Example"); GridBagEx1 ex1 = new GridBagEx1(); /* <applet code="GridBagEx1.class" width=700 height=800></applet>*/

67

68 What if I don’t want a LayoutManager?
LayoutManagers have proved to be difficult to deal with. The LayoutManager can be removed from a Container by invoking its setLayout method with a null parameter. Panel aPanel = new Panel(); aPanel.setLayout(null);

69 Menubars Menus are a number of pull-down combo boxes (In Java called as Choice) placed at single place for easy selection by the user. To create menus, the java.awt package comes with mainly four classes – MenuBar, Menu, MenuItem and CheckboxMenuItem. All these four classes are not AWT components as they are not subclasses of java.awt.Component class. They are subclasses of java.awt.MenuComponent. MenuBar: MenuBar holds the menus. MenuBar is added to frame with setMenuBar() method. Implicitly, the menu bar is added to the north (top) of the frame. MenuBar cannot be added to other sides like south and west etc. 2) Menu: Menu holds the menu items. Menu is added to frame with add() method. A sub-menu can be added to Menu.

70 Menubars 3) MenuItem: MenuItem displays the actual option user can select. Menu items are added to menu with method addMenuItem(). A dull-colored line can be added in between menu items with addSeparator() method. 4) CheckboxMenuItem: It differs from MenuItem in that it appears along with a checkbox. The selection can be done with checkbox selected.

71 import java.awt.event.*;
 public class SimpleMenuExample extends Frame {   Menu states, cities;   SimpleMenuExample()   {     MenuBar mb = new MenuBar();         // begin with creating menu bar     setMenuBar(mb); // add menu bar to frame     states = new Menu("Indian States"); // create menus       cities = new Menu("Indian Cities");      mb.add(states); // add menus to menu bar      mb.add(cities); states.add(new MenuItem("Himachal Pradesh"));     states.add(new MenuItem("Rajasthan"));     states.add(new MenuItem("West Bengal"));     states.addSeparator(); // separates from north Indian states from south Indian     states.add(new MenuItem("Andhra Pradesh"));     states.add(new MenuItem("Tamilnadu"));     states.add(new MenuItem("Karnataka"));      

72 cities.add(new MenuItem("Delhi"));
    cities.add(new MenuItem("Jaipur"));     cities.add(new MenuItem("Kolkata"));     cities.addSeparator(); // separates north Indian cities from south Indian     cities.add(new MenuItem("Hyderabad"));     cities.add(new MenuItem("Chennai"));     cities.add(new MenuItem("Bengaluru"));      setTitle("Simple Menu Program"); // frame creation methods     setSize(300, 300);     setVisible(true);   }     public static void main(String args[])  {     new SimpleMenuExample();   }}

73 Dialog boxes and File Dialog
Dialog boxes are pop-up windows on the screen that appear for a small time to take either input or display output while a main application is running. Dialog boxes are generally used to draw special attention of the user like displaying warnings.   Dialog box is a top-level window that comes with a border including a title bar. The dialog box can be made non-resizable and the default layout manager is BorderLayout.  A dialog box works within a main program. It cannot be created as a standalone application. It is a child window and must be connected to a main program or to a parent window. Frame is a parent window as it can work independently. For example, the Find and Replace Dialog box cannot be obtained without opening MS-Word document. Likewise, File Deletion Confirmation box cannot appear without deleting a file.

74 Types of Dialog boxes Two types of dialog boxes exist 1)Modal  2)Modeless. -> Modal dialog box does not allow the user to do any activity without dismissing (closing) it; example is File Deletion Confirmation  dialog box . -> Modeless dialog box permits the user to do any activity without closing it; example is Find and Replace dialog box of MS Word. Java supports both styles of dialog boxes. ->One more dialog box exists with AWT, known as File dialog which gets the platform dependent file searching dialog box.

75 Swings in Java Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java. Unlike AWT, Java Swing provides platform-independent and lightweight components. The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, Jmenu etc.

76 Swing Features 1. Light Weight - Swing component are independent of native Operating System's API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls. 2. Rich controls - Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, table controls etc. 3.Highly Customizable - Swing controls can be customized in very easy way as visual apperance is independent of internal representation. 4.Pluggable look-and-feel- SWING based GUI Application look and feel can be changed at run time based on available values.

77 MVC Architecture MVC stands for Model View and Controller. It is a design pattern that separates the business logic, presentation logic and data. Model represents the state of the application i.e. data. It can also have business logic. View represents the presentation i.e. UI(User Interface). Controller acts as an interface between View and Model. Controller intercepts all the incoming requests.

78 Swing Components 1) JButton
JButton class provides functionality of a button. JButton class has three constuctors. JButton(Icon ic) JButton(String str) JButton(String str, Icon ic) It allows a button to be created using icon, a string or both. JButton supports ActionEvent. When a button is pressed an ActionEvent is generated.

79 import javax.swing.*; import java.awt.event.*; import java.awt.*; public class testswing extends JFrame { testswing() JButton bt1 = new JButton("Yes"); //Creating a Yes Button. JButton bt2 = new JButton("No"); //Creating a No Button. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close operation. setLayout(new FlowLayout()); //setting layout using FlowLayout object setSize(400, 400); //setting size of Jframe add(bt1); //adding Yes button to frame. add(bt2); //adding No button to frame. setVisible(true); } public static void main(String[] args) new testswing();

80

81 Swing components 2) JTextField
It is used for taking input of single line of text. It is most widely used text component. It has three constructors, i)JTextField(int cols) ii)JTextField(String str, int cols) iii)JTextField(String str) cols represent the number of columns in text field. import javax.swing.*; import java.awt.event.*; import java.awt.*; public class MyTextField extends JFrame { MyTextField() JTextField jtf = new JTextField(20); //creating JTextField. add(jtf); //adding JTextField to frame. setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); setVisible(true); } public static void main(String[] args) { new MyTextField(); }

82

83 Swing components 3) JCheckBox
JCheckBox class is used to create checkboxes in frame. Following is constructor for JCheckBox, JCheckBox(String str);

84 import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Test extends JFrame { Test() JCheckBox jcb = new JCheckBox("yes"); //creating JCheckBox. add(jcb); //adding JCheckBox to frame. jcb = new JCheckBox("no"); //creating JCheckBox. jcb = new JCheckBox("maybe"); //creating JCheckBox. setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); setVisible(true); } public static void main(String[] args) new Test(); } }

85

86 Swing components 4) JRadioButton
Radio button is a group of related button in which only one can be selected. JRadioButton class is used to create a radio button in Frames. Following is the constructor for JRadioButton, JRadioButton(String str)

87 import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Test extends JFrame { Test() JRadioButton jcb = new JRadioButton("A"); //creating JRadioButton. add(jcb); //adding JRadioButton to frame. jcb = new JRadioButton("B"); //creating JRadioButton. jcb = new JRadioButton("C"); //creating JRadioButton. jcb = new JRadioButton("none"); add(jcb); setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); setVisible(true); } public static void main(String[] args) new Test();

88

89 Swing components 5) JComboBox
Combo box is a combination of text fields and drop-down list.JComboBox component is used to create a combo box in Swing. Following is the constructor for JComboBox, JComboBox(String arr[])

90 import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Test extends JFrame { String name[] = {"Abhi","Adam","Alex","Ashkay"}; //list of name. Test() JComboBox jc = new JComboBox(name); //initialzing combo box with list of name. add(jc); //adding JComboBox to frame. setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); setVisible(true); } public static void main(String[] args) new Test();

91

92 Swing components 6) JProgressBar Constructors :
The class JProgressBar is a component which visually displays the progress of some task. Constructors : JProgressBar() Creates a horizontal progress bar that displays a border but no progress string. JProgressBar(int orient) Creates a progress bar with the specified orientation, which can be either SwingConstants. VERTICAL or SwingConstants.HORIZONTAL. JProgressBar(int min, int max)Creates a horizontal progress bar with the specified minimum and maximum. JProgressBar(int orient, int min, int max)Creates a progress bar using the specified orientation, minimum, and maximum.

93 Progress bar Example import java.awt.*; import javax.swing.*; import javax.swing.BorderFactory; import javax.swing.border.Border; public class ProgressSample { public static void main(String args[]) JFrame f = new JFrame("JProgressBar Sample"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content = f.getContentPane(); JProgressBar progressBar = new JProgressBar(); progressBar.setValue(25); progressBar.setStringPainted(true); Border border = BorderFactory.createTitledBorder("Reading..."); progressBar.setBorder(border); content.add(progressBar, BorderLayout.NORTH); f.setSize(300, 100); f.setVisible(true); }

94 7) ToolTips Creating a tool tip for any JComponent is easy. You just use the setToolTipText method to set up a tool tip for the component. For example, to add tool tips to three buttons, you add only three lines of code: b1.setToolTipText("Click this button to disable the middle button."); b2.setToolTipText("This middle button does nothing when you click it."); b3.setToolTipText("Click this button to enable the middle button.");

95 import javax.swing.JButton;
import javax.swing.JFrame; public class Tooltipdemo extends JFrame { public Tooltipdemo() setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton b = new JButton("Test"); b.setToolTipText("Help text for the button"); getContentPane().add(b, "Center"); pack(); } public static void main(String[] args) new Tooltipdemo().setVisible(true);

96 8) Seperator The JSeparator class provides a horizontal or vertical dividing line or empty space. It's most commonly used in menus and tool bars. We can use separators without even knowing that a JSeparator class exists, since menus and tool bars provide convenience methods that create and add separators customized for their containers. Separators are somewhat similar to borders, except that they are the components which are drawn inside a container, rather than around the edges of a particular component. Here is a picture of a menu that has three separators, used to divide the menu into four groups of items:

97 import javax.swing.*; import java.awt.*; public class SeparatorDemo { public static void main(String args[]) JFrame f = new JFrame("JSeparator Sample"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content = f.getContentPane(); content.setLayout(new GridLayout(0, 1)); JLabel above = new JLabel("Above Separator"); content.add(above); JSeparator separator = new JSeparator(); content.add(separator); JLabel below = new JLabel("Below Separator"); content.add(below); f.setSize(300, 100); f.setVisible(true); }

98 9) Jtable


Download ppt "Introduction to Abstract Windowing Toolkit (AWT) & Swings"

Similar presentations


Ads by Google