0% found this document useful (0 votes)
23 views

Chapter 1

Uploaded by

hi827019
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Chapter 1

Uploaded by

hi827019
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 32

Swing Classes Hierarchy

Difference between Java AWT and Java Swing


Swing

 It is a part of java Foundation Class.


 Swing is a Set of API (API- Set of Classes and Interfaces)
 Swing is Provided to Design Graphical User Interfaces
 Swing is an Extension library to the AWT (Abstract Window Toolkit)
 Swing is Entirely written in Java.
 Swing Supports a Pluggable look and feel and Swing provides more
powerful components.
o Look represent appearance
o feel represent how user can interact with components.
 Java Swing provides platform independent and light-weight
components.
 Swing classes are defined in javax.swing package and its sub-packages.
 It is used to create window based application.
 Further Swing Follows MVC.
 Advanced features such as JTable, JTabbedPane, JScollPane,
JColourChooser etc.
 It is used to create window based application.

JFC (Java Foundation classes) which encompass a group of features for building
Graphical User Interfaces(GUI) and adding rich graphical functionalities and
interactivity to Java applications. Java Swing is a part of Java Foundation
Classes (JFC).

Features of Swing
1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Rich Controls
7. Pluggable Look and Feel
Advantage of JFC
o Its components are pluggable and require few lines of code.
o It retains Java qualities.
o An application that runs flawlessly on one OS runs flawlessly on another OS.
o It offers an open architecture.

3)
Creating a JFrame
There are two ways to create a JFrame Window.
1. By instantiating JFrame class.
2. By extending JFrame class.

1) By instantiating JFrame class.

import javax.swing.*; //importing swing package


import javax.swing.*; //importing swing package
import java.awt.*; //importing awt package
public class First
{
JFrame jf;
public First()
{
jf = new JFrame("MyWindow"); //Creating a JFrame with name MyWindow
JButton btn = new JButton("Say Hello");//Creating a Button named Say Hello
jf.add(btn); //adding button to frame
jf.setLayout(new FlowLayout()); //setting layout using FlowLayout object
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting close operation.
jf.setSize(400, 400); //setting size
jf.setVisible(true); //setting frame visibility
}
public static void main(String[] args)
{
new First();
}
}

OUTPUT
2) By extending JFrame class.

import javax.swing.*; //importing swing package


import java.awt.*; //importing awt package
public class Second extends JFrame
{
public Second()
{
setTitle("MyWindow"); //setting title of frame as MyWindow JLabel lb = new
JLabel("Welcome to My Second Window");
add(lb); //adding label to frame.
setLayout(new FlowLayout()); //setting layout using FlowLayout object.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400); //setting size
setVisible(true); //setting frame visibility
}
public static void main(String[] args)
{
new Second();
}
}

OUTPUT
Useful Methods of Component Class
Method Description

public void add(Component c) Inserts a component on this component.

Sets the size (width and height) of the


public void setSize(int width,int height)
component.

Defines the layout manager for the


public void setLayout(LayoutManager m)
component.

Changes the visibility of the component, by


public void setVisible(boolean status)
default false.

JButton class declaration


Let's see the declaration for javax.swing.JButton class.
1. public class JButton extends AbstractButton implements Access
ible
Commonly used Constructors:

Constructor Description
It creates a button with no text
JButton()
and icon.

It creates a button with the


JButton(String s)
specified text.

It creates a button with the


JButton(Icon i)
specified icon object.

Commonly used Methods of AbstractButton class:

Methods Description

It is used to set specified text on


void setText(String s)
button

It is used to return the text of the


String getText()
button.

It is used to enable or disable the


void setEnabled(boolean b)
button.

It is used to set the specified Icon


void setIcon(Icon b)
on the button.

It is used to get the Icon of the


Icon getIcon()
button.

It is used to set the mnemonic on


void setMnemonic(int a)
the button.

void It is used to add the action


addActionListener(ActionListener a) listener to this object.

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 is used to display a text

import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class testswing extends JFrame
{
testswing()
{
JButton bt1 = new JButton("Yes"); //Creating a Yes Button.
JButton bt2 = new JButton("No"); //Creating a No Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close operation.
setLayout(new FlowLayout()); //setting layout using FlowLayout object
setSize(400, 400); //setting size of Jframe
add(bt1); //adding Yes button to frame.
add(bt2); //adding No button to frame.
setVisible(true);
}
public static void main(String[] args)
{
new testswing();
}
}
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyTextField extends JFrame
{
public MyTextField()
{
JTextField jtf = new JTextField(20); //creating JTextField.
add(jtf); //adding JTextField to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new MyTextField();
}
}

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.

