• No results found

Chpate

r

Using Standard Java Packages:

Question: What is a user interface?

Answer:

The user interface is that part of a program that interacts with the user of the program. User interfaces take many forms. These forms range in complexity from simple command-line interfaces to the point-and-click graphical user interfaces provided by many modern applications There are two types of GUI elements:

Component: Components are elementary GUI entities, such as Button, Label, and TextField.

Container: Containers, such as Frame and Panel, are used to hold components in a specific layout (such as FlowLayout or GridLayout). A container can also hold sub-containers.

AWT Packages

AWT is huge! It consists of 12 packages of 370 classes (Swing is even bigger, with 18 packages of 737 classes as of JDK 1.8). Fortunately, only 2 packages - java.awt and java.awt.event - are commonly-used.

The java.awt package contains the core AWT graphics classes:

 GUI Component classes, such as Button, TextField, and Label,

 GUI Container classes, such as Frame and Panel,

 Layout managers, such as FlowLayout, BorderLayout and GridLayout,

 Custom graphics classes, such as Graphics, Color and Font.

The java.awt.event package supports event handling:

 Event classes, such as ActionEvent, MouseEvent, KeyEvent and WindowEvent,

 Event Listener Interfaces, such as ActionListener, MouseListener, KeyListener and WindowListener,

 Event Listener Adapter classes, such as MouseAdapter, KeyAdapter, and WindowAdapter.

 AWT provides a platform-independent and device-independent interface to develop graphic programs that runs on all platforms, including Windows, Mac OS, and Unixes.

2.3 AWT Container Classes:

Question: Define top-level and secondary container .Write about flow layout with syntax used in Java. Exam-2014

Top-Level Containers: Frame, Dialog and Applet

Each GUI program has a top-level container. The commonly-used top-level containers in AWT are Frame, Dialog and Applet:

 A Frame provides the "main window" for the GUI application, which has a title bar (containing an icon, a title, the minimize, maximize/restore-down and close buttons), an optional menu bar, and the content display area. To write a GUI program, we typically start with a subclass extending from java.awt.Frame to inherit the main window as follows:

A b u S a l e h M u s a M i a h ( A b i d ) 0 1 7 3 4 2 6 4 8 9 9 Page 45 Secondary Containers: Panel and ScrollPane

Secondary containers are placed inside a top-level container or another secondary container.

AWT also provide these secondary containers:

 Panel: a rectangular box under a higher-level container, used to layout a set of related GUI components in pattern such as grid or flow.

 ScrollPane: provides automatic horizontal and/or vertical scrolling for a single child component.

Basic Terminologies Term Description Component

Component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. For examples buttons, checkboxes, list and scrollbars of a graphical user interface.

Container

The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends Container class are known as container

Examples: panel, box

Frame A Frame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. Frame encapsulates window. It and has a title bar, menu bar, borders, and resizing corners.

Panel Panel provides space in which an application can attach any other components, including other panels.

Window

Window is a rectangular area which is displayed on the screen. In different window we can execute different program and display different data. Window provide us with multitasking environment. A window must have either a frame, dialog, or another window defined as its owner when it's constructed.

Useful Methods of Component class

Every user interface considers the following three main aspects:

UI elements: These are the core visual elements the user eventually sees and interacts with.

GWT provides a huge list of widely used and common elements varying from basic to complex which we will cover in this tutorial.

Layouts: They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in Layout chapter.

Behavior: These are events which occur when the user interacts with UI elements. This part will be covered in Event Handling chapter.

AWT UI Elements:

Following is the list of commonly used controls while designed GUI using AWT.

Sr. No. Control & Description

1 Label: A Label object is a component for placing text in a container.

2 Button: This class creates a labeled button.

3 Check Box: A check box is a graphical component that can be in either an on (true) or off (false) state.

4 Check Box Group: The CheckboxGroup class is used to group the set of checkbox.

5 List: The List component presents the user with a scrolling list of text items.

6 Text Field: A TextField object is a text component that allows for the editing of a single line of text.

7 Text Area: A TextArea object is a text component that allows for the editing of a multiple lines of text.

8 Choice: A Choice control is used to show pop up menu of choices. Selected choice is shown on the top of the menu.

9 Canvas: A Canvas control represents a rectangular area where application can draw something or can receive inputs created by user.

10 Image: An Image control is superclass for all image classes representing graphical images.

