980 likes | 995 Views
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. Abstract Window Toolkit.
E N D
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
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.
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. AWT (Abstract Windowing Toolkit)
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. Swing
Component Components are generally the things that the user interacts with. List of common Components List Scrollbar TextArea TextField Choice Button Label ... All containers
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 Container
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); Windows and Frames
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. 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. 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. Creating a Graphical User Interface
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. 12.2 Frames
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. The Frame Class
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. 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. 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. Frame Methods
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. Creating a Frame
FrameTest.java // 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); } }
Frame created by the FrameTest program: As with the other AWT components, the appearance of a frame depends on the platform. 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. Creating 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. Setting the Location of 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); Adding Components to a Frame
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 } publicstaticvoid main(String args[]) { First f=new First(); } }
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(); } }
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); Panels The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc.
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));
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.
Label Ll = new Label("Enter password:"); Ll.setAlignment(Label.RIGHT); Ll.add(aLabel);
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, booleanmultipleMode) Creates a new scrolling list initialized to display the specified number of rows.
List L1 = new List(); L1.add(“India"); L1.add(“UK"); L1t.add(“USA");
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.
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(); }
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"); Choice
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 emailTextField = new TextField(); TextField passwordTextField = new TextField(); passwordTextField.setEchoChar("*"); String userEmail = emailTextField.getText(); String userpassword = passwordTextField.getText(); TextField
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(); TextArea
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. Layout Managers
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
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. Layout Managers (cont)
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
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
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) align – alignment used by the manager A default 5-unit horizontal and vertical gap. 3)FlowLayout() A centered alignment and a default 5-unit horizontal and vertical gap.
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>*/
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
The regions of the BorderLayout are defined as follows: Center North West East South Border Layout (cont)
Border Layout Constructors 1)BorderLayout(hgap, vgap) hgap – horizontal gaps between components vgap – vertical gaps between components 2)BorderLayout() No vertical or horizontal gaps.
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>*/