Java Unit-5
Java Unit-5
Java Unit-5
Adapter Classes
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
Java provides a special feature, called an adapter class, that can simplify the creation of event handlers in certain
situations. An adapter class provides an empty implementation of all methods in an event listener interface.
Adapter classes are useful when you want to receive and process only some of the events that are handled by a
particular event listener interface. You can define a new class to act as an event listener by extending one of the
adapter classes and implementing only those events in which you are interested. For example, the
MouseMotionAdapter class has two methods, mouseDragged( ) and mouseMoved( ), which are the methods
defined by the MouseMotionListener interface. If you were interested in only mouse drag events, then you
could simply extend MouseMotionAdapter and override mouseDragged( ). The empty implementation of
mouseMoved( ) would handle the mouse motion events for you.
The following example demonstrates an adapter. It displays a message in the status bar of an applet viewer or
browser when the mouse is clicked or dragged. However, all other mouse events are silently ignored. The
program has three classes. AdapterDemo extends Applet. Its init( ) method creates an instance of
MyMouseAdapter and registers that object to receive notifications of mouse events. It also creates an instance
of MyMouseMotionAdapter and registers that object to receive notifications of mouse motion events. Both of
the constructors take a reference to the applet as an argument. MyMouseAdapter extends MouseAdapter and
overrides the mouseClicked( ) method. The other mouse events are silently ignored by code inherited from the
MouseAdapter class. MyMouseMotionAdapter extends MouseMotionAdapter and overrides the
mouseDragged( ) method. The other mouse motion event is silently ignored by code inherited from the
MouseMotionAdapter class.
Note that both of the event listener classes save a reference to the applet. This information is provided as an
argument to their constructors and is used later to invoke the showStatus( ) method.
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
1
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}
}
Inner Classes
// Inner class demo.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="InnerClassDemo" width=200 height=100>
</applet>
*/
public class InnerClassDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
}
}
Anonymous Inner Classes
An anonymous inner class is one that is not assigned a name. This section illustrates how an anonymous inner
class can facilitate the writing of event handlers. Consider the applet shown in the following listing. As before,
its goal is to display the string “Mouse Pressed” in the status bar of the applet viewer or browser when the mouse
is pressed.
// Anonymous inner class demo.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="AnonymousInnerClassDemo" width=200 height=100>
</applet>
*/
public class AnonymousInnerClassDemo extends Applet {
public void init() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
2
showStatus("Mouse Pressed");
}
});
}
}
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs
inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the
subclass of Component.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
3
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be
used for drawing oval, rectangle, arc etc.
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file and place the
applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
Note: class must be public because its object is created by Java Plugin software that resides on the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
4
Example:
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
String str;
public void init()
{
Str=”hello”;
}
public void paint(Graphics g)
{
g.drawString(str,150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
Method Description
public void setSize(int width,int height) sets the size (width and height) of the
component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
7
AWT Example by Inheritance
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button
component on the Frame.
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that sets the
position of the awt button.
8
Event and Listener (Java Event Handling)
The Delegation Event Model
The modern approach to handling events is based on the delegation event model, which defines standard and
consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event
and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once an
event is received, the listener processes the event and then returns. The advantage of this design is that the
application logic that processes events is cleanly separated from the user interface logic that generates those
events. A user interface element is able to “delegate” the processing of an event to a separate piece of code.
In the delegation event model, listeners must register with a source in order to receive an event notification. This
provides an important benefit: notifications are sent only to listeners that want to receive them. This is a more
efficient way to handle events than the design used by the old Java 1.0 approach. Previously, an event was
propagated up the containment hierarchy until it was handled by a component. This required components to
receive events that they did not process, and it wasted valuable time. The delegation event model eliminates this
overhead.
Events
In the delegation model, an event is an object that describes a state change in a source. It can be generated as a
consequence of a person interacting with the elements in a graphical user interface. Some of the activities that
cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a
list, and clicking the mouse. Many other
user operations could also be cited as examples. Events may also occur that are not directly caused by
interactions with a user interface. For example, an event may be generated when a timer expires, a counter
exceeds a value, a software or hardware failure occurs, or an operation is completed. You are free to define
events that are appropriate for your application.
Event Sources
Asource is an object that generates an event. This occurs when the internal state of that object changes in some
way. Sources may generate more than one type of event. A source must register listeners in order for the listeners
to receive notifications about
a specific type of event. Each type of event has its own registration method. Here is the general form:
public void addTypeListener(TypeListener el)
Here, Type is the name of the event, and el is a reference to the event listener. For example, the method that
registers a keyboard event listener is called addKeyListener( ). The method that registers a mouse motion
listener is called addMouseMotionListener( ). When an event occurs, all registered listeners are notified and
receive a copy of the event object. This is known as multicasting the event. In all cases, notifications are sent
only to listeners that register to
receive them.
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.
Java Event classes and Listener interfaces
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
9
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
10
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets
the position of the component it may be button, textfield etc.
import java.awt.*;
import java.lang.String;
import java.awt.event.*;
import java.applet.Applet;
public class Fact extends Applet implements ActionListener
{
String str;
Button b0;
TextField t1,t2;
Label l1;
public void init(){
Panel p=new Panel();
p.setLayout(new GridLayout());
add(new Label("Enter any Integer value"));
add(t1=new TextField(20));
add(new Label("Factorial value is: "));
add(t2=new TextField(20));
add(b0=new Button("compute"));
11
b0.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
int i,n,f=1;
n=Integer.parseInt(t1.getText());
for(i=1;i<=n;i++)
f=f*i;
t2.setText(String.valueOf(f));
repaint();
}
}
13
Handling Keyboard Events
To handle keyboard events, you use the same general architecture as that shown in the mouse event example in
the preceding section. The difference, of course, is that you will be implementing the KeyListener interface.
Before looking at an example, it is useful to review how key events are generated. 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. Thus,
each time the user presses a key, at least two and often three events are generated. If all you care about are actual
characters, then you can ignore the information passed by the keypress and release events. However, if your
program needs to handle special keys, such as the arrow or function keys, then it must watch for them through
the keyPressed( ) handler. The following program demonstrates keyboard input. It echoes keystrokes to the
applet window and shows the pressed/released status of each key in the status window.
// 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 = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
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);
}
}
If you want to handle the special keys, such as the arrow or function keys, you need to respond to them within
the keyPressed( ) handler. They are not available through keyTyped( ). To identify the keys, you use their
virtual key codes. For example, the next applet outputs the name of a few of the special keys:
// Demonstrate some virtual key codes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
14
/*
<applet code="KeyEvents" width=300 height=100>
</applet>
*/
public class KeyEvents extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
int key = ke.getKeyCode();
switch(key) {
case KeyEvent.VK_F1:
msg += "<F1>";
break;
case KeyEvent.VK_F2:
msg += "<F2>";
break;
case KeyEvent.VK_F3:
msg += "<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>";
break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
}
repaint();
}
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);
}
15
}
17
Difference between AWT and Swing
There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing
3) AWT doesn't support pluggable look and Swing supports pluggable look and feel.
feel.
18
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop
applications.
public void setLayout(LayoutManager m) sets the layout manager for the component.
19
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
22
Example of displaying image on the button:
import javax.swing.*;
public class ButtonExample{
ButtonExample(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("D:\\icon.png"));
b.setBounds(100,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ButtonExample();
}
}
Output:
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a single line of read
only text. The text can be changed by an application but a user cannot edit it directly. It inherits JComponent
class.
JLabel class declaration
Let's see the declaration for javax.swing.JLabel class.
public class JLabel extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:
Constructor Description
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
23
horizontalAlignment) horizontal alignment.
Methods Description
void setText(String text) It defines the single line of text this component will
display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along
the X axis.
Icon getIcon() It returns the graphic image that the label displays.
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It inherits
JTextComponent class.
JTextField class declaration
Let's see the declaration for javax.swing.JTextField class.
public class JTextField extends JTextComponent implements SwingConstants
Commonly used Constructors:
Constructor Description
JTextField(String text) Creates a new TextField initialized with the specified text.
25
JTextField(String text, int columns) Creates a new TextField initialized with the specified text and
columns.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.
void addActionListener(ActionListener l) It is used to add the specified action listener to receive action
events from this textfield.
Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
26
Java JTextField Example with ActionListener
import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}}
Output:
27
Java JTextArea
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
JTextArea class declaration
Let's see the declaration for javax.swing.JTextArea class.
public class JTextArea extends JTextComponent
Commonly used Constructors:
Constructor Description
JTextArea(int row, int column) Creates a text area with the specified number of rows and columns
that displays no text initially.
JTextArea(String s, int row, int Creates a text area with the specified number of rows and columns
column) that displays specified text.
Methods Description
void insert(String s, int position) It is used to insert the specified text on the specified position.
void append(String s) It is used to append the given text to the end of the document.
29
Java JPasswordField
The object of a JPasswordField class is a text component specialized for password entry. It allows the editing of
a single line of text. It inherits JTextField class.
JPasswordField class declaration
Let's see the declaration for javax.swing.JPasswordField class.
public class JPasswordField extends JTextField
Commonly used Constructors:
Constructor Description
JPasswordField(String text, int Construct a new JPasswordField initialized with the specified
columns) text and columns.
31
setBackground (Color.red);
g.setColor (Color.white);
g.setFont (new Font("Courier New",Font.BOLD,30));
g.drawString ("Hello Readers!", 50, 100);
}
}
class FrameDemo extends JFrame
{
FrameDemo ()
{
Container c = getContentPane ();
MyPanel mp = new MyPanel ();
c.add (mp);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
FrameDemo ob = new FrameDemo ();
ob.setSize (600, 200);
ob.setVisible (true);
}
}
Output:
Java JCheckBox
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 class.
JCheckBox class declaration
Let's see the declaration for javax.swing.JCheckBox class.
public class JCheckBox extends JToggleButton implements Accessible
Commonly used Constructors:
Constructor Description
32
JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether or not it
is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.
Commonly used Methods:
Methods Description
34
l.setBounds(50,50,300,20);
cb1=new JCheckBox("Pizza @ 100");
cb1.setBounds(100,100,150,20);
cb2=new JCheckBox("Burger @ 30");
cb2.setBounds(100,150,150,20);
cb3=new JCheckBox("Tea @ 10");
cb3.setBounds(100,200,150,20);
b=new JButton("Order");
b.setBounds(100,250,80,30);
b.addActionListener(this);
add(l);add(cb1);add(cb2);add(cb3);add(b);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
float amount=0;
String msg="";
if(cb1.isSelected()){
amount+=100;
msg="Pizza: 100\n";
}
if(cb2.isSelected()){
amount+=30;
msg+="Burger: 30\n";
}
if(cb3.isSelected()){
amount+=10;
msg+="Tea: 10\n";
}
msg+="-----------------\n";
JOptionPane.showMessageDialog(this,msg+"Total: "+amount);
}
public static void main(String[] args) {
new CheckBoxExample();
}
}
Output:
35
Java JRadioButton
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.
JRadioButton class declaration
Let's see the declaration for javax.swing.JRadioButton class.
public class JRadioButton extends JToggleButton implements Accessible
Commonly used Constructors:
Constructor Description
JRadioButton(String s, boolean selected) Creates a radio button with the specified text and
selected status.
37
}}
Output:
Java 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.
JComboBox class declaration
Let's see the declaration for javax.swing.JComboBox class.
public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionListener, A
ccessible
Commonly used Constructors:
Constructor Description
void removeAllItems() It is used to remove all the items from the list.
Java JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab with a given title
or icon. It inherits JComponent class.
JTabbedPane class declaration
Let's see the declaration for javax.swing.JTabbedPane class.
public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstants
Commonly used Constructors:
Constructor Description
Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or off.
Nested Classes
Modifier and Class Description
Type
JToggleButton(Icon icon, boolean selected) It creates a toggle button with the specified image
and selection state, but no text.
JToggleButton(String text, boolean selected) It creates a toggle button with the specified text and
41
selection state.
JToggleButton(String text, Icon icon) It creates a toggle button that has the specified text
and image, and that is initially unselected.
JToggleButton(String text, Icon icon, boolean It creates a toggle button with the specified text,
selected) image, and selection state.
Methods
Modifier and Type Method Description
String getUIClassID() It returns a string that specifies the name of the l&f
class that renders this component.
JToggleButton Example
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
public class JToggleButtonExample extends JFrame implements ItemListener {
public static void main(String[] args) {
new JToggleButtonExample();
}
private JToggleButton button;
JToggleButtonExample() {
setTitle("JToggleButton with ItemListener Example");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setJToggleButton() {
button = new JToggleButton("ON");
add(button);
}
private void setAction() {
button.addItemListener(this);
}
42
public void itemStateChanged(ItemEvent eve) {
if (button.isSelected())
button.setText("OFF");
else
button.setText("ON");
}
}
Output
Java JScrollBar
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation of a
scrollbar. It inherits JComponent class.
JScrollBar class declaration
Let's see the declaration for javax.swing.JScrollBar class.
public class JScrollBar extends JComponent implements Adjustable, Accessible
Commonly used Constructors:
Constructor Description
JScrollBar(int orientation, int value, int extent, int Creates a scrollbar with the specified
min, int max) orientation, value, extent, minimum, and
maximum.
44
Java JList
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.
JList class declaration
Let's see the declaration for javax.swing.JList class.
public class JList extends JComponent implements Scrollable, Accessible
Commonly used Constructors:
Constructor Description
JList(ary[] listData) Creates a JList that displays the elements in the specified
array.
JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified, non-
null, model.
JTable:
JTable represents data in the form of a table. The table can have rows of data, and column headings.
To create a JTable: JTable tab = new JTable (data, column_names); Here, data and column_names
can be a 2D array or both can be vector of vectors.
To create a row using a vector: Vector row = new Vector();
row.add(object); //here object represents a column row.add (object);
row.add (object);
To create a table heading, we use getTableHeader () method of JTable class.
JTableHeader head = tab.getTableHeader ();
JMenu Class:
A menu represents a group of items or options for the user to select. To create a menu, the following steps should
be used:
Create a menu bar using JMenuBar class object: JMenuBar mb = new JMenuBar ();
Attach this member to the container. c.add (mb);
Create separate menu to attach to the menubar. JMenu file = new JMenu ("File");
Note: Here, "File" is title for the menu which appear in the menubar.
Attach this menu to the menubar. mb.add (file);
Create menuitems using JMenuItem or JCheckBoxMenuItem or JRadioButtonMenuItem classes.
JMenuItem op = new JMenuITem ("Open");
Attach this menuitem to the menu. file.add (op);
Creating a submenu:
o Create a menu: JMenu font = new JMenu ("Font");
Here, font represents a submenu to be attached to a menu.
o Now attach it to a menu: file.add (font);
o Attach menuitems to the font submenu. font.add (obj);
Note: obj can be a JMenuItem or JCheckBoxMenuItem or JRadioButtonMenuItem
Ex: Write a program to create a menu with several menu items. //Menu Creation
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MyMenu extends JFrame implements ActionListener
{
JMenuBar mb;
JMenu file, edit, font;
JMenuItem op, cl, cp, pt;
JCheckBoxMenuItem pr;
MyMenu ()
{
Container c = getContentPane ();
c.setLayout (new BorderLayout ());
mb = new JMenuBar ();
c.add ("North", mb);
//create file, edit menus
file = new JMenu ("File");
49
edit = new JMenu ("Edit");
//add menus to mb
mb.add (file);
mb.add (edit);
//create menuitems
op = new JMenuItem ("Open");
cl = new JMenuItem ("Close");
cp = new JMenuItem ("Copy");
pt = new JMenuItem ("Paste");
//add menu items to menus
file.add (op);
file.add (cl);
file.add (cp);
file.add (pt);
//disable close
cl.setEnabled (false);
//create checkbox menu item
pr = new JCheckBoxMenuItem ("Print");
//add checkbox menu item to file menu
file.add (pr);
//display line (separator)
file.addSeparator ();
//create submenu
font = new JMenu ("Font");
//add this submenu in file
file.add (font);
//add menu items to font
font.add ("Arial");
font.add ("Times New Roman");
//add action listeners to menu items
op.addActionListener (this);
cl.addActionListener (this);
cp.addActionListener (this);
pt.addActionListener (this);
pr.addActionListener (this);
//close the frame
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
if (op.isArmed())
System.out.println ("Open is selected");
if (cl.isArmed())
System.out.println ("Close is selected");
if (cp.isArmed())
System.out.println ("Copy is selected");
if (pt.isArmed())
System.out.println ("Paste is selected");
if (pr.isArmed())
System.out.println ("Print is selected");
50
}
public static void main (String args[])
{
MyMenu ob = new MyMenu ();
ob.setSize (600,450);
ob.setVisible (true);
}
}
Output:
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:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each
region (area) may contain one component only. It is the default layout of frame or window. The BorderLayout
provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
51
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
between the components.
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");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each
rectangle.
Constructors of GridLayout class
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps
between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and
columns alongwith given horizontal and vertical gaps.
Example of GridLayout class
52
import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout
of applet or panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical
gap.
53
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal
and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given
horizontal and vertical gap.
import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
} }
Java CardLayout
The CardLayout class manages the components in such a manner that only one component is visible at a time. It
treats each component as a card that is why it is known as CardLayout.
Constructors of CardLayout class
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.
Commonly used methods of CardLayout class
o public void next(Container parent): is used to flip to the next card of the given container.
o public void previous(Container parent): is used to flip to the previous card of the given container.
o public void first(Container parent): is used to flip to the first card of the given container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card with the given
name.
55
Modifier and Type Field Description
56
object.
protected getLayoutInfo(Container parent, int sizeflag) This method is obsolete and supplied
GridBagLay for backwards compatibility.
outInfo
57
protected GetMinSize(Container parent, This method is obsolete and supplied
Dimension GridBagLayoutInfo info) for backwards compatibility only
Example
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
58
Example 2
public class GridBagLayoutDemo {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}
button = new JButton("Button 1");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Button 2");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Button 3");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 2;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Long-Named Button 4");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; //make this component tall
59
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
pane.add(button, c);
button = new JButton("5");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0; //reset to default
c.weighty = 1.0; //request any extra vertical space
c.anchor = GridBagConstraints.PAGE_END; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.gridx = 1; //aligned with button 2
c.gridwidth = 2; //2 columns wide
c.gridy = 2; //third row
pane.add(button, c);
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Output:
Dialog Boxes
Often, you will want to use a dialog box to hold a set of related controls. Dialog boxes are primarily used to
obtain user input and are often child windows of a top-level window. Dialog boxes don’t have menu bars, but in
other respects, they function like frame windows. (You can add controls to them, for example, in the same way
that you add controls to a frame window.) Dialog boxes may be modal or modeless. When a modal dialog box is
active, all input is directed to it until it is closed. This means that you cannot access other parts of your program
until you have closed the dialog box. When a modeless dialog box is active, input focus can be directed to
another window in your program. Thus, other parts of your program remain active and accessible. Dialog boxes
are of type Dialog. Two commonly used constructors are shown here:
Dialog(Frame parentWindow, boolean mode)
Dialog(Frame parentWindow, String title, boolean mode)
Here, parentWindow is the owner of the dialog box. If mode is true, the dialog box is modal.
Otherwise, it is modeless. The title of the dialog box can be passed in title. Generally, you
will subclass Dialog, adding the functionality required by your application.
60