11 Scroll Bar: A Scrollbar control represents a scroll bar component in order to enable user to select from range of values.

12 Dialog: A Dialog control represents a top-level window with a title and a border used to take some form of input from the user.

13 File Dialog: A FileDialog control represents a dialog window from which the user can select a file.

Question: What is the difference between container and component in a GUI? Exam-2015 Answer:

Difference between container and component:

Container Component

A container is a component that holds and manages other components. Containers display components using a layout manager.

a component is the basic user interface object and is found in all Java applications.

Components include lists, buttons, panels, and windows.

To use components, we need to place them in

a container. Component important for interaction

JComponent, in turn, inherits from the Container class in the Abstract Windowing Toolkit (AWT). So Swing is based on classes inherited from AWT.

Swing components inherit from the

javax.Swing.JComponent class, which is the root of the Swing component hierarchy.

Containers:

Frame Window Dialog Panel

List of common Components List

A b u S a l e h M u s a M i a h ( A b i d ) 0 1 7 3 4 2 6 4 8 9 9 Page 47 Label

Creating graphical user interfaces with AWT,

To create simple awt example, you need a frame. There are two ways to create a frame in AWT.

1. By extending Frame class (inheritance)

2. By creating the object of Frame class (association)

Frame Typically holds (hosts) other components Common methods:

 JFrame(String title) – constructor, title optional

 setSize(int width, int height) – set size

 add(Component c) – add component to window

 setVisible(boolean v) – make window visible or not. Don’t forget this public void

 setDefaultCloseOperation(int op) Makes the frame perform the given action when it closes.

– Common value passed: JFrame.EXIT_ON_CLOSE

– If not set, the program will never exit even if the frame is closed.

 public void setSize(int width, int height) Gives the frame a fixed size in pixels.

 public void pack() Resizes the frame to fit the components inside it snugly.

Some Attribute of Frame:

AWT Example by Inheritance

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button component on the Frame.

1. import java.awt.*;

2. class First extends Frame{

3. First(){

4. Button b=new Button("click me");

5. b.setBounds(30,100,80,30);// setting button position 6. add(b);//adding button into frame

7. setSize(300,300);//frame size 300 width and 300 height 8. setLayout(null);//no layout manager

9. setVisible(true);//now frame will be visible, by default not visible 10. }

11. public static void main(String args[]){

12. First f=new First();

13. }}

AWT Example by Association

Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are showing Button component on the Frame.

import java.awt.*;

class First2{

First2(){

Frame f=new Frame();

Button b=new Button("click me");

b.setBounds(30,50,80,30);

f.add(b);

f.setSize(300,300);

f.setLayout(null);

f.setVisible(true);

}

public static void main(String args[]){

First2 f=new First2();

}}

Method 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

A b u S a l e h M u s a M i a h ( A b i d ) 0 1 7 3 4 2 6 4 8 9 9 Page 49 Managing graphics objects with GUI layout managers,

Question: What is layout manager? Briefly explain about the basic layout manager in Java and give the syntax of each layout manager. Exam-2013

Question: Write down the constructors of Flow Layout, Card Layout and GridBag Laoyout manager. Explain them. Exam-2015

Layout Manager:

A layout manager is an object that implements the LayoutManager interface*

and determines the size and position of the components within a container.

Although components can provide size and alignment hints, a container's layout manager has the final say on the size and position of the components within the container.

The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers.

There are following classes that represents the layout managers:

 java.awt.BorderLayout

 java.awt.FlowLayout

 java.awt.GridLayout

 java.awt.CardLayout

 java.awt.GridBagLayout

 javax.swing.BoxLayout

 javax.swing.GroupLayout

 javax.swing.ScrollPaneLayout

 javax.swing.SpringLayout etc.

We Discuss here some AWT of layout:

 Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain

one component only. It is the default layout of frame or window. The BorderLayout provides five constants for each region:

1. public static final int NORTH 2. public static final int SOUTH 3. public static final int EAST 4. public static final int WEST 5. public static final int CENTER

false.

import java.awt.*;

JButton b1=new JButton("NORTH");;

JButton b2=new JButton("SOUTH");;

JButton b3=new JButton("EAST");;

JButton b4=new JButton("WEST");;

JButton b5=new JButton("CENTER");;

public static void main(String[] args) { new Border();

}

}

 Java GridLayout

The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.

Constructors of GridLayout class 1. GridLayout(): creates a grid