Constructor Description
JJCheckBox() Creates an initially unselected check box button with no
text, no icon.
JChechBox(String s) Creates an initially unselected check box with text
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
It is used to get the AccessibleContext associated
AccessibleContext getAccessibleContext()
with this JCheckBox.
It returns a string representation of this
protected String paramString()
JCheckBox.

import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
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.

Commonly used Constructors:

Constructor Description

Creates an unselected radio button with no


JRadioButton()
text.

Creates an unselected radio button with


JRadioButton(String s)
specified text.

Creates a radio button with the specified


JRadioButton(String s, boolean selected)
text and selected status.

Commonly used Methods:

Methods Description

void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

It is used to set the specified Icon on the


void setIcon(Icon b)
button.

Icon getIcon() It is used to get the Icon of the button.


It is used to set the mnemonic on the
void setMnemonic(int a)
button.

It is used to add the action listener to this


void addActionListener(ActionListener a)
object.

import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");

r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);

}
public static void main(String[] args) {
new RadioButtonExample();
}
}

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.
1. public class JComboBox extends JComponent implements ItemSelectable, ListDataL
istener, ActionListener, Accessible
Commonly used Constructors:

Constructor Description

Creates a JComboBox with a default data


JComboBox()
model.

Creates a JComboBox that contains the


JComboBox(Object[] items)
elements in the specified array.

Creates a JComboBox that contains the


JComboBox(Vector<?> items)
elements in the specified Vector.

Commonly used Methods:

Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

It is used to remove all the items from the


void removeAllItems()
list.

It is used to determine whether the


void setEditable(boolean b)
JComboBox is editable.

void addActionListener(ActionListener a) It is used to add the ActionListener.

void addItemListener(ItemListener i) It is used to add the ItemListener.

import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
import javax.swing.*;
class MenuExample

{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
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);
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();
}}
List layout manager classes in Java. Explain any one with example.
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
6

1) 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
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


 BorderLayout(): creates a border layout but with no gaps between
the components.
 BorderLayout(int hgap, int vgap): creates a border layout with the
given horizontal and vertical gaps between the components.
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");;
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();
}
}

2) Java GridLayout
 The GridLayout is used to arrange the components in rectangular grid. One
component is displayed in each rectangle.
Constructors of GridLayout class
 GridLayout(): creates a grid layout with one column per component
in a row.
 GridLayout(int rows, int columns): creates a grid layout with the
given rows and columns but no gaps between the components.
 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

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();
}
}

3)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
 FlowLayout(): creates a flow layout with centered alignment and a
default 5 unit horizontal and vertical gap.
 FlowLayout(int align): creates a flow layout with the given alignment
and a default 5 unit horizontal and vertical gap.
 FlowLayout(int align, int hgap, int vgap): creates a flow layout with
the given alignment and the given horizontal and vertical gap.

Example of FlowLayout class

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();
}
}
4) CardLayout
For CardLayout, it treats the components as a stack and every time, what you
can see is only one component. That’s why it’s called CardLayout.

To demonstrate how to use CardLayout, three buttons have been constructed.


We can click the button and get the next button, then click it again, getting
the next one. The following code is to show how to achieve this CardLayout.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DemoCard extends JFrame implements ActionListener {


public static CardLayout c1 = new CardLayout(40, 30);
public static Container c;
JButton jb1, jb2, jb3;

public DemoCard() {
c = getContentPane();
c.setLayout(c1);

// Define new buttons


jb1 = new JButton("Button 1");
jb2 = new JButton("Button 2");
jb3 = new JButton("Button 3");
jb1.addActionListener(this);
jb2.addActionListener(this);
jb3.addActionListener(this);
c.add(jb1);
c.add(jb2);
c.add(jb3);
}

public static void main(String[] args) {


// Create and set up a frame window
DemoCard d1 = new DemoCard();
d1.setSize(300, 300);
d1.setVisible(true);
d1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Action listener
public void actionPerformed(ActionEvent e) {
c1.next(c);
}

}
5) GridBagLayout
GridBagLayout is a more flexible layout manager, which allows the
components to be vertical, horizontal, without specifying the components to
be the same size. Each GridLayout object holds a dynamic rectangular grid of
cells. Each component is associated with an instance of GridBagConstraints.
The GridBagConstraints decides where the component to be displayed and
how the component should be positioned.

import java.awt.*;
import javax.swing.*;
public class DemoGridBag
{
public static void main(String args[])
{
JFrame f1=new JFrame("MyFrame");
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
GridBagLayout l = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
JPanel p1 = new JPanel();
p1.setLayout(l);

// Put constraints on different buttons


gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
p1.add(b1, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
p1.add(b2, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
p1.add(b3, gbc);
f1.setLayout(new FlowLayout());
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.add(p1);
f1.setVisible(true);
f1.setSize(800,800);
f1.pack();
}
}

6)SpringLayout
Similar to the name, SpringLayout manages the layout of its children/Spring.
Every child of Spring object controls the vertical or horizontal distance
between the two components edges. In addition, for every child, it has
exactly one set of constraint associated with it.

import java.awt.*;
import javax.swing.*;
public class DemoSpring
{
public static void main(String args[])
{
JFrame f1=new JFrame("Spring Example");
SpringLayout l = new SpringLayout();
JPanel p1=new JPanel();
JLabel label = new JLabel("Label: ");
JTextField text = new JTextField("Text field", 15);
p1.setSize(300,300);

f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1.setLayout(l);
p1.add(label);
p1.add(text);
l.putConstraint(SpringLayout.WEST, label, 5, SpringLayout.WEST, p1);
l.putConstraint(SpringLayout.NORTH, label, 5, SpringLayout.NORTH, p1);
l.putConstraint(SpringLayout.WEST, text, 5, SpringLayout.EAST, label);
l.putConstraint(SpringLayout.NORTH, text, 5, SpringLayout.NORTH, p1);
f1.setVisible(true);
f1.setSize(1000,1000);
f1.add(p1);

}
}

7)GroupLayout
According to its name, GroupLayout manages the layout of hierarchically
groups and places them in different positions. It consists of two type of
groups: sequential and parallel group.
For sequential group arrangement, the components are placed very similar to
BoxLayout or FlowLayout, one after another. The position of each component
is according to the order of the component.
For parallel group arrangement, components are placed on top of each other
at the same place. They can be baseline-, top- or bottom-aligned at vertical,
or left-, right-, center-aligned at horizontal axis.
In the following example, four buttons are created with button 1, 2, 3 are
following the sequential pattern, while button 3, 4 are grouped together.

GroupLayoutExample.java

import java.awt.*;
import javax.swing.*;
public class GroupExample {
public static void main(String[] args) {
JFrame fr= new JFrame("GroupLayoutExample");
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = fr.getContentPane();
GroupLayout gp = new GroupLayout(cp);

cp.setLayout(gp);

JLabel b1 = new JLabel("Click Here");


JButton b2= new JButton("This Button");

gp.setHorizontalGroup(
gp.createSequentialGroup()
.addComponent(b1)
.addGap(10, 20, 100)
.addComponent(b2));
gp.setVerticalGroup(
gp.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(b1)
.addComponent(b2));

fr.pack();
fr.setVisible(true);
}
}

GroupExample
8) BoxLayout

The Java BoxLayout class is used to arrange the components either


vertically or horizontally. For this purpose, the BoxLayout class
provides four constants.
2)Explain event handling in Java.

Event describes the change in state of any object. For Example : Pressing a button,
Entering a character in Textbox, Clicking or Dragging a mouse, etc.

Components of 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 occurs.

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

Event Classes Description Listener


Interface
ActionEvent generated when button is pressed, menu-item is ActionListener
selected ,list item is double clicked

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressed or released and also when it
enters or exit a component
KeyEvent generated when input is received from keyboard KeyListener
ItemEvent generated when check-box or list item is clicked ItemListener

WindowEvent generated when window is activated, WindowListener


deactivated, deiconified, iconified, opened or
closed

FocusEvent generated when component gains or loses FocusListener


keyboard focus

KeyListener Example
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class KeyListenerExample extends JFrame implements KeyListener{
JLabel l;
JTextField tf;
KeyListenerExample(){

l=new JLabel();
l.setBounds(20,50,100,20);
tf=new JTextField();
tf.setBounds(20,80,300, 300);
tf.addKeyListener(this);

add(l);add(tf);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void keyPressed(KeyEvent e) {
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e) {
l.setText("Key Released");
}
public void keyTyped(KeyEvent e) {
l.setText("Key Typed");
}

public static void main(String[] args) {


new KeyListenerExample();
}
}

You might also like