Chapter - 8 - 9 - 10 - Java GUI
Chapter - 8 - 9 - 10 - Java GUI
Objective:
After completing this Topic, you will be familiar with AWT Package and able to create GUI using AWT Components 1 . Introduction to AWT and AWT Components 2 . Visual Components 3 . The Container Components 4 . The Menu 5 . Utility classes
Copyright 2004, Cognizant Academy, All Rights Reserved 2
Component
Visual Component
Container Component
Menu Component
button.setEnabled(true);
figure 1 button.setEnabled(false);
figure 2
Copyright 2004, Cognizant Academy, All Rights Reserved 5
Visual Components
AWT Visual Components
Button Label Checkbox TextField TextArea Choice List FileDialog Canvas ScrollPane Scrollbar
Visual Components
This is the sample program to create components.
1
import java.awt.Button; import java.awt.Frame; class Sample extends Frame { public static void main(String args[]) { //Create an instance. Frame mainFrame =new Sample(); }
2
Sample() { //Set the title of window setTitle("CTS: Visual component Demo"); setSize(300,140); //Set the size of the frame. setVisible(true); //Make window visible. /* Change only following lines */ Button button = new Button("Click me!"); button.setBounds(80,60,140,40); add(button); } }//End of Class
Continue
Visual Components
Button
The button class implements push button
Button button = new Button("Click me!");
Constructor :
public Button() public Button(String label)
Visual Components
Label
The label is only used to display any text, and not for user interaction
Label label = new Label( This is Label ");
Constructor :
public Label() public Label(String label) public Label(String label, int alignment)
Copyright 2004, Cognizant Academy, All Rights Reserved 9
Visual Components
Checkbox
The Checkbox is a kind of button with two states. Two states are true (Checked) and false (Unchecked).
Label label = new Label( This is Label ");
Constructor :
public Checkbox() public Checkbox(String label) public Checkbox(String label, CheckboxGroup group, boolean state)
10
Visual Components
TextField
The TextField is used to accept text from user
TextField textfield = new TextField ( Input here");
Constructor :
public TextField() public TextField(int cols) public TextField(String text) public TextField(String text, int cols)
Copyright 2004, Cognizant Academy, All Rights Reserved 11
Visual Components
TextArea
The TextArea is used to accept text from user
TextArea textarea = new TextArea ( Input here");
Constructor :
public TextArea() public TextArea(int rows, int cols) public TextArea(String text) public TextArea(String text, int rows, int cols)
12
Visual Components
Choice
The Choice is also called as pull-down list.
Choice choice = new Choice (); choice.addItem(Item 1); //To add Items to Choice choice.addItem(Item 2);
Constructor :
public Choice()
13
Visual Components
List
The List is a collection of text items. List can be used for single selection or multi selection
List list = new List(); list.add(List Item 1); list.add(List Item 2);
Constructor :
public List() public List(int rows) public List(int rows, boolean isMultipleSelections)
14
Visual Components
FileDialog
File open or file save dialog. Appearance of this dialog box is platform dependent
FileDialog filedialog = new FileDialog (this, Select File to Load, FileDialog.LOAD);
Constructor : public FileDialog(Frame parentWindow, String dlgTitle) public FileDialog(Frame parentWindow, String dlgTitle, int dlgMode)
Copyright 2004, Cognizant Academy, All Rights Reserved 15
Visual Components
Canvas
Without any default appearance or behavior We can use Canvas to create custom drawing Canvas canvas = new Canvas (); canvas.setBackground(Color. BLUE); canvas.setSize(200,200);
Constructor :
public Canvas ()
Copyright 2004, Cognizant Academy, All Rights Reserved 16
Visual Components
ScrollPane
Form of panel Can contain child component having dimensions greater than the ScrollPane Scroll pane provides horizontal or/and vertical scrollbars
//Code snippet ScrollPane scrollpane = new ScrollPane (): TextArea bigText = new TextArea(" This is very very Long Text .. !!!"); bigText.setVisible(true); scrollpane.add(bigText); add(scrollpane);
Constructor :
ScrollPane() ScrollPane(int scrollBarPolicy)
Copyright 2004, Cognizant Academy, All Rights Reserved 17
Visual Components
Scrollbar
The Scrollbar component that adjusts scroll panes and lists which is available as a component in Scrollbar's own right.
setLayout(null); Scrollbar sb = new Scrollbar(Scrollbar.HORIZONTAL, 10, 10, 0, 300); sb.setBounds(3,26,300,20); Range of scrollbar add(sb);
Constructor :
Container Components
AWT Container Components
Applet Frame Panel Dialog
19
Container Components
Hierarchy for Container components
Component
Container
Panel
Window
Applet
Frame
Dialog
20
Container Components
Applet
Applets are Java programs that are integrated in Web pages. Every applet is implemented by creating a subclass of the Applet class. Import java.applet.*; Java.applet package contains
- 1 class : Applet - 3 interfaces : AppletContext, AppletStub, and AudioClip
21
Container Components
Rules for Applet / Restriction on Applet :
Applet can not execute any program on local machine Applet can not access any file on local machine Applet can not open socket connection to any one other than from where it is down loaded If any Applet opens any new window then that window gives warning and message box
22
Container Components
Applet example :
//FirstApplet.java import java.applet.*; import java .awt.Button; import java.awt.Graphics; public class FirstApplet extends Applet { Button b = new Button ("Click Me"); public FirstApplet() { b.setBounds(20,25,100,40); this.setLayout(null); this.add(b); } public void paint (Graphics g) { g.drawString(Applet Example",14,14); }
2
public void init() { System.out.println("Applet Initialized "); } public void start() { System.out.println("Applet Started"); } public void stop() { System.out.println("Applet Stopped"); } public void destroy(){ System.out.println("Applet Destroyed"); } } //End Applet Class
Continue
Copyright 2004, Cognizant Academy, All Rights Reserved 23
Container Components
Applet life cycle
Init Start Stop Destroy Init
Applet Loaded
Start
Window Maximized
Stop
Window Closed
Destroy
24
Container Components
HTML Code to use applet in HTML file
<html> <body> <applet code= "FirstApplet.class" height= "100" width = "140" > </applet> </body> </html>
25
Container Components
Figure 1
Figure 2
26
Container Components
Figure 1
27
Container Components
Parameter passing to Applet :
Code snippet in java file String s = new String(); public void init(){ s="Parameter :" + getParameter("Param1"); System.out.print("Applet Initialized "); } public void paint (Graphics g){ g.drawString(s,14,14); } Constructor : public Button() Creates a button with no label. public Button(String label) Creates a button with the indicated label.
Copyright 2004, Cognizant Academy, All Rights Reserved
Code snippet in HTML file <html> <body> <applet code= "FirstApplet.class height= "100 width = "140" > <param name= "Param1 value= "Cognizant"> </param> </applet> </body> </html>
28
Container Components
Figure 2
29
Container Components
Other Applet Attribute Tags:
< APPLET [CODEBASE = code_Base_URL] CODE = applet_File [ALT = alternate_Text] [NAME = applet_Instance_Name] WIDTH = in_Pixels HEIGHT = in_Pixels [ALIGN = alignment] [VSPACE = in_Pixels] [HSPACE = in_Pixels] > [< PARAM NAME = applet_Parameter1 VALUE = value >] [< PARAM NAME = applet_Parameter2 VALUE = value >] ...... </APPLET>
Copyright 2004, Cognizant Academy, All Rights Reserved 30
Container Components
Frame
Create a standard window import java.awt.Frame Constructors :
Frame() Frame(String frameTitle)
Methods :
setTitle(String), setVisible(boolean), setSize(int, int), setSize(Dimension) Dimension getSize().
31
Container Components
Panel
Subclass of container Panel is super class for applet Intermediate level of space organization of GUI. Does not contain Title bar , Menu bar and Border add() method
32
Container Components
Dialog
Pop-up window User input Modal or Modeless Constructors :
Dialog(Frame parentWindow,boolean Mode) Dialog(Frame parentWindow, String windowTitle, boolean Mode)
Example :
Save Dialog box Load Dialog box etc.
33
The Menu
Menus
Pull-down menus
Tear-off menu.
34
The Menu
Menu bar
Menu Items
35
The Menu
// Menu demo code 1 import java.awt.*; import java.awt.event.*; class Test extends Frame { MenuBar mb; public Test(){ mb=new MenuBar(); Menu menu=new Menu("File"); MenuItem mn=new MenuItem("New"); MenuItem mo=new MenuItem("Open"); menu.add(mn); menu.add(mo); mb.add(menu); this.setMenuBar(mb); } // Test Constructor
2
public static void main(String args[] ){ System.out.println("Starting Test..."); Test mainFrame = new Test(); mainFrame.setSize(200, 200); mainFrame.setTitle("Test"); mainFrame.setVisible(true); } }
36
The Menu
Figure 1
Figure 2
Figure 3
37
The Menu
A PopupMenu class implements a menu which can be dynamically popped up at a specified position within a component. public class PopupMenu extends Menu As the inheritance hierarchy suggests, a PopupMenu can be used anywhere a Menu can be used. However, if you use a PopupMenu like a Menu (e.g., We add it to a MenuBar), then you can not call show on that PopupMenu. We can show Popup Menu to specified location using show() method void show(Component origin, int x, int y) Shows the popup menu at the x, y position relative to an origin component.
Copyright 2004, Cognizant Academy, All Rights Reserved 38
Utility classes
Vectors
Dimension Insets Point Polygon Rectangle Shape
Color
Color SystemColor
39
Utility classes
Resource
Cursor Font FontMetrics Graphics Image PrintGraphics PrintJob Toolkit
40
Utility classes
Vectors
Dimension : The Dimension class encapsulates the width and height of a
component in a single object. e.g. void setSize(Dimension d) method of Component
Point : A point represents an coordinate. Polygon : A polygon consists of a list of, where each successive pair of
coordinates defines a side of the polygon
Utility classes
Color
Color : This class encapsulate colors using the RGB format. SystemColor : A class to encapsulate symbolic colors representing the
color of native GUI objects on a system.
Resource
Cursor : A class to encapsulate the bitmap representation of the mouse
cursor.
Font : The Font class represents fonts, which are used to render text on
screen.
Utility classes
Graphics : The Graphics class is the abstract base class for all graphics
contexts that allow an application to draw onto components.
Image : The abstract class Image is the superclass of all classes that
represent graphical images.
Note : Example code snippets for Dimension, Point, Polygon, Rectangle, Color,Font, Graphics, Image, Toolkit are in Topic Painting
43
: Quiz
Which are the categories for AWT Components ? Give three methods of AWT Component which are inherited from Component ? What is difference between setBounds() and setSize() ?
45
46
Objective
After completing this Topic, you will be able to capture and handle AWT Component Events using Listeners/Adapters . In this Topic we will cover 1. Event Delegation Model 2. Event Hierarchy 3. Event Listeners 4. Event Adapters
47
Event Listener
48
Event Hierarchy
Java.util.EventObject
Java.awt.AWTEvent
ActionEvent
AdjustmentEvent ComponentEvent
TextEvent
ItemEvent
ContainerEvent
FocusEvent
InputEvent
WindowEvent
PaintEvent
MouseEvent
Copyright 2004, Cognizant Academy, All Rights Reserved
KeyEvent
49
Event Listeners
Event Listener
Event Handler Contains different methods to handle different event
50
Event Listeners
Table : Event Listener Interfaces and their methods
Interface
WindowListener
Interface Methods
windowActivated ( WindowEvent ) windowClosed ( WindowEvent ) windowClosing ( WindowEvent ) windowDeactivated ( WindowEvent ) windowDeiconified ( WindowEvent ) windowIconified ( WindowEv actionPerformed ( ActionEvent )
Add Method
addWindiwListener( )
Components
Frame ,
addActionListener( )
adjustmentValueChanged ( AdjustmentEvent ) addAdjustmentListener( ) componentMoved ( ComponentEvent ) componentHidden ( ComponentEvent ) componentResized ( ComponentEvent ) componentShown ( ComponentEvent ) componentAdded ( ContainerEvent ) componentRemoved ( ContainerEvent ) addComponentListener( )
ContainerListener
addContainerListener( )
Frame , Panel
Continued
Copyright 2004, Cognizant Academy, All Rights Reserved 51
Event Listeners
Table : Event Listener Interfaces and their methods
Interface
FocusListener ItemListener KeyListener
Interface Methods
focusGained( FocusEvent ) focusLost( FocusEvent ) itemStateChanged ( ItemEvent ) keyPressed ( KeyEvent ) keyReleased ( KeyEvent ) keyTyped ( KeyEvent ) mouseClicked ( MouseEvent ) mouseEntered ( MouseEvent ) mouseExited ( MouseEvent ) mousePressed ( MouseEvent ) mouseReleased ( MouseEvent ) mouseDragged (MouseEvent ) mouseMoved ( MouseEvent ) textValueChanged ( TextEvent )
Add Method
addFocusListener( ) addItemListener( ) addKeyListener( )
Components
Frame , Button, Canvas Checkbox, Choice, List Button , Canvas, Panel
MouseListener
addMouseListener( )
MouseMotionListener TextListener
addMouseMotionListener( ) addTextListener( )
52
Event Listeners
Adding Listener to component : Method 1
// Test.java import java.awt.*; import java.awt.event.*; public class Test extends Frame{ public static void main(String args[]) { Frame mainFrame =new Test (); myWinList myWL=new myWinList(); mainFrame.setVisible(true); mainFrame.setBounds(10,10,200,200); mainFrame.addWindowListener(myWL); } }
53
Event Listeners
// myWinList class implements WindowListner class myWinList implements WindowListener{ public void windowActivated ( WindowEvent we) {} public void windowClosed ( WindowEvent we) {} public void windowClosing ( WindowEvent we) {System.exit(0);} public void windowDeactivated ( WindowEvent we){} public void windowDeiconified ( WindowEvent we){} public void windowIconified ( WindowEvent we) {} public void windowOpened ( WindowEvent we) {} }
54
Event Listeners
Adding Listener to component : Method 2
// Test.java import java.awt.*; import java.awt.event.*; public class Test extends Frame implements WindowListener{ public static void main(String args[]) { Frame mainFrame =new Test (); myWinList myWL=new myWinList(); mainFrame.setVisible(true); mainFrame.setBounds(10,10,200,200); } Test(){ addWindowListener(this); }
55
Event Listeners
public void windowActivated ( WindowEvent we) {} public void windowClosed ( WindowEvent we) {} public void windowClosing ( WindowEvent we) {System.exit(0);} public void windowDeactivated ( WindowEvent we){} public void windowDeiconified ( WindowEvent we){} public void windowIconified ( WindowEvent we) {} public void windowOpened ( WindowEvent we) {} } // End Test
56
Event Listeners
Example : How to Use ActionListener for Button
import java.awt.*; import java.awt.event.*; public class Test extends Frame { public static void main(String args[]) { Frame mainFrame =new Test (); myAction myA = new myAction(); Button b1=new Button("Button 1"); mainFrame.setVisible(true); mainFrame.setBounds(10,10,200,200); mainFrame.setLayout(null); b1.setBounds(40,100,80,40); b1.addActionListener(myA); mainFrame.add(b1); } //main } //Class Test
57
Event Listeners
class myAction implements ActionListener { public void actionPerformed ( ActionEvent ae){ System.out.println(ae.getActionCommand()); } } //Class myAction
58
Event Adapters
Event Adapters : Empty implementation of Listener interface
Example :
import java.awt.*; import java.awt.event.*; public class Test extends Frame { public static void main(String args[]) { Frame mainFrame =new Test (); myWinAd myWA = new myWinAd (); mainFrame.setVisible(true); mainFrame.setBounds(10,10,200,200); mainFrame.addWindowListener(myWA); } }//Class Test End class myWinAd extends WindowAdapter { public void windowClosing ( WindowEvent we){ } //Class Adapter End
Copyright 2004, Cognizant Academy, All Rights Reserved
System.exit(0); }
59
Event Adapters
Adapter classes and corresponding interfaces
60
Events : Summary
Event is a platform-independent class Event handling is done by using Listeners and Adapters
61
: Quiz
Which are the entities in Event-Delegation model ? What is the use of event listeners ?
62
63
64
CardLayout Manager
GridBagLayout Manager
65
66
Figure 3
68
Figure 1
Figure 2
69
70
mainFrame.setVisible(true);
mainFrame.setBounds(10,10,400,100); mainFrame.setLayout(new GridLayout(0,2)); // Important Line mainFrame.add(new Button("Button 1")); mainFrame.add(new Button("Button 2")); mainFrame.add(new Button("Button 3")); mainFrame.add(new Button("Button 4")); } }
Copyright 2004, Cognizant Academy, All Rights Reserved 71
Figure 3
72
Figure 1
Figure 2
73
74
Figure 3
76
Figure 1
Figure 2
77
Constructors :
public CardLayout() public CardLayout(int horizontalgap, int verticalgap)
Copyright 2004, Cognizant Academy, All Rights Reserved 78
79
2
b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { cardLayout.last(cardPanel); }});
Panel cp_1 = new Panel(); Panel cp_2 = new Panel(); cp1.add(b1); cp1.add(b2); controlPanel.add(cp1); controlPanel.add(cp2); add(controlPanel,BorderLayout.SOUTH); } //Constructor
Continue
Copyright 2004, Cognizant Academy, All Rights Reserved 80
Figure 1
Figure 2
Figure 3
81
GridBagLayout Manager
GridBagLayout Manager
GridBagLayout is the most sophisticated, flexible layout manager This layout manager aligns components by placing them within a grid of cells
82
GridBagLayout Manager
GridBagConstraints
public GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill, Insets insets, int ipadx, int ipady) Parameters:
gridx - The initial gridx value. gridy - The initial gridy value. gridwidth - The initial gridwidth value. gridheight - The initial gridheight value. weightx - The initial weightx value. weighty - The initial weighty value. anchor - The initial anchor value. fill - The initial fill value. insets - The initial insets value. ipadx - The initial ipadx value. ipady - The initial ipady value.
Copyright 2004, Cognizant Academy, All Rights Reserved 83
GridBagLayout Manager
import java.awt.*; import java.awt.event.*;
add(new Button("TopLeft"),c); c.gridx=1; add(new Button("TopCentre"),c); c.gridx=2; add(new Button("TopRight"),c); c.gridx=1; c.gridy=1; add(p1,c); c.gridx=2; add(p2,c); }
public static void main(String args[]) { Frame f=new Frame("CTS"); setLayout(new GridBagLayout()); f.add(new GB()); GridBagConstraints c = new GridBagConstraints(); f.pack(); c.gridx=0; f.setVisible(true); Continue c.gridy=0; } }
Copyright 2004, Cognizant Academy, All Rights Reserved 84
GridBagLayout Manager
Figure 1: Output of previous code Col 0 Row 0 Row 1 Col 1 Col 2
Figure 3: Resized window when weightx and weighty are set to 1.0 -
85
GridBagLayout Manager
Controlling the cell size for a component
How to specify if a component occupies multiple cells ? The gridwidth and gridheight parameters
Example
In the previous example if we modify the code to make panel1 occupy first and second columns, the output will look as The code is like this
c.gridx=0; c.gridy=1; c.gridwidth=2; add(p1,c); c.gridx=2; c.gridwidth=1; add(p2,c);
Col 0 Col 1 Col 2
Row 0
Row 1
86
: Quiz
What is absolute positioning ? Write any 3 Layout Managers ? Which is default layout manager type for panels and applets. Which layout manager by default arranges components horizontally ? Where by default component will get added In BorderLayout ? How many cards at a time are visible while using CardLayout ? Which parameters of GridBagConstraints are used to control cell size for components?
88
89