layout with one column per component in a row.

2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the

components.

3. GridLayout(int rows, int columns, int hgap, int vgap):

creates a grid layout with the given rows and columns

public class MyGridLayout{

A b u S a l e h M u s a M i a h ( A b i d ) 0 1 7 3 4 2 6 4 8 9 9 Page 51 JFrame f;

MyGridLayout(){

f=new JFrame();

JButton b1=new JButton("1");

JButton b2=new JButton("2");

JButton b3=new JButton("3");

JButton b4=new JButton("4");

JButton b5=new JButton("5");

JButton b6=new JButton("6");

JButton b7=new JButton("7");

JButton b8=new JButton("8");

JButton b9=new JButton("9");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

f.add(b6);f.add(b7);f.add(b8);f.add(b9);

f.setLayout(new GridLayout(3,3));

//setting grid layout of 3 rows and 3 columns

f.setSize(300,300);

f.setVisible(true);

}

public static void main(String[] args) { new MyGridLayout();

} }

Java FlowLayout

The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel.

Fields of FlowLayout class 1. public static final int LEFT 2. public static final int RIGHT 3. public static final int CENTER 4. public static final int LEADING 5. public static final int TRAILING Constructors of FlowLayout class

1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.

2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap.

3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given horizontal and vertical gap.

Example of FlowLayout class import java.awt.*;

import javax.swing.*;

public class MyFlowLayout{

JFrame f;

f.setLayout(new FlowLayout(FlowLa yout.RIGHT));

//setting flow layout of right alignme nt

f.setSize(300,300);

f.setVisible(true);

}

public static void main(String[] args) { new MyFlowLayout();

} } Java BoxLayout

A b u S a l e h M u s a M i a h ( A b i d ) 0 1 7 3 4 2 6 4 8 9 9 Page 53 The BoxLayout is used to arrange the components either vertically or horizontally. For this purpose, BoxLayout provides four constants. They are as follows:

Note: BoxLayout class is found in javax.swing package.

Fields of BoxLayout class

1. public static final int X_AXIS 2. public static final int Y_AXIS 3. public static final int LINE_AXIS 4. public static final int PAGE_AXIS Example of BoxLayout class with

Y-import java.awt.*;

import javax.swing.*;

