Unit-Iv Swings Notes
Unit-Iv Swings Notes
Syllabus:
Swing – Introduction, limitations of AWT, MVC architecture, components, containers, exploring swing-
JApplet, JFrame and JComponent, Icons and Labels, text fields, buttons – The JButton class, Check
boxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll Panes, Trees, and Tables.
Swings
Introduction:
Swing is a set of classes that provides more powerful and flexible GUI components than does the AWT
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
There are many differences between java awt and swing that are given below
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc.
The solution was Swing. Introduced in 1997, Swing was included as part of the Java Foundation Classes
(JFC). Swing was initially available for use with Java 1.1 as a separate library. However, beginning with
Java 1.2, Swing (and the rest of the JFC) was fully integrated into Java.
Swing components are lightweight. This means that they are written entirely in Java and do not map
directly to platform-specific peers
Swing supports a pluggable look and feel (PLAF). Because each Swing component is rendered by Java
code rather than by native peers, the look and feel of a component is under the control of Swing
In other words, it is possible to “plug in” a new look and feel for any given component without creating
any side effects in the code that uses that component.
Due to the lack of certain component features, the toolkit does not support images on buttons.
MVC
• The way that the component looks when rendered on the screen
In MVC terminology, the model corresponds to the state information associated with the component.
For example, in the case of a check box, the model contains a field that indicates if the box is checked
or unchecked. The view determines how the component is displayed on the screen, including any aspects
of the view that are affected by the current state of the model. The controller determines how the
component reacts to the user.
For example, when the user clicks a check box, the controller reacts by changing the model to reflect
the user’s choice (checked or unchecked). This then results in the view being updated. By separating a
component into a model, a view, and a controller, the specific implementation of each can be changed
without affecting the other two. For instance, different view implementations can render the same
component in different ways without affecting the model or the controller
CMRCET CSE JAVA UNIT-IV PART-II NOTES
->Because containers are components, a container can also hold other containers.
->This enables Swing to define what is called a containment hierarchy at the top of which must be a top-
level container
Components:
-> In general, Swing components are derived from the JComponent class.
All of Swing’s components are represented by classes defined within the package javax.swing
Containers:
The first are top-level containers: JFrame, JApplet, JWindow, and JDialog.
These containers do not inherit JComponent. They do, however, inherit the AWT classes
Component and Container
CMRCET CSE JAVA UNIT-IV PART-II NOTES
Furthermore, every containment hierarchy must begin with a top-level container. The one most
commonly used for applications is JFrame. The one used for applets is JApplet.
The second type of containers supported by Swing are lightweight containers. Lightweight containers
do inherit JComponent. An example of a lightweight container is JPanel, which is a general-purpose
container. Lightweight containers are often used to organize and manage groups of related components
because a lightweight container can be contained within another container.
The Top-Level Container Panes Each top-level container defines a set of panes. At the top of the
hierarchy is an instance of JRootPane. JRootPane is a lightweight container whose purpose is to manage
the other panes
Swing is a very large subsystem and makes use of many packages. These are the packages used by Swing
that are defined by Java SE 6.
The methods of Component class are widely used in java swing that are given below.
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.
We can write the code of swing inside the main(), constructor or any other method.
Let's see a simple swing example where we are creating one button and adding it on the JFrame object
inside the main() method.
File: FirstSwingExample.java
package azam;
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.
File: Simple.java
CMRCET CSE JAVA UNIT-IV PART-II NOTES
We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.
File: Simple2.java
Java JButton
The JButton class is used to create a labeled button that has platform independent implementation. The
application result in some action when the button is pushed. It inherits AbstractButton class.
Constructor Description
Methods Description
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.
Constructor Description
Code:
CMRCET CSE JAVA UNIT-IV PART-II NOTES
package azam;
import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JCheckBox checkbox1 = new JCheckBox("C++");
checkbox1.setBounds(150,100, 50,50);
JCheckBox checkbox2 = new JCheckBox("Java");
checkbox2.setBounds(150,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Output:
CMRCET CSE JAVA UNIT-IV PART-II NOTES
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.
Code:
package azam;
import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
CMRCET CSE JAVA UNIT-IV PART-II NOTES
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female.");
}
}
public static void main(String args[]){
new RadioButtonExample();
}}
Output:
CMRCET CSE JAVA UNIT-IV PART-II NOTES
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.
Constructor Description
Methods Description
CMRCET CSE JAVA UNIT-IV PART-II NOTES
package azam;
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
final JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
f.add(cb); f.add(label); f.add(b);
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "
+ cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Output:
CMRCET CSE JAVA UNIT-IV PART-II NOTES
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.
Constructor Description
Output:
CMRCET CSE JAVA UNIT-IV PART-II NOTES
Java JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we
use a scroll pane to display a large component or a component whose size can change
dynamically.
Constructors
Constructor Purpose
JScrollPane(int, int)
JScrollPane(Component,
int, int)
Useful Methods
void setRowHeaderView(Component) It sets the row header for the scroll pane.
void setCorner(String, Component) It sets or gets the specified corner. The int
parameter specifies which corner and
must be one of the following constants
Component getCorner(String)
defined in ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
CMRCET CSE JAVA UNIT-IV PART-II NOTES
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
JScrollPane Example
Code:
package azam;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
Output:
Java JTree
The JTree class is used to display the tree structured data or hierarchical data. JTree is a complex
component. It has a 'root node' at the top most which is a parent for all nodes in the tree. It
inherits JComponent class.
Constructor Description
JTree(Object[] Creates a JTree with every element of the specified array as the child
CMRCET CSE JAVA UNIT-IV PART-II NOTES
JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which
root) displays the root node.
package azam;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
CMRCET CSE JAVA UNIT-IV PART-II NOTES
Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.
Constructor Description
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
Code:
import javax.swing.*;
CMRCET CSE JAVA UNIT-IV PART-II NOTES
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.
CMRCET CSE JAVA UNIT-IV PART-II NOTES
Constructor Description
Methods Description
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.
Constructor Description
JTextField(String text, int Creates a new TextField initialized with the specified
columns) text and columns.
Methods Description
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}}
Output:
Code:
package test1;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements
ActionListener{
JButton b;
JTextField tf;
CMRCET CSE JAVA UNIT-IV PART-II NOTES
Output:
Java JComponent
The JComponent class is the base class of all Swing components except top-level
containers. Swing components whose names begin with "J" are descendants of the
JComponent class. For example, JButton, JScrollPane, JPanel, JTable etc. But,
JFrame and JDialog don't inherit JComponent class because they are the child of
top-level containers.
The JComponent class extends the Container class which itself extends
CMRCET CSE JAVA UNIT-IV PART-II NOTES
Component. The Container class has support for adding components to the
container.
Fields
Constructor
Constructor Description
Useful Methods
property.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyJComponent extends JComponent {
public void paint(Graphics g) {
g.setColor(Color.green);
g.fillRect(30, 30, 100, 100);
}
}
public class JComponentExample {
public static void main(String[] arguments) {
MyJComponent com = new MyJComponent();
// create a basic JFrame
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JComponent Example");
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the JComponent to main frame
frame.add(com);
frame.setVisible(true);
}
}
Output:
CMRCET CSE JAVA UNIT-IV PART-II NOTES
JApplet - A base class that lets you write code that will run within the context of a
browser, like for an interactive web page. This is cool and all but it brings
limitations which is the price for it playing nice in the real world. Normally
JApplet is used when you want to have your own UI in a web page. I've always
wondered why people don't take advantage of applets to store state for a session so
no database or cookies are needed.
JComponent - A base class for objects which intend to interact with Swing.
JFrame - Used to represent the stuff a window should have. This includes borders
(resizeable y/n?), titlebar (App name or other message), controls
(minimize/maximize allowed?), and event handlers for various system events like
'window close' (permit app to exit yet?).
CMRCET CSE JAVA UNIT-IV PART-II NOTES
JPanel - Generic class used to gather other elements together. This is more
important with working with the visual layout or one of the provided layout
managers e.g. gridbaglayout, etc. For example, you have a textbox that is bigger
then the area you have reserved. Put the textbox in a scrolling pane and put that
pane into a JPanel. Then when you place the JPanel, it will be more manageable in
terms of layout.