Unit 5
Unit 5
Graphics programming
Java contains support for graphics that enable programmers to visually enhance applications
Java contains many more sophisticated drawing capabilities as part of the Java 2D API
M
O
AWT
C
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in
S.
U
java.
C
Java AWT components are platform-dependent i.e. components are displayed according to the view
FO
of operating system.
TS
AWT is heavyweight i.e. its components are using the resources of OS.The java.awt package
EN
provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice,
D
U
List etc.
ST
CS8392 1
Container
The Container is a component in AWT that can contain another components like buttons, textfields,
labels etc. The classes that extend Container class are known as container such as Frame, Dialog and Panel.
Window
The window is the container that has no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components
like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
M
There are two ways to create a Frame. They are,
O
C
By Instantiating Frame class
S.
U
By extending Frame class
C
Example:
FO
import java.awt.*;
TS
import java.awt.event.*;
class MyLoginWindow extends Frame
EN
{
D
TextField name,pass;
U
Button b1,b2;
ST
MyLoginWindow()
{
setLayout(new FlowLayout());
this.setLayout(null);
Label n=new Label("Name:",Label.CENTER);
Label p=new Label("password:",Label.CENTER);
name=new TextField(20);
pass=new TextField(20);
pass.setEchoChar('#');
b1=new Button("submit");
b2=new Button("cancel");
this.add(n);
this.add(name);
this.add(p);
this.add(pass);
this.add(b1);
this.add(b2);
CS8392 2
n.setBounds(70,90,90,60);
p.setBounds(70,130,90,60);
name.setBounds(200,100,90,20);
pass.setBounds(200,140,90,20);
b1.setBounds(100,260,70,40);
b2.setBounds(180,260,70,40);
}
public static void main(String args[])
{
MyLoginWindow ml=new MyLoginWindow();
ml.setVisible(true);
ml.setSize(400,400);
ml.setTitle("my login window");
}}
Output:
M
O
C
S.
U
C
FO
TS
EN
D
U
ST
Event handling:
Changing the state of an object is known as an event. For example, click on button, dragging mouse
etc. The java.awt.event package provides many event classes and Listener interfaces for event handling.
Event handling has three main components,
Events : An event is a change in state of an object.
Events Source : Event source is an object that generates an event.
Listeners : A listener is an object that listens to the event. A listener gets notified when an
event occur
CS8392 3
How Events are handled ?
A source generates an Event and send it to one or more listeners registered with the source. Once
event is received by the listener, they process the event and then return. Events are supported by a number
of Java packages, like java.util, java.awt and java.awt.event.
Important Event Classes and Interface
M
O
KeyEvent generated when input is received from keyboard KeyListener
C
S.
U
ItemEvent generated when check-box or list item is clicked ItemListener
C
FO
TS
changed
D
U
CS8392 4
FocusEvent generated when component gains or loses keyboard FocusListener
focus
M
{
O
C
// Set of Code
}
S.
U
C
2. Register an instance of the event handler class as a listener on one or more components. For
FO
example:
TS
someComponent.addActionListener(instanceOfMyClass);
EN
3. Include code that implements the methods in listener interface. For example:
D
Mouse Listener
package Listener;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
CS8392 5
public class Mouse implements MouseListener {
TextArea s;
public Mouse()
{
Frame d=new Frame("kkkk");
s=new TextArea("");
d.add(s);
s.addMouseListener(this);
d.setSize(190, 190);
d.show();
}
public void mousePressed(MouseEvent e) {
System.out.println("MousePressed");
M
int a=e.getX();
O
C
int b=e.getY();
System.out.println("X="+a+"Y="+b);
S.
U
C
}
FO
System.out.println("MouseReleased");
EN
}
D
System.out.println("MouseEntered");
}
public void mouseExited(MouseEvent e) {
System.out.println("MouseExited");
}
public void mouseClicked(MouseEvent e) {
System.out.println("MouseClicked");
}
public static void main(String arg[])
{
Mouse a=new Mouse();
CS8392 6
}
}
package Listener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MouseMotionEventDemo extends JPanel implements MouseMotionListener {
MouseMotionEventDemo()
M
{
O
C
JTextArea a=new JTextArea();
a.addMouseMotionListener(this);
S.
U
C
b.add(a);
TS
b.setVisible(true);
EN
}
D
System.out.println("Mouse is Moving");
}
public void mouseDragged(MouseEvent e) {
System.out.println("MouseDragged");
}
public static void main(String arg[])
{
MouseMotionEventDemo a=new MouseMotionEventDemo();
}
}
CS8392 7
KEY LISTENER
package Listener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class KeyEventDemo implements KeyListener
{
public KeyEventDemo()
{
JFrame s=new JFrame("hai");
JTextField typingArea = new JTextField(20);
M
typingArea.addKeyListener(this);
O
C
s.add(typingArea);
s.setVisible(true);
S.
U
C
}
FO
System.out.println("KeyTyped");
EN
}
D
package Listener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class itemlistener implements ItemListener
{
M
public itemlistener()
O
C
{
JFrame s=new JFrame("hai");
S.
U
C
a.addItemListener(this);
TS
s.add(a);
EN
s.setVisible(true);
D
}
U
ST
CS8392 9
Window Listener
package Listener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class window extends JPanel implements WindowListener {
window()
{
JFrame b=new JFrame();
M
b.addWindowListener(this);
O
C
b.setVisible(true);
}
S.
U
C
{
TS
}
D
System.out.println("Window activated");
}
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Window closed");
}
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Window closing");
}
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
CS8392 10
System.out.println("Window deactivated");
}
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Window deiconified");
}
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Window Iconified");
}
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Window opened");
M
}}
O
C
S.
WINDOW FOCUS LISTENER
U
C
FO
package Listener;
TS
import java.awt.event.MouseEvent;
EN
import java.awt.event.MouseMotionListener;
D
import java.awt.event.WindowEvent;
U
ST
import java.awt.event.WindowFocusListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class window1 extends JPanel implements WindowFocusListener {
window1()
{
JFrame b=new JFrame();
b.addWindowFocusListener(this);
b.setVisible(true);
}
CS8392 11
public static void main(String arg[])
{
window1 b=new window1();
}
public void windowGainedFocus(WindowEvent e) {
// TODO Auto-generated method stub
System.out.println("Window gained");
}
public void windowLostFocus(WindowEvent e) {
// TODO Auto-generated method stub
System.out.println("Windowlostfocus");
}}
M
WindowStateListener
O
C
package Listener;
S.
U
C
import java.awt.event.MouseEvent;
FO
import java.awt.event.MouseMotionListener;
TS
import java.awt.event.WindowEvent;
EN
import java.awt.event.WindowStateListener;
D
import javax.swing.JFrame;
U
ST
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class window2 extends JPanel implements WindowStateListener {
window2()
{
JFrame b=new JFrame();
b.addWindowStateListener(this);
b.setVisible(true);
}
public static void main(String arg[])
{
window2 b=new window2();
CS8392 12
}
public void windowStateChanged(WindowEvent e) {
// TODO Auto-generated method stub
System.out.println("State Changed");
}}
ACTION LISTENER
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class A extends JFrame implements ActionListener {
Scientific() {
M
JPanel buttonpanel = new JPanel();
O
C
JButton b1 = new JButton("Hai");
buttonpanel.add(b1);
S.
U
C
b1.addActionListener(this);
FO
}
TS
System.out.println(“Hai button”);
D
}
U
ST
CS8392 13
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
M
ComponentAdapter ComponentListener
O
C
ContainerAdapter ContainerListener
S.
U
C
HierarchyBoundsAdapter HierarchyBoundsListener
FO
TS
import java.awt.*;
D
U
import java.awt.event.*;
ST
M
f.setSize(300,300);
O
C
f.setLayout(null);
f.setVisible(true);
S.
U
C
}
FO
Graphics g=f.getGraphics();
EN
g.setColor(Color.BLUE);
D
g.fillOval(e.getX(),e.getY(),30,30);
U
ST
}
public static void main(String[] args) {
new MouseAdapterExample();
} }
M
O
C
Java KeyAdapter Example
import java.awt.*;
S.
U
C
import java.awt.event.*;
FO
Label l;
EN
TextArea area;
D
Frame f;
U
ST
KeyAdapterExample(){
f=new Frame("Key Adapter");
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
CS8392 16
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public static void main(String[] args) {
new KeyAdapterExample();
} }
M
O
C
S.
U
C
FO
TS
EN
Swing
D
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based
U
ST
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in
java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
CS8392 17
The hierarchy of java swing API is given below
M
O
C
Difference between AWT and Swing S.
U
There are many differences between java awt and swing that are given below.
C
FO
are lightweight.
CS8392 18
Layout management
Java LayoutManagers
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:
AWT Layout Manager Classes
Following is the list of commonly used controls while designing GUI using AWT.
BorderLayout
1 The borderlayout arranges the components to fit in the five regions: east, west,
north, south, and center.
CardLayout
2 The CardLayout object treats each component in the container as a card. Only one
M
card is visible at a time.
O
C
3 FlowLayout S.
The FlowLayout is the default layout. It layout the components in a directional flow.
U
C
FO
4 GridLayout
TS
GridBagLayout
This is the most flexible layout manager class. The object of GridBagLayout aligns
D
5
U
the component vertically, horizontally, or along their baseline without requiring the
ST
GroupLayout
6 The GroupLayout hierarchically groups the components in order to position them in
a Container.
SpringLayout
7 A SpringLayout positions the children of its associated container according to a set
of constraints.
8 BoxLayout
The BoxLayout is used to arrange the components either vertically or horizontally.
ScrollPaneLayout
9 The layout manager used by JScrollPane. JScrollPaneLayout is responsible for nine
components: a viewport, two scrollbars, a row header, a column header, and four
"corner" components.
CS8392 19
Border layout:
Example:
import java.awt.*;
import javax.swing.*;
public class Border {
JFrame f;
Border(){
f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
M
JButton b5=new JButton("CENTER");;
O
C
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
S.
U
C
f.add(b3,BorderLayout.EAST);
FO
f.add(b4,BorderLayout.WEST);
TS
f.add(b5,BorderLayout.CENTER);
EN
f.setSize(300,300);
D
f.setVisible(true);
U
ST
}
public static void main(String[] args) {
new Border();
} }
ScrollPaneLayout:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public class ScrollPaneDemo extends JFrame
CS8392 20
{
public ScrollPaneDemo() {
super("ScrollPane Demo");
ImageIcon img = new ImageIcon("child.png");
JScrollPane png = new JScrollPane(new JLabel(img));
getContentPane().add(png);
setSize(300,250);
setVisible(true);
}
public static void main(String[] args) {
new ScrollPaneDemo();
} }
M
Boxlayout
O
C
import java.awt.*;
import javax.swing.*;
S.
U
C
Button buttons[];
TS
public BoxLayoutExample1 () {
EN
CS8392 21
Group layout:
Example
public class GroupExample
{
public static void main(String[] args)
{
JFrame frame = new JFrame("GroupLayoutExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPanel = frame.getContentPane();
GroupLayout groupLayout = new GroupLayout(contentPanel);
contentPanel.setLayout(groupLayout);
JLabel clickMe = new JLabel("Click Here");
JButton button = new JButton("This Button");
M
groupLayout.setHorizontalGroup(
O
C
groupLayout.createSequentialGroup()
.addComponent(clickMe)
S.
U
C
.addComponent(button));
TS
groupLayout.setVerticalGroup(
EN
groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
D
.addComponent(clickMe)
U
ST
.addComponent(button));
frame.pack();
frame.setVisible(true);
} }}
Swing components:
Text Fields
The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.
Text Areas
The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class
CS8392 22
Buttons
The JButton class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed. It inherits AbstractButton class.
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class SwingFirstExample {
public static void main(String[] args) {
// Creating instance of JFrame
JFrame frame = new JFrame("My First Swing Example");
M
// Setting the width and height of frame
O
C
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
S.
U
C
*/
U
ST
M
*/
O
C
JTextField userText = new JTextField(20);
userText.setBounds(100,20,165,25);
S.
U
C
panel.add(userText);
FO
passwordLabel.setBounds(10,50,80,25);
D
panel.add(passwordLabel);
U
ST
Check Boxes
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits JToggleButton
M
class.
O
Example:
C
import javax.swing.*; S.
U
C
{
TS
CheckBoxExample(){
EN
checkBox1.setBounds(100,100, 50,50);
ST
CS8392 25
}}
Radio Buttons
The JRadioButton class is used to create a radio button. It is used to choose one option from multiple
options. It is widely used in exam systems or quiz. It should be added in ButtonGroup to select one radio
button only.
import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
M
rb1.setBounds(100,50,100,30);
O
C
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
S.
U
C
bg.add(rb1);bg.add(rb2);
TS
b=new JButton("click");
EN
b.setBounds(100,150,80,30);
D
b.addActionListener(this);
U
ST
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female.");
} }
CS8392 26
public static void main(String args[]){
new RadioButtonExample();
}}
Lists
The object of JList class represents a list of text items. The list of text items can be set up so that the
user can choose either one item or multiple items. It inherits JComponent class.
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
M
l1.addElement("Item1");
O
C
l1.addElement("Item2");
l1.addElement("Item3");
S.
U
C
l1.addElement("Item4");
FO
list.setBounds(100,100, 75,75);
EN
f.add(list);
D
f.setSize(400,400);
U
ST
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}}
CS8392 27
Choices (JComboBox)
The object of Choice class is used to show popup menu of choices. Choice selected by user is shown
on the top of a menu. It inherits JComponent class.
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
M
O
ComboBoxExample(){
C
f=new JFrame("ComboBox Example"); S.
U
String country[]={"India","Aus","U.S.A","England","Newzealand"};
C
FO
f.add(cb);
EN
f.setLayout(null);
D
U
f.setSize(400,500);
ST
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
} }
CS8392 28
Output:
Scrollbars
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation
of a scrollbar. It inherits JComponent class.
mport javax.swing.*;
class ScrollBarExample
M
O
{
C
ScrollBarExample(){ S.
U
JFrame f= new JFrame("Scrollbar Example");
C
FO
f.add(s);
EN
f.setSize(400,400);
D
U
f.setLayout(null);
ST
f.setVisible(true);
}
public static void main(String args[])
{
new ScrollBarExample();
}}
CS8392 29
Output:
Windows
The class JWindow is a container that can be displayed but does not have the title bar
Menus
The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
The object of JMenu class is a pull down menu component which is displayed from the menu bar. It
M
inherits the JMenuItem class.
O
C
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must
belong to the JMenuItem or any of its subclass.
S.
U
C
import javax.swing.*;
FO
class MenuExample
TS
{
EN
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
CS8392 30
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}
Output :
M
O
C
S.
U
C
FO
TS
EN
D
U
Dialog Boxes.
ST
The JDialog control represents a top level window with a border and a title used to take some form
of input from the user. It inherits the Dialog class.Unlike JFrame, it doesn't have maximize and minimize
buttons.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
CS8392 31
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false); }}};
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
M
public static void main(String args[])
O
C
{
new DialogExample(); }}
S.
U
C
Output:
FO
TS
EN
D
U
ST
CS8392 32