public class BoxLayoutExample1 extends Frame { Button buttons[];

public static void main(String args[]){

BoxLayoutExample1 b=new BoxLayoutExample1(); one component is visible at a time. It treats each component as a card that is why it is known as CardLayout. Constructors of CardLayout class

1. 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.

Commonly used methods of CardLayout class

 public void next(Container parent): is used to flip to the next card of the given container.

 public void previous(Container parent): is used to flip to the previous card of the given container.

 public void first(Container parent): is used to flip to the first card of the given container.

 public void last(Container parent): is used to flip to the last card of the given container.

public void show(Container parent, String name): is used to flip to the specified card with the given name. me implements ActionListener{

CardLayout card;

//create CardLayout object with 40 hor space and 30 ver space

public void actionPerformed(ActionEvent e) { card.next(c);

cl.setDefaultCloseOperation(EXIT_ON_CLOSE);

} }

 Java GridBagLayout

The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline.

The components may not be of same size. Each GridBagLayout object maintains a

dynamic, rectangular grid of cells. Each component occupies one or more cells known as

its display area. Each component associates an instance of GridBagConstraints. With the

help of constraints object we arrange component's display area on the grid. The

A b u S a l e h M u s a M i a h ( A b i d ) 0 1 7 3 4 2 6 4 8 9 9 Page 55

GridBagLayout manages each component's minimum and preferred sizes in order to determine component's size.

Summary of Layout Manager:

Sr. No. Layout Manager & Description 1 BorderLayout

The borderlayout arranges the components to fit in the five regions: east, west, north, south and center.

3 FlowLayout

The FlowLayout is the default layout.It layouts the components in a directional flow.

4 GridLayout

The GridLayout manages the components in form of a rectangular grid.

5

GridBagLayout

This is the most flexible layout manager class.The object of GridBagLayout aligns the component vertically,horizontally or along their baseline without requiring the components of same size.

Drawing methods include:

drawString – For drawing text

g.drawString("Hello", 10, 10);

drawImage – For drawing images

g.drawImage(img,

0, 0, width, height,

0, 0, imageWidth, imageHeight, null);

drawLine, drawArc, drawRect, drawOval, drawPolygon – For drawing geometric shapes g2.draw(new Line2D.Double(0, 0, 30, 40));

Depending on your current need, you can choose one of several methods in the Graphics class based on the following criteria:

Whether you want to render the image at the specified location in its original size or scale it to fit inside the given rectangle

Whether you prefer to fill the transparent areas of the image with color or keep them transparent

Fill methods apply to geometric shapes and include fillArc, fillRect, fillOval, fillPolygon.

Whether you draw a line of text or an image, remember that in 2D graphics every point is determined by its x and y coordinates. All of the draw and fill methods need this information which determines where the text or image should be rendered.

For example, to draw a line, an application calls the following:

java.awt.Graphics.drawLine(int x1, int y1, int x2, int y2)

In this code (x1, y1) is the start point of the line, and (x2, y2) is the end point of the line.

So the code to draw a horizontal line is as follows:

Graphics.drawLine(20, 100, 120, 100);

Each Graphics object has its own coordinate system, and all the methods of Graphics including those for drawing Strings, lines, rectangles, circles, polygons and more. Drawing in Java starts with particular Graphics object. You get access to the Graphics object through the paint(Graphics g) method of your applet. Each draw method call will look like g.drawString("Hello World", 0, 50) where g is the particular Graphics object with which you're drawing.

For convenience's sake in this lecture the variable g will always refer to a preexisting object of the Graphics class. As with any other method you are free to use some other name for the particular Graphics context, myGraphics or appletGraphics perhaps.

Layout strategy for border interactors

As an example, suppose that you want to write a program that displays two buttons—Start and Stop—at the bottom of a program window. Let’s ignore for the moment what those buttons actually do and concentrate instead on how to make them appear. If you use the standard layout management tools provided by the Program class, all you have to do is include the following code as part of the init method:

add(new JButton("Start"), SOUTH);

add(new JButton("Stop"), SOUTH);

A b u S a l e h M u s a M i a h ( A b i d ) 0 1 7 3 4 2 6 4 8 9 9 Page 57 Question: How to implement a listener interface. Exam-2013

Answer:

Assigning action listeners to the buttons

Creating the buttons, however, accomplishes only part of the task. To make the buttons active, you need to give each one an action listener so that pressing the button performs the appropriate action.

These days, the most common programming style among experienced Java programmers is to assign an individual action listener to each button in the form of an anonymous inner class.

Suppose, for example, that you want the Start and Stop buttons to invoke methods called startAction and stopAction, respectively. You could do so by changing the initialization code as follows:

JButton startButton = new JButton("Start");

startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { startAction();

} });

add(startButton, SOUTH);

JButton stopButton = new JButton("Start");

stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { stopAction();

} });

add(stopButton, SOUTH);

Question:Define actionPerfomed().What is the signature of the actionPerfomed method? Exam-2014

Answer:

Define actionPerfomed().

The actionPerformed() method is invoked automatically whenever you click on the registered component.

public abstract void actionPerformed(ActionEvent e);

The ActionEvent argument e is the object that represents the event. This object contains information about the event, like which component is the event source. The ActionEvent class has two methods that you might find beneficial: getActionCommand() and getSource() (which is actually inherited by the ActionEvent class from the EventObject class). The first method returns a string that identifies the action. This string is usually set by the event source, using a method called setActionCommand. The second method returns the event source object

Example:

import java.awt.*;

import java.awt.event.*;

public class ActionListenerExample { public static void main(String[] args) {

Frame f=new Frame("ActionListener Example");

final TextField tf=new TextField();

tf.setBounds(50,50, 150,20);

Button b=new Button("Click Here");

b.setBounds(50,100,60,30);

b.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

tf.setText("Welcome to Javatpoint.");

} });

f.add(b);f.add(tf);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

} }

Signature of the actionPerfomed method:

The signature of actionPerfomed method is ActionEvent e

Event handling of various components.

Question: What is an event? List down the names of some of the Java AWT event listener interfaces.

Question: What is an Event?

Change button in the state of an object is known as event.

i.e. event describes the change in state of source. Events are generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to happen.

Types of Event

A b u S a l e h M u s a M i a h ( A b i d ) 0 1 7 3 4 2 6 4 8 9 9 Page 59 The events can be broadly classified into two categories:

 Foreground Events

Those events which require the direct interaction of user.

They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page etc.

 Background Events –

 Background Events –

Related documents