Unit 3 Event and GUI Programming (NEP)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

OBJECT ORIENTED PROGRAMMING WITH JAVA

Unit-3
Event and GUI programing

Event Handling in Java


Event
An event can be defined as changing the state of an object or behavior by performing actions. Actions can be a
button click, cursor movement, keypress through keyboard or page scrolling, etc.

The java.awt.event package can be used to provide various event classes.

Classification of Events

• Foreground Events
• Background Events

Types of Events
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events are generated
due to interaction by the user on components in Graphic User Interface (GUI). Interactions are nothing but
clicking on a button, scrolling the scroll bar, cursor moments, etc.

2. Background Events
Events that don’t require interactions of users to generate are known as background events. Examples of these
events are operating system failures/interrupts, operation completion, etc.

Event Handling
It is a mechanism to control the events and to decide what should happen after an event occur. To handle the
events, Java follows the Delegation Event model.

Delegation Event model

• It has Sources and Listeners.

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

Delegation Event Model

• Source: Events are generated from the source. There are various sources like buttons, checkboxes, list,
menu-item, choice, scrollbar, text components, windows, etc., to generate events.
• Listeners: Listeners are used for handling the events generated from the source. Each of these listeners
represents interfaces that are responsible for handling events.

Handling Keyboard Events

When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed ( )
event handler. When the key is released, a KEY_RELEASED event is generated and the keyReleased ( )
handler is executed. If a character is generated by the keystroke, then a KEY_TYPED event is sent and the
keyTyped ( ) handler is invoked. A user interacts with the application by pressing either keys on the
keyboard or by using mouse. A programmer should know which key the user has pressed on the keyboard or
whether the mouse is moved, pressed, or released. These are also called ‘events’. Knowing these events will
enable the programmer to write his code according to the key pressed or mouse event.

KeyListener interface of java.awt.event package helps to know which key is pressed or


Released by the user. It has 3 methods
1. public void keyPressed (KeyEvent ke): This method is called when a key is pressed
on the keyboard. This include any key on the keyboard along with special keys like
function keys, shift, alter, caps lock, home, end etc.
2. public void keyTyped(keyEvent ke) : This method is called when a key is typed on
the keyboard. This is same as keyPressed () method but this method is called when
general keys like A to Z or 1 to 9 etc are typed. It cannot work with special keys.
3. public void keyReleased(KeyEvent ke): this method is called when a key is release.
KeyEvent class has the following methods to know which key is typed by the user.
1. char getKeyChar(): this method returns the key name (or character) related to the key
pressed or released.
2. int getKeyCode(): this method returns an integer number which is the value of the
key presed by the user.

EX: Demonstrate the key event handlers.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="SimpleKey" width=300
height=100>
</applet> */
public class SimpleKey extends Applet implements KeyListener
{
String msg = "";

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

int X = 10, Y = 20; // output coordinates


public void init()
{
addKeyListener(this);
requestFocus(); // request input focus
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y); }
}
Handling Mouse Events
The user may click, release, drag, or move a mouse while interacting with a the application. If the programmer
knows what the user has done, he can write the code according to the mouse events. To trap the mouse events,
MouseListener and MouseMotionListener interfaces of java.awt.event package are use.

MouseListener interface has the following methods.


1. void mouseClicked(MouseEvent me); void MouseClicked this method is invoked when the mouse button has
been clicked(pressed and released) on a component.
2. void mouseEntered(MouseEvent me): this method is invoked when the mouse enters a component.
3. void mouseExited(MouseEvent me): this method is invoked when the mouse exits a component
4. void mousePressed(MouseEvent me): this method is invoked when a mouse button has been pressed on a
component.
5. void mouseRelease(MouseEvent me): this method is invoked when a mouse button has been released on a
component.

MouseMotionListener interface has the following methods.


1. void mouseDragged(MouseEvent me): this method is invoked when a mouse button is
pressed on a component and then dragged.
2. void mouseMoved(MouseEvent me): this method is invoked when a mouse cursor has
been moved onto a component and then dragged.
The MouseEvent class has the following methods
1. int getButton(): this method returns a value representing a mouse button, when it
is clicked it return 1 if left button is clicked, 2 if middle button, and 3 if right
button is clicked.
2. int getX(); this method returns the horizontal x position of the event relative to the

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

source component.
3. int getY(); this method returns the vertical y postion of the event relative to the
source component.
Program to create a text area and display the mouse event when the button on the
mouse is clicked, when mouse is moved, etc. is done by user.
Handling Mouse Events
To handle mouse events, we must implement the MouseListener and the MouseMotion Listener
interfaces.
EX: // Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet implements MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mouseX = 0; // save coordinates
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
public void mouseExited(MouseEvent me)
{
mouseX= 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
public void mousePressed(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{

mouseX = me.getX();
mouseY = me.getY();
msg= "Up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}

Frame and panel


What is the Difference Between Panel and Frame in Java?
The main difference between Panel and Frame in Java is that the Panel is an internal region to a frame or
another panel that helps to group multiple components together while a Frame is a resizable, movable
independent window with a title bar which contains all other components.

What is Panel
Panel is a component that allows placing multiple components on it. It is created using the Panel class. This class
inherits the Container class. Refer the below program.

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

In the above program, f is a Frame object while the panel is a Panel object. The panel object is placed according
to the specified location using setBounds method. The color of the panel is Gray. The b1 is a button object that is
placed according to the specified location. The color of the button is blue. Then, b1 button is added to the panel
and the panel is added to the Frame f1. Finally, the frame f1 is visible with the components.
What is Frame
Frame is a component that works as the main top-level window of the GUI application. It is created using the Frame
class. For any GUI application, the first step is to create a frame. There are two methods to create a frame: by
extending the Frame class or by creating an object of Frame class.

According to the above program (Figure 1), f is a Frame object. Other GUI components are added to it. Finally, the
frame is displayed. The frame is a resizable and a movable window. It has the title bar. The default visibility of a
Frame is hidden. The programmer has to make it visible by using setVisible method and providing the value “true”
to it.

Applet Life Cycle in Java


Applet Life Cycle:

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

Applets are small java programs that are primarily used in internet computing. It can be transported over the
internet from one computer to another and run using the Applet Viewer or any web browser that supports Java.
An applet is like an application program, it can do many things for us. It can perform arithmetic operations,
display graphics, create animation & games, play sounds and accept user input, etc. Every Java applet inherits
a set of default behaviours from the Applet class. As a result, when an applet is loaded, it undergoes a series of
changes in its states. Applet Life Cycle is defined as how the applet created, started, stopped and destroyed
during the entire execution of the application. The methods to execute in the Applet Life Cycle
are init(), start(), stop(), destroy(). The Applet Life Cycle Diagram is given as below:

▪ Born or Initialization State


▪ Running State
▪ Idle State
▪ Dead State
1. Born or Initialization State: Applets enters the initialization state when it is first loaded. It is achieved
by init() method of Applet class. Then applet is born.

o init(): The init() method is the first method to run that initializes the applet. It can be invoked only once at
the time of initialization. The web browser creates the initialized objects, i.e., the web browser (after
checking the security settings) runs the init() method within the applet.

public void init()


{
.............
.............
(Action)
}
2. Running State: Applet enters the running state when the system calls the start() method of Applet class. This
occurs automatically after the applet is initialized.

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

o start(): The start() method contains the actual code of the applet and starts the applet. It is invoked
immediately after the init() method is invoked. Every time the browser is loaded or refreshed, the start()
method is invoked. It is also invoked whenever the applet is maximized, restored, or moving from one tab
to another in the browser. It is in an inactive state until the init() method is invoked.

public void start()


{
.............
.............
(Action)
}
3.Display State
Applet moves to the display state whenever it has to perform some output operations on
the screen. This happens immediately after the applet enters into the running state.
The paint () method is called to accomplish this task. Almost every applet will have a paint () method.
public void paint(Graphics g)
{
// Any shape's code

}
4. Idle State: An applet becomes idle when it is stopped from running. Stopping occurs automatically when we
leave the page containing the currently running applet. This is achieved by calling the stop() method explicitly.

o stop(): The stop() method stops the execution of the applet. The stop () method is invoked whenever the
applet is stopped, minimized, or moving from one tab to another in the browser, the stop() method is
invoked. When we go back to that page, the start() method is invoked again.

public void stop()


{
............
.............
(Action)
}

4.Display state:

5. Dead State: An applet is said to be dead when it is removed from memory. This occurs automatically by
invoking the destroy() method when we want to quit the browser.
public void destroy()
{
.............
.............
(Action)

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

o destroy(): The destroy() method destroys the applet after its work is done. It is invoked when the applet
window is closed or when the tab containing the webpage is closed. It removes the applet object from
memory and is executed only once. We cannot start the applet once it is destroyed.

Layout Manager

What is a LayoutManager and types of LayoutManager in Java?


The Layout managers enable us to control the way in which visual components are arranged in the GUI
forms by determining the size and position of components within the containers.
Types of LayoutManager
• FlowLayout: It arranges the components in a container like the words on a page. It fills the top
line from left to right and top to bottom. The components are arranged in the order as they are
added i.e. first components appears at top left, if the container is not wide enough to display all the
components, it is wrapped around the line. Vertical and horizontal gap between components can be
controlled. The components can be left, center or right aligned.
• BorderLayout: It arranges all the components along the edges or the middle of the container
i.e. top, bottom, right and left edges of the area. The components added to the top or bottom gets
its preferred height, but its width will be the width of the container and also the components added
to the left or right gets its preferred width, but its height will be the remaining height of the
container. The components added to the center gets neither its preferred height or width. It covers
the remaining area of the container.
• GridLayout: It arranges all the components in a grid of equally sized cells, adding them from
the left to right and top to bottom. Only one component can be placed in a cell and each region of
the grid will have the same size. When the container is resized, all cells are automatically resized.
The order of placing the components in a cell is determined as they were added.
Example
import java.awt.*;
import javax.swing.*;
public class LayoutManagerTest extends JFrame {
JPanel flowLayoutPanel1, flowLayoutPanel2, gridLayoutPanel1,
gridLayoutPanel2, gridLayoutPanel3;
JButton one, two, three, four, five, six;
JLabel bottom, lbl1, lbl2, lbl3;
public LayoutManagerTest() {
setTitle("LayoutManager Test");

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

setLayout(new BorderLayout()); // Set BorderLayout for JFrame


flowLayoutPanel1 = new JPanel();
one = new JButton("One");
two = new JButton("Two");
three = new JButton("Three");
flowLayoutPanel1.setLayout(new FlowLayout(FlowLayout.CENTER)); // Set FlowLayout
Manager
flowLayoutPanel1.add(one);
flowLayoutPanel1.add(two);
flowLayoutPanel1.add(three);
flowLayoutPanel2 = new JPanel();
bottom = new JLabel("This is South");
flowLayoutPanel2.setLayout (new FlowLayout(FlowLayout.CENTER)); // Set FlowLayout
Manager
flowLayoutPanel2.add(bottom);
gridLayoutPanel1 = new JPanel();
gridLayoutPanel2 = new JPanel();
gridLayoutPanel3 = new JPanel();
lbl1 = new JLabel("One");
lbl2 = new JLabel("Two");
lbl3 = new JLabel("Three");
four = new JButton("Four");
five = new JButton("Five");
six = new JButton("Six");
gridLayoutPanel2.setLayout(new GridLayout(1, 3, 5, 5)); // Set GridLayout Manager
gridLayoutPanel2.add(lbl1);
gridLayoutPanel2.add(lbl2);
gridLayoutPanel2.add(lbl3);
gridLayoutPanel3.setLayout(new GridLayout(3, 1, 5, 5)); // Set GridLayout Manager
gridLayoutPanel3.add(four);
gridLayoutPanel3.add(five);
gridLayoutPanel3.add(six);
gridLayoutPanel1.setLayout(new GridLayout(2, 1)); // Set GridLayout Manager
gridLayoutPanel1.add(gridLayoutPanel2);

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

gridLayoutPanel1.add(gridLayoutPanel3);
add(flowLayoutPanel1, BorderLayout.NORTH);
add(flowLayoutPanel2, BorderLayout.SOUTH);
add(gridLayoutPanel1, BorderLayout.CENTER);
setSize(400, 325);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new LayoutManagerTest();
}
}
Output

Layout Managers
In Java, Layout Managers is used for arranging the components in order. LayoutMananger is an interface which
implements the classes of the layout manager.

Below are some of the class which are used for the representation of layout manager.

1. java.awt.BorderLayout

2. java.awt.FlowLayout

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

3. java.awt.GridLayout

Border Layout
BorderLayout is used, when we want to arrange the components in five regions. The five regions can be north,
south, east, west and the centre. There are 5 types of constructor in Border Layout. They are as following:

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

Example:

import java.awt.*;

import javax.swing.*;

public class BorderDemo1

JFrame frame;

BorderDemo1()

frame=new JFrame();

JButton box1=new JButton("**NORTH**");;

JButton box2=new JButton("**SOUTH**");;

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

JButton box3=new JButton("**EAST**");;

JButton box4=new JButton("**WEST**");;

JButton box5=new JButton("**CENTER**");;

frame.add(box1,BorderLayout.NORTH);

frame.add(box2,BorderLayout.SOUTH);

frame.add(box3,BorderLayout.EAST);

frame.add(box4,BorderLayout.WEST);

frame.add(box5,BorderLayout.CENTER);

frame.setSize(400,400);

frame.setVisible(true);

public static void main(String[] args)

new BorderDemo1();

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

Grid Layout
Grid Layout is used, when we want to arrange the components in a rectangular grid.

There are 3 types of constructor in Grid Layout. They are as following:

1. GridLayout()

2. GridLayout(int rows, int columns)

3. GridLayout(int rows, int columns, inthgap, int vgap)

Example:

import java.awt.*;

import javax.swing.*;

public class GridDemo1{

JFrame frame1;

GridDemo1(){

frame1=new JFrame();

JButton box1=new JButton("*1*");

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

JButton box2=new JButton("*2*");

JButton box3=new JButton("*3*");

JButton box4=new JButton("*4*");

JButton box5=new JButton("*5*");

JButton box6=new JButton("*6*");

JButton box7=new JButton("*7*");

JButton box8=new JButton("*8*");

JButton box9=new JButton("*9*");

frame1.add(box1);

frame1.add(box2);

frame1.add(box3);

frame1.add(box4);

frame1.add(box5);

frame1.add(box6);

frame1.add(box7);

frame1.add(box8);

frame1.add(box9);

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

frame1.setSize(500,500);

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

frame1.setVisible(true);

public static void main(String[] args) {

new GridDemo1();

Flow Layout
Flow Layout is used, when we want to arrange the components in a sequence one after another.

There are 3 types of constructor in the Flow Layout. They are as following:

1. FlowLayout()

2. FlowLayout(int align)

3. FlowLayout(int align, inthgap, intvgap)

Example:

import java.awt.*;

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

import javax.swing.*;

public class FlowDemo1{

JFrame frame1;

FlowDemo1(){

frame1=new JFrame();

JButton box1=new JButton("1");

JButton box2=new JButton("2");

JButton box3=new JButton("3");

JButton box4=new JButton("4");

JButton box5=new JButton("5");

JButton box6=new JButton("6");

JButton box7=new JButton("7");

JButton box8=new JButton("8");

JButton box9=new JButton("9");

JButton box10=new JButton("10");

frame1.add(box1);

frame1.add(box2);

frame1.add(box3);

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

frame1.add(box4);

frame1.add(box5);

frame1.add(box6);

frame1.add(box7);

frame1.add(box8);

frame1.add(box9);

frame1.add(box10);

frame1.setLayout(new FlowLayout(FlowLayout.LEFT));

frame1.setSize(400,400);

frame1.setVisible(true);

public static void main(String[] args) {

new FlowDemo1();

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

Programming with Java GUI components

Java’s GUI components include labels, text fields, text areas, buttons, pop-up menus, etc. The SWING Toolkit
also includes containers which can include these components. Containers include frames (windows), canvases
(which are used to draw on), and panels (which are used to group components). Panels, buttons, and other
components can be placed either directly in frames or in panels inside the frames.

These GUI components are automatically drawn whenever the window they are in is drawn. Thus we will not
need to explicitly put in commands to draw them..

Actions on these GUI components are handled using Java’s event model. When a user interacts with a
component (clicks on a button, types in a field, chooses from a pop-up menu, etc.), an event is generated by the
component that you interact with. For each component of your program, the programmer is required to designate
one or more objects to “listen” for events from that component. Thus if your program has a button labeled “start”
you must assign one or more objects that will be notified when a user clicks on the button.

1 Buttons:

JButton is a class in package javax.swing that represents buttons on the screen. The most common constructor is:
public JButton(String label);
which, when executed, creates a button with “label” printed on it. Generally the button is large enough to display
label. There is also a parameter less constructor that creates an unlabeled button. Buttons respond to a variety of
messages, but the only one likely to be useful to you is getText(), which returns a String representing the label on
the button.
You add an “ActionListener” to a button with the method:
public void addActionListener(ActionListener listener);

Adding buttons to a JFrame or JPanel


We can add a button to a frame (window) or panel of a frame by sending the message:
myFrame.add(startButton);
Normally we include such code in the constructor for the frame or panel. Hence usually we just write
this.add(startButton) or simply add(startButton).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

public class ButtonDemo extends JFrame {


protected JButton startButton, stopButton;
// Constructor sets features of the frame, creates buttons, adds them to the frame, and
// assigns an object to listen to them
public ButtonDemo() {
super("Button demo"); // set title bar
setSize(400,200); // sets the size of the window
startButton = new JButton("Start"); // create two new buttons w/labels start and stop
stopButton = new JButton("Stop");
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout()); // layout objects from left to right
// until fill up row and then go to next row
contentPane.add(startButton);
contentPane.add(stopButton);
// create an object to listen to both buttons:
ButtonListener myButtonListener = new ButtonListener();
startButton. AddActionListener(myButtonListener);
stopButton.addActionListener(myButtonListener);
}

public static void main(String[] main) {


ButtonDemo app = new ButtonDemo(); // Create an instance of Buttons
app.setVisible(true); // Show it on the screen
}
}
Other GUI components

Labels
A JLabel is a very simple component which contains a string. The constructors are
public JLabel() // creates label with no text
public JLabel(String text) //create label with text
The methods available are
public String getText() // return label text
public void setText(String s) // sets the label text

Text Fields
A JTextField is an area that the user can type one line of text into. It is a good way of getting text
input from the user. The constructors are
public JTextField () // creates text field with no text
public JTextField (int columns)
// create text field with appropriate # of columns
public JTextField (String s) // create text field with s displayed
public JTextField (String s, int columns)
// create text field with s displayed & approp. width

Methods include:
public void setEditable(boolean s)
// if false the TextField is not user editable
public String getText() // return label text

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

public void setText(String s) // sets the label text


Many other methods are also available for this component (see also the documentation for its
superclass,JTextComponent).
When the user types into a text field and then hits the return or enter key, it generates an event
which can be handled by the same kind of ActionListener used with JButtons. Thus in order to
respond to the user’s hitting of the return key while typing in a JTextField, myField, we can write:
public void actionPerformed(ActionEvent evt) {
String contents = myField.getText();
System.out.println("The field contained: "+contents);
}

Text Areas
JTextArea is a class that provides an area to hold multiple lines of text. It is fairly similar to JTextField
except that no special event is generated by hitting the return key.
The constructors are:
public JTextArea(int rows, int columns)
// create text field with appropriate # rows & columns
public JTextArea(String s, int rows, int columns)
// create text field with rows, columns, & displaying s

Methods:
public void setEditable(boolean s)
// if false the text area is not user editable
public String getText() // return text in the text area
public void setText(String s) // sets the text
public void append(String s) // append the text to text in the text area

JComboBox menus
JComboBox provides a pop-up list of items from which the user can make a selection.
The constructor is:
public JComboBox() // create new choice button
The most useful methods are:
public void addItem(Object s) // add s to list of choices
public int getItemCount() // return # choices in list
public Object getItemAt(int index) // return item at index
public Object getSelectedItem() // return selected item
public int getSelectedIndex() // return index of selected
When an object is added to a JComboBox, the results of sending toString() to the combo box is
displayed in the corrresponding menu.
You can also set the combo box so the user can type an element in the combo box rather than
being forced to select an item from the list. This is done by sending the combo box the message
setEditable(true).
When a user selects an item it generates an ActionEvent which can be handled as usual with an
actionPerformed method. One can determine whether the combo box generated the event by sending the event the
getSource() method, just as we did with other components

Check Boxes

The JCheckbox class provides support for check box buttons. You can also put check boxes in menus, using

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

the JCheckBoxMenuItem class. Because JCheckBox and JCheckBoxMenuItem inherit from AbstractButton

Check boxes are similar to radio buttons but their selection model is different, by convention. Any number of
check boxes in a group — none, some, or all — can be selected. A group of radio buttons, on the other hand, can
have only one button selected.

chinButton = new JCheckBox ("Chin");

chinButton.setMnemonic (KeyEvent.VK_C);
chinButton.setSelected (true);

glassesButton = new JCheckBox ("Glasses");


glassesButton.setMnemonic (KeyEvent.VK_G);
glassesButton.setSelected (true);

hairButton = new JCheckBox ("Hair");


hairButton.setMnemonic (KeyEvent.VK_H);
hairButton.setSelected (true);

teethButton = new JCheckBox ("Teeth");


teethButton.setMnemonic (KeyEvent.VK_C);
teethButton.setSelected (true);

//Register a listener for the check boxes.


chinButton.addItemListener (this);
glassesButton.addItemListener (this);
hairButton.addItemListener (this);
teethButton.addItemListener (this);
...

Radio buttons

Radio buttons are groups of buttons in which, by convention, only one button at a time can be selected. The Swing
release supports radio buttons with the JRadioButton and ButtonGroup classes. To put a radio button in
a menu, use the JRadioButtonMenuItem class. Other ways of displaying one-of-many choices are combo
boxes and lists. Radio buttons look similar to check boxes, but, by convention, check boxes place no limits on how
many items can be selected at a time.
Because JRadioButton inherits from AbstractButton, Swing radio buttons have all the usual button
characteristics

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

JRadioButton birdButton = new JRadioButton (birdString);


birdButton.setMnemonic (KeyEvent.VK_B);
birdButton.setActionCommand (birdString);
birdButton.setSelected (true);

JRadioButton catButton = new JRadioButton (catString);


catButton.setMnemonic (KeyEvent.VK_C);
catButton.setActionCommand (catString);

//Group the radio buttons.


ButtonGroup group = new ButtonGroup ();
group.add (birdButton);
group.add (catButton);

//Register a listener for the radio buttons.


birdButton.addActionListener (this);
catButton.addActionListener (this);

Scrollbar

The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI component allows
us to see invisible number of rows and columns .It can be added to top-level container like Frame or a component
like Panel. The Scrollbar class extends the Component class.

AWT Scrollbar Class Declaration


public class Scrollbar extends Component implements Adjustable, Accessible

Scrollbar Class Fields

The fields of java.awt. Image class are as follows:

o static int HORIZONTAL - It is a constant to indicate a horizontal scroll bar.


o static int VERTICAL - It is a constant to indicate a vertical scroll bar.

Menus

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

A menu is a list of buttons each of which have their own corresponding action when selected. Types of menus
include:

• drop-down (or pull-down) - usually associated with an application's menu bar


• popup - associated with any container component (i.e., often accessed via right button click) o
• cascaded - pops up when another menu item is selected (i.e. a sub menu)

DIALOG BOX

A dialog box is: • a separate window that pops up in response to an event occurring in a window. often used to
obtain information from the user (e.g., entering some values such as when filling out a form).

There are various types of commonly used dialog boxes:

1. Message Dialog - displays a message indicating information, errors, warnings etc...

2. Confirmation Dialog - asks a question such as yes/no

3. Input Dialog - asks for some kind of input

4. Option Dialog - asks the user to select some option JAVA has a class called JOptionP

Sliders
The Java JSlider class is used to create the slider. By using JSlider, a user can set value from a specific range.

Introduction to Java Swing


Similar to AWT, swing is also a GUI toolkit that facilitates the creation of highly interactive GUI
applications. However, swing is more flexible and robust when it comes to implementing graphical components
One of the main differences between swing and awt is that swing will always generate similar

type of output irrespective of the underlying platform. AWT on the other hand, is more dependent on the

underlying operating system for generating the graphic components; thus the output may vary from one

platform to another.

Swings can be regarded as more graphically-rich than AWT not only because they provide some entirely

new graphical components (like tabbed window and tree structure) but also due to the fact that they have

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

enhanced some of the conventional AWT components (like buttons with both image and text).

Some of the key swing classes are:

• JApplet: An extension of Applet class, it is the swing's version of applet.

• JFrame: An extension of java.awt.Frame class, it is the swing's version of frame.

● JButton: Helps to realize a push button in swing.

• JTabbedPane: Helps to realize a tabbed pane in swing.

• Jtree: Helps to realize a hierarchical (tree) structure in swing.

• JComboBox: Helps to realize a combo box in swing.

I/O programming

Files

Files can be classified as either text or binary

• Human readable files are text files

• All other files are binary files

Java provides many classes for performing text I/O and binary I/O

Text I/O

• Use the Scanner class for reading text data from a file

• The JVM converts a file specific encoding when to Unicode when reading a character

• Use the PrintWriter class for writing text data to a file

• The JVM converts Unicode to a file specific encoding when writing a

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

Binary I/O

• Binary I/O does not involve encoding or decoding and thus is more efficient than text I/O

• Binary files are independent of the encoding scheme on the host machine

Binary I/O classes

• The abstract InputStream is the root class for reading binary data

• The abstract OutputStream is the root class for writing binary data

The FileInputStream class

• To construct a FileInputStream object, use the following constructors

public FileInputStream(String filename)

public FileInputStream(File file)

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

• A java.io. FileNotFoundException will occur if you attempt to create a FileInputStream with a nonexistent file

The FileOutputStream class

• To construct a FileOutputStream object, use the following constructors

public FileOutputStream(String filename)

public FileOutputStream(File file)

public FileOutputStream(String filename, boolean append)

public FileOutputStream(File file, boolean append)

• If the file does not exist, a new file will be created

• If the file already exists, the first two constructors will delete the current contents in the file

• To retain the current content and append new data into the file, use the last two constructors by passing true to

the append parameter

Binary file I/O classes

• FileInputStream/FileOutputStream are for reading/writing bytes from/to files

• All the methods in FileInputStream and FileOutputStream are inherited from their superclasses

Binary file I/O using FileInputStream and FileOutputStream

public class TestFileStream

public static void main(String[] args) throws IOException

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

try

// Create an output stream to the file

FileOutputStream output = new FileOutputStream("temp.dat");

// Output values to the file

for (int i = 1; i <= 10; i++)

output.write(i);

try

// Create an input stream for the file

FileInputStream input = new FileInputStream("temp.dat");

// Read values from the file

int value;

while ((value = input.read()) != -1)

System.out.print(value + " ");

Input stream classes


Input stream classes that are used to read 8 – bit bytes include a super class known as
InputStream and a number of subclasses for supporting various input-related functions.

The super class InputStream is an abstract class, and therefore we cannot create
instances of this class. Rather, we must use the subclasses that inherit from this class.
The InputStream class defines methods for performing input functions such as

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

• Reading bytes

• Closing streams

• Marking positions in streams

• Skipping ahead in a stream

• Finding the number of bytes in a stream

Method Description
read ( ) Reads a byte from the input stream
Reads an array of bytes into b
read ( byte b [ ] )

read ( byte b [ ], int n, int m ) Reads m bytes into b starting from nth byte

available ( ) Gives number of bytes available in the input

skip ( n ) Skips over n bytes from the input stream

reset ( ) Goes back to the beginning of the stream

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

close ( ) Closes the input

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

Note that the class DataInputStream extends FilterInputStream and implements the interface
DataInput. Therefore, the DataInputStream class implements the methods described in DataInput
in addition to using the methods of InputStream class. The DataInput interface contains the
following methods:

* readShort ( ) * readFloat ( )

* reading ( ) * readUTF ( )

* readLong ( ) * readDouble ( )

* readLine ( ) * readChar ( )

* readBoolean ( )

Output stream classes

Output stream classes are derived from the base class OutputStream. Like InputStream,
the OutputStream is an abstract class and therefore we cannot instantiate it. The several
subclasses of the OutputStream can be used for performing the output operations.

The OutputStream includes methods that are designed to perform the following tasks.

• Writing bytes

• Closing streams

• Flushing streams

Summary of OutputStream Methods

Method Description

write ( ) Writes a byte to the output stream


write ( byte [ ] b ) Writes all bytes in the array b to the output stream

write ( byte b[ ], int, int m ) Writes m bytes from array b starting from nth byte

close ( ) Closes the output stream


flush ( ) Flushes the output stream

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

Shwetha Rani R S 2ND SEM BCA 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

The DataOutputStream, a counterpart of DataInputStream, implements the interface


DataOutput and therefore implements the following methods contained in DataOutput
interfaces.
Object input/output

The ObjectInputStream class of the java.io package can be used to read objects that were

previously written by ObjectOutputStream . It extends the InputStream abstract class

Working of ObjectInputStream

The ObjectInputStream is mainly used to read data written by the ObjectOutputStream.


Basically, the ObjectOutputStream converts Java objects into corresponding streams. This is
known as serialization. Those converted streams can be stored in files or transferred through
networks.
Now, if we need to read those objects, we will use the ObjectInputStream that will convert the
streams back to corresponding objects. This is known as deserialization.

Create an ObjectInputStream

In order to create an object input stream, we must import the java.io.


ObjectInputStream package first. Once we import the package, here is how we can create an input
stream.
In the above example, we have created an object input stream named objStream that is linked with
the file input stream named fileStream.
Now, the objStream can be used to read objects from the file.

// Creates a file input stream linked with the specified file


FileInputStream fileStream = new FileInputStream(String file);

// Creates an object input stream using the file input stream


ObjectInputStream objStream = new ObjectInputStream(fileStream);

SHWETHA RANI R S 1ST BCA Page 33


OBJECT ORIENTED PROGRAMMING WITH JAVA

ObjectOutputStream
An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.
The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can
be accomplished by using a file for the stream.

• Only objects that support the java.io.Serializable interface can be written to streams. The
class of each serializable object is encoded including the class name and signature of the
class, the values of the object’s fields and arrays, and the closure of any other objects
referenced from the initial objects.
• The Java ObjectOutputStream is often used together with a Java ObjectInputStream. The
ObjectOutputStream is used to write the Java objects, and the ObjectInputStream is used to
read the objects again.
Methods

• void close() : Closes the stream.This method must be called to release any resources
associated with the stream.

Syntax :public void close()


throws IOException
RandomAccessFile
RandomAccessFile in Java is a class that allows data to be read from and written to at any
location in the file. In other simple words, RandomAccessFile class allows creating files that can be
used for reading and writing data with random access.

This class is used for reading and writing to random access file. A random access file behaves like
a large array of bytes. There is a cursor implied to the array called file pointer, by moving the cursor
we do the read write operations. If end-of-file is reached before the desired number of byte has been
read than EOFException is thrown. It is a type of IOException.

Declaration :

public class RandomAccessFile


extends Object
implements DataOutput, DataInput, Closeable

Methods of RandomAccessFile Class :

1.read() : java.io.RandomAccessFile.read() reads byte of data from file. The byte is returned as an
integer in the range 0-255

2.read(byte[] b) java.io.RandomAccessFile.read(byte[] b) reads bytes upto b.length from the


buffer.

Syntax :
public int read(byte[] b)
SHWETHA RANI R S 1ST BCA Page 34
OBJECT ORIENTED PROGRAMMING WITH JAVA

readChar() : java.io.RandomAccessFile.readChar() reads a character from the file, start reading


from the File Pointer.

Syntax :
public final char readChar()

SHWETHA RANI R S 1ST BCA Page 35

You might also like