Sie sind auf Seite 1von 70

Java Graphics Programming

Using AWT Components


Figure shows the inheritance hierarchies for all the AWT component classes.

The AWT
Provides basic GUI components which are used in all Java applets and applications Has super classes which can be extended and their properties inherited; classes can also be abstract Ensures that every GUI component that is displayed on the screen is a subclass of the abstract class Component Contains Container which is an abstract subclass of Component and which includes two subclasses Panel Window

Containers
The two main types of containers are Window and Panel. Windows are objects of java.awt.Window. Panels are objects of java.awt.Panel.

Building Graphical User Interfaces


The position and size of a component in a container is determined by a layout manager. You can control the size or position of components by disabling the layout manager. You must Then use setLocation(), setSize(), or setBounds() on components to locate them in the container.

Frames
Are subclasses of Window Have title and resize corners Inherit from Component and add components with the add method
Can be used to create invisible Frame objects with a title specified by String Have Border Layout as the default layout Manager Use the setLayout method to change the default layout manager

Panels
Provide a space for components Allow subpanels to have their own layout manager Add components with the add method

Container Layouts
Flow Layout - Default layout for a Panel and Applet. Border Layout - Default layout for a Frame Grid Layout Card Layout GridBag Layout

How to use Frames :

The Frame class provides windows for applets and applications. Every GUI application needs at least one Frame.

How to use Frames :


Import java.awt.*; public class MyWindow extends Frame {

MyWindow() {
setTitle(Employee Registration Form); setSize(200,200);

setVisible(true);
} public static void main(String[] ar) { MyWindow mw = new MyWindow(); }

How to use Panels:


Here's an example of using a Panel instance to hold some Components: Panel p1 = new Panel(); p1.add(new Button(Submit")); p1.add(new Button(Reset")); p1.add(new Button(Cancel")); add(North,p1);//adding to North // side of the Frame

How to use Buttons :


The Button class provides a default button implementation. A button is a simple control that generates an action event when the user clicks it.

//In initialization code: Button b1 = new Button(); b1.setLabel(Click Me");

How to use Labels :


The Label class provides an easy way of putting unselectable text in your program's GUI. Labels are aligned to the left of their drawing area, by default. You can specify that they be centered or right-aligned by specifying Label.CENTER or Label.RIGHT either to the Label

constructor or to the setAlignment() method. As with


every Component, you can also specify the font and color of a Label.

How to use Labels :


Below is the code that the applet uses to create its labels and set their alignment.

Label label1 = new Label(); label1.setText("Left"); Label label2 = new Label("Center"); label2.setAlignment(Label.CENTER); Label label3 = new Label("Right", Label.RIGHT);
Besides the constructor, setText(), and getAlignment() methods used above, the Label class also provides getText() and getAlignment() methods.

How to use Text Fields :


import java.awt.*; class TextDemo extends Frame { TextField tf1, tf2; TextDemo() { setLayout(new FlowLayout()); setSize(300, 200); tf1 = new TextField(); tf2 = new TextField(); add(tf1); add(tf2); } public static void main(String args[]) { TextDemo window = new TextDemo(); window.show(); } }

Lab Session
Write a program to create a Frame. Create two panels, one with two buttons Ok and Cancel, using FlowLayout, and another panel with two text fields one below the other, using BorderLayout.
Place one panel to the north and one to the south of the Frame

Write a program to place six text fields in 2 rows by 3 columns fashion.

Event Driven Programming

What Is An Event?
Events - Objects that describe what happened Event source - The generator of an event Event handlers - A method that receives an event object,deciphers it,and processes the users interaction

Delegation Model (JDK 1.1 and Beyond )


Events are not accidentally handled.

There is better distribution of work among the classes.

The Color class Color(int red, int green, int blue) or Color.blue value setForeground(Color.blue) or setBackground(Color.blue) The Font class Font(String name, int style, int size) Styles - Font.PLAIN, Font.BOLD, Font.ITALIC can have Font.BOLD | Font.ITALIC also The FontMetrics class FontMetrics(Font f) The Graphics class Every component has a graphics context Component.getGraphics() - Ex. button.getGraphics(); g.getFontMetrics()

Graphics

Lab Session
Write a program to display the name of your company with a font size of 30, color - black and background - gray in a frame.

Write a program to display all possible shapes available in the graphics class, in a frame using the API.

Creating User Interfaces

List of AWT Components

Checkbox CheckboxGroup Choice Dialog List Menu TextArea

How to use Checkboxes :


The Checkbox class provides checkboxes :-

Two-state buttons that can be either "on" or "off".


When the user clicks a checkbox, the checkbox state changes and generates an event. If you want a group of checkboxes in which only one checkbox at a time can be "on", you can add a CheckboxGroup (You might know this UI element as a radio button.)

How to use Checkboxes :


Checkbox cb1, cb2, cb3; //These are independent checkboxes.

cb1 = new Checkbox(); //Default state is "off" (false). cb1.setLabel(Java"); cb2 = new Checkbox(Cobol"); cb3 = new Checkbox(Visual Basic"); cb3.setState(true); //Set state to "on" (true).. . .

How to use Choice :

A Choice is a Drop Down Menu When the user chooses an item,

the Choice generates an event.


Choices are useful when you need to display a number of alternatives in a limited amount of space

How to use Choice :

Choice choice;

//Drop Down list of choices

//...Where initialization occurs: choice = new Choice(); choice.addItem(Java"); choice.addItem(Oracle"); choice.addItem(Visual Basic); choice.addItem(SmallTalk");

How to use Dialogs :


Windows that are dependent on other windows -- with the Dialog class. - new Dialog(frame), where frame is the parent window. We can create a dialog with a model using a different constructor. By default, dialogs are non-modal -- the user can keep them up and still work in other windows of the application

How to use Dialogs :


Here's just the code that implements the Dialog object: public class MyWindow extends Frame { Dialog d; Label l; MyWindow() { d=new Dialog(this,true); l=new Label(Invalid number entered); d.add(Center,l); d.setSize(100,200); //This is a must d.show(); //To show the dialog window. // We can activate a dialog window based on // an event. } }

How to use Lists :


The List class provides a scrollable area containing selectable text items (one per line). Lists can allow either multiple selections or just one selection at a time.

How to use Lists :


//Build first list, which allows multiple selections. List1 = new List(2, true); //prefer 2 items visible List1.add(Unix"); List1.add(Dos"); //Build second list, which allows one selection at a time. List2 = new List(); //Defaults to none visible, only one selectable List2.add(Unix"); List2.add(Dos");

How to use Menus:


Menu classes inherit from the MenuComponent class : The AWT provides the following MenuComponent subclasses to support menus: MenuBar : MenuBar represents the platform-dependent notion of a group of menus attached to a window. MenuBars can not be bound to Panels. Menu :

Each menu is represented by a Menu object.


MenuItem : Each item in a menu is represented by a MenuItem object.

How to use Menus:


. Here's just the code that deals with menus: public class MenuWindow extends Frame { public MenuWindow() { MenuBar mb; Menu file, edit; MenuItem newfile, open, close; MenuItem cut, copy, paste; //Build the menu bar. mb = new MenuBar(); setMenuBar(mb); //Set menu bar for the frame Contd. In Next Page...

How to use Menus:

file= new Menu(File); mb.add(file); newfile = new MenuItem(New"); file.add(newfile); open = new MenuItem(Open"); file.add(open); close = new MenuItem(Close"); file.add(close);

How to use TextArea :


TextArea textArea;
//create text area of 5 rows and 30 //columns textArea=new TextArea(5,30) textArea.setEditable(false);

Lab Session
Write a program to show the appearance of a Notepad program using all the menu options.

Create a GUI form using all the GUI components covered in this session.

Write a program to display a Dialog box with a message, using a Font and a Color class.

Using Listener Interfaces


Listener
ActionListener Event Object ActionEvent actionPerformed(ActionEvent e) {

Component Button

List of Listeners
Listener Interfaces ActionListener AdjustmentListener AWTEventListener ComponentListener Methods void actionPerformed(ActionEvent) adjustmentValueChanged(AdjustmentEvent) eventDispatched(AWTEvent) componentHidden(ComponentEvent) componentMoved(ComponentEvent) componentResized(ComponentEvent) componentShown(ComponentEvent) componentAdded(ContainerEvent) componentRemoved(ContainerEvent) focusGained(FocusEvent) focusLost(FocusEvent) itemStateChanged(ItemEvent)

ContainerListener
FocusListener

ItemListener

Listener Interfaces KeyListener

Methods

keyPressed(KeyEvent) keyReleased(KeyEvent) keyTyped(KeyEvent) MouseListener mouseClicked(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent) MouseMotionListener mouseDragged(MouseEvent) mouseMoved(MouseEvent) TextListener textValueChanged(TextEvent)

Listener Interfaces

Methods

WindowListener

windowActivated(WindowEvent) windowClosed(WindowEvent) windowClosing(WindowEvent) windowDeactivated(WindowEvent) windowDeiconified(WindowEvent) windowIconified(WindowEvent) windowOpened(WindowEvent)

Event
ActionEvent ItemEvent

Component
Button, List (Double click), Menu Check box, List, Choice

KeyEvent
MouseEvent TextEvent

Keyboard
Mouse operations TextField and TextArea.

WindowEvent

Window, Frame, Dialog

Multiple Listeners
One component can register itself for more than one listener. All registered listeners have their handler called when the event occurs.

Lab Session
Write a program to show the event handling of a list, choice, check box and radio buttons. Show proper messages.
Write a program to change the background color of the frame using a list of colors. Create a form with three text fields for Name, Age and Salary. Show the details on the screen as a single line, when clicked on the Submit button. Clear the form for next entry.

Applets

What is an Applet ?
A Java class that can be embedded within an HTML page and is downloaded and executed by a web browser. Is loaded as follows :

Browser loads URL


Browser loads the HTML document

Browser loads applet classes


Browser runs the applet

Applet Security Restrictions


Most browsers prevent the following Runtime execution of another program

Any file I/O (input/output)


Calls to any native methods Attempts to open a socket to any system except the host that provided the applet.

Key Applet Methods


init()

start()
stop()

destroy()
paint()

Applet Display
Applets are graphical in nature

paint() method is called by the browser environment


Example of an applet that uses a paint() method : import java.awt.*;

import java.applet.*;
public class HelloJava extends Applet { public void paint(Graphics g) {

g.drawString(Hello Java!,25,25);
} }

init()

Applet methods and the Applet Life Cycle


Called when the applet is created Can be used to initialize data values

start() Runs when the applet becomes visible stop() Called when the applet becomes invisible destroy() Called when the browser or the appletviewer is closed paint() Called automatically when the applet is started

AWT Painting
paint(Graphics g) repaint() update(Graphics g)

repaint()

AWT thread (waiting)

Exposure

update() update background call paint()

paint()

What is the appletviewer ?


A Java application that enables you to run applets without using a web browser

It loads the HTML file supplied as an argument


appletviewer HelloJava.html It needs at least the following HTML code : <html> <applet code=HelloJava.class width=100 height=100> </applet> </html>

Syntax of applet tag


<applet [ archive=archiveList ] code=appletFile.class width=pixels height=pixels [ codebase=codebaseURL ] [ alt=alternateText ] [ name=appletInstanceName ] [ align=alignment ] [ vspace=pixels ] [ hspace=pixels ] > [ <param name=appletAttribute1 value=value> ] [ <param name=appletAttribute2 value=value> ]

</applet>

Additional Applet Facilities


getDocumentBase() - Returns a URL object that describes

directory of the current browser page.


getCodeBase() - Returns a URL object that describes the source directory of the applet class. getImage(URL base, String target) and getAudioClip(URL base, String target) - Use the URL

object as a starting point.

A sample image test


//HelloJava extended to draw an image //Assume existence of javalogo.gif import java.awt.*; import java.applet.*; public class HwImage extends Applet { Image logo; public void init() { logo = getImage(getDocumentBase(), javalogo.gif); } public void paint(Graphics g) { g.drawImage(logo,25,25,this); } }

Looping an Audio Clip


Loading an audio clip
Playing an audio clip

Stopping an audio clip

A sample Audio Looping Test


//HelloJava extended to loop an audio track //Assume existence of spacemusic.au import java.awt.Graphics; import java.applet.*; public class HwLoop extends Applet { AudioClip sound; public void init() { sound=getAudioClip(getDocumentBase(), spacemusic.au); } public void paint(Graphics g) { g.drawString(Audio test,25,25); } public void start() { sound.loop(); } public void stop() { sound.stop(); } }

Lab Session
Write a program that demonstrates the use of the life cycle methods of an applet. Show proper messages on the screen.

Write an applet to load an image file

Write an applet to accept two numbers in text fields and compute the sum of the numbers when clicked on the Add button.

Advanced Graphics

Grid Bag Layout Manager


GridBagLayout enables finer control over the size and placement of individual cells in a grid layout. Each grid area or component is associated with a particular GridBagConstraints instance that specifies how the component is laid out within the display area. Like GridLayout, the GridBagLayout layout manager aligns components within a rectangular grid of cells. Where GridLayout and GridBagLayout differ is in that GridBagLayout use an object called GridBagConstraints.

By setting values within the GridBagConstraints object, components can be aligned vertically or horizontally (with or without insets and padding), told to expand to fill the given area , and instructed on how to behave upon resizing of the window. You initialize and utilize a GridBagLaoyout and its associated GriBagConstraints object as follows: private GridBagLayout guiLayout; private GridBagConstraints guiConstraints; guiLayout = new GridBagLayout(); setLayout(guiLayout); guiConstraints = new GridBagConstraints(); guiConstraints.anchor = GridBagConstraints.CENTER;

Using GridBagConstriants
Only new about the code in the previous page is the final statement: guiConstraints.anchor = GridBagConstraints.CENTER; The GridBagConstraints object, associated with the GridBagLayout layout manager, contains instance variables that can be set to govern how components are laid out. This instance variable is used to instruct GridBagLayout on how to place a component when it is smaller than its cell. Valid values are: GridBagConstraints.CENTER GridBagConstraints.NORTH GridBagConstraints.EAST GridBagConstraints.SOUTH GridBagConstraints.SOUTHEAST

GridBagConstraints Instance Variables The API pages for GridBagLayout explains the instance variables used for governing component layout. These are gridx and gridy These variables specify the characteristics of the cell at the upper left of the components display area, where the upper leftmost cell has the address gridx=0, gridy=0. gridwidth and gridheight These variables specify the number of cells in a row (gridwidth) or column (gridheight) in the components display area. The default value is 1. fill fill is used when the components display area is larger than the components requested size; fill determines whether (and how) to resize the component. Contd In Next Page...

ipadx and ipady

These variables specify the internal padding; that is , how much to add to the minimum size of the component. insets

insets specifies the external padding of the component; that is, the minimum amount of the space between the component and the edges of its display area. anchor

This variable is used when the component is smaller than its display area; anchor determines where to the place the component.

GridBagConstraints Example import java.awt.*; public class GridBagLayoutDemo extends Frame { void makeButton(String name, GridBagConstraints gbc) { Button button = new Button(name); add(button, gbc); } public GridBagLayoutDemo() { setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); setFont(new Font("Helvetica", Font.PLAIN, 14)); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; makeButton("Button1", c); makeButton("Button2", c); makeButton("Button3", c); Contd. In Next Page..

c.gridwidth = GridBagConstraints.REMAINDER; //end row makeButton("Button4", c); c.weightx = 0.0; //reset to the default makeButton("Button5", c); //another row //next-to-last in row c.gridwidth = GridBagConstraints.RELATIVE; makeButton("Button6", c); c.gridwidth = GridBagConstraints.REMAINDER; //end row makeButton("Button7", c); c.gridwidth = 1; //reset to the default c.gridheight = 2; c.weighty = 1.0; makeButton("Button8", c); Contd. In Next Page..

c.weighty = 0.0; //reset to the default c.gridwidth = GridBagConstraints.REMAINDER; //end row c.gridheight = 1; //reset to the default makeButton("Button9", c); makeButton("Button10", c); } public static void main(String args[]) { GridBagLayoutDemo window = new GridBagLayoutDemo(); window.pack(); window.show(); } }

Card Layout
- Create a panel for card layout - Create different panels as cards and add to this card panel - Change the card (panel) on some event Example : Panel cards; Panel p1, p2 //for buttons, text fields .... cards.setLayout(new CardLayout()); cards.add(ButtonPanel,p1); cards.add(TextPanel,p2); CardLayout cl = (CardLayout) (cards.getLayout()); cl.show(cards, ButtonPanel);

Lab Session
Write a program to create the login screen using Grid bag layout.

Exercise (contd)
16. A need to persist the data has now arisen as the client observes that the development team is either getting the data from the console or is having it stored as string attributes in the programs. The client wishes that the data should be persisted and reused by any other programs, as well. Hence, store the data in the Collection into a file. Implement methods to read/write the data to/from the given file. The access methods should be synchronized

Das könnte Ihnen auch gefallen