Chapter 1
Chapter 1
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.
OUTPUT
2) By extending JFrame class.
OUTPUT
Useful Methods of Component Class
Method Description
Constructor Description
It creates a button with no text
JButton()
and icon.
Methods Description
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.
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.
Constructor Description
Methods Description
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
Methods Description
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
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.
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:
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.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public DemoCard() {
c = getContentPane();
c.setLayout(c1);
// 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);
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);
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
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.
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.
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");
}