Beruflich Dokumente
Kultur Dokumente
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.
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
The Frame class provides windows for applets and applications. Every GUI application needs at least one Frame.
MyWindow() {
setTitle(Employee Registration Form); setSize(200,200);
setVisible(true);
} public static void main(String[] ar) { MyWindow mw = new MyWindow(); }
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.
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
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
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.
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).. . .
Choice choice;
//...Where initialization occurs: choice = new Choice(); choice.addItem(Java"); choice.addItem(Oracle"); choice.addItem(Visual Basic); choice.addItem(SmallTalk");
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);
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.
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
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
Event
ActionEvent ItemEvent
Component
Button, List (Double click), Menu Check box, List, Choice
KeyEvent
MouseEvent TextEvent
Keyboard
Mouse operations TextField and TextArea.
WindowEvent
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 :
start()
stop()
destroy()
paint()
Applet Display
Applets are graphical in nature
import java.applet.*;
public class HelloJava extends Applet { public void paint(Graphics g) {
g.drawString(Hello Java!,25,25);
} }
init()
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()
Exposure
paint()
</applet>
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 accept two numbers in text fields and compute the sum of the numbers when clicked on the Add button.
Advanced Graphics
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...
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