Module-03
Module-03
Study Material
By
Faculty Name:
Mrs. Rajani,Vijayalakshmi B
Designation: Assistant Professor
Semester: VI
Module-3
Introducing Swing: The Origin of Swing, Swing Is Built on AWT, Two Key Swing Features, The MVC
Connection, Components and Containers, The Swing Packages, A Simple Swing Application, Event
Handling, Painting in Swing, Exploring Swing : JLabel and ImageIcon, JTextField,The Swing Buttons-
1. Introducing Swing:
In earlier days of Java AWT classes were used to create Graphical User
Interface(GUI’s).
Now no longer AWT Classes are used to develop GUI.
Today, most programmers use Swing for this purpose because “Swing is a set of classes
that provides more powerful and flexible GUI components than does the AWT”
Earlier to swing, Java programmer uses AWT classes to develop GUI’s but AWT classes
contains limited graphical interface.
This is one of reason that programmer wants to develop different component, that has
more flexible and rich in graphical interface.
Because of the limited graphical interface AWT translate its various visual components
into their corresponding, platform-specific equivalents, or peers. That means look and
feel of the component is decided by platform, not by JAVA.
Because the AWT components use native code resources, they are referred to as
heavyweight.
The usage of native resources of platform led to following problems
Because of variations between operating systems, a component might look, or even act,
differently on different platforms which also threaten the philosophy of java “write once,
run anywhere”.
Second, the look and feel of each component was fixed and could not be (easily)
changed.
The use of heavyweight components caused some frustrating restrictions.
This Restriction and limitation of AWT classes create serious issues for programmer so
SWINGS came into picture.
Introduced in 1997, Swing was included as part of the Java Foundation Classes (JFC).
Java Swing component is completely incorporated in JDK 1.2.
2. SWING is Bulit on AWT
There is one important point to be remembered that Although SWING eliminates
number of limitations of AWT classes, but SWING doesn't replace it.
Swing is built on the foundation of the AWT.
Java is a platform-independent language and runs on any client machine, the GUI look and
feel, owned and delivered by a platform-specific O/S, simply does not affect an application’s GUI
constructed using Swing components.
Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight
component development. For a component to qualify as lightweight, it must not depend on any
non-Java [O/s based) system classes. Swing components have their own view supported by Java’s
look and feel classes.
Pluggable Look and Feel: This feature enable the user to switch the look and feel of Swing
components without restarting an application. The Swing library supports components’ look and
feels that remain the same across all platforms wherever the program runs. The Swing library
provides an API that gives real flexibility in determining the look and feel of the GUI of an
application
Highly customizable – Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane, slider,
colorpicker, and table controls.
Advantages:
Swing components are lightweight and don't rely on peers.
Swing supports a pluggable look and feel.
Swing is built on AWT.
5. Model-View-Controller(MVC)
Containers:
Swing defines two types of containers:
Top-level containers
1. JFrame ,JApplet ,JWindow ,Jdialog
2. These containers do not inherit Jcomponent.
3. They inherit the AWT classes Component and Container.
4. The top-level containers are heavyweight.
5. It must be at the top of a containment hierarchy
6. A top-level container is not contained within any other container.
7. Every containment hierarchy must begin with a top-level container.
8. The one most commonly used for applications is JFrame.
9. The one used for applets is JApplet.
JRootPane manages the other panes and can add a menu bar.
Glass pane: This is the first pane and is very close to the monitor’s screen. Any
components to be displayed in the foreground are attached to this glass pane. To reach
this glass pane we use getGlassPane() method of JFrame class, which return Component
class object
Root Pane: This pane is below the glass pane. Any components to be displayed in the
background are displayed in this frame. To go to the root pane, we can use getRootPane()
method of JFrame class, which returns JRootPane object.
Layered pane: This pane is below the root pane. When we want to take several
components as a group, we attach them in the layered pane. We can reach this pane by
calling getLayeredPane() method of JFrame class which returns JLayeredPane class
object
content pane: to add our components We can reach this pane by calling getcontentPane()
Lightweight containers:
• JPanel
• used to organize and manage groups of related components(it can be contained within
another container. )
• Used to create subgroups of related controls that are contained within an outer container
• Panel JPanel is the simplest container. It provides space in which any other component
can be placed, including other panels.
import javax.swing.*;
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
import javax.swing.*;
JFrame f;
MySwing()
add(b);//adding button on
frame setSize(400,500);
setLayout(null);
setVisible(true);
new MySwing();
Note: We can write the code of swing inside the main(), constructor or any other method
⚫ When swing component do respond to user input and the events are generated by
those interactions.
⚫ Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc.
⚫ The event handling mechanism used by Swing is the same as that used by the AWT.
⚫ In many cases, Swing uses the same events as does the AWT, and these events are
packaged in java.awt.event.
⚫ Events specific to Swing are stored in javax.swing.event.
⚫ Create an Event Listener: Choose the appropriate listener interface for the event you want
to handle. Common listener interfaces include ActionListener, MouseListener,
KeyListener, etc.
⚫ Implement the Listener Interface: Implement the methods of the chosen listener interface
in your class. This involves writing code to respond to the specific event triggered by the
component.
⚫ Register the Listener: Attach the listener to the Swing component using the appropriate
method. For example, if you're using an ActionListener, you would typically use the
addActionListener() method to register the listener with a JButton or JMenuItem.
⚫ Handle the Event: Write the code that should execute when the event occurs. This code is
placed inside the listener's methods. For example, if you're handling a button click event
with an ActionListener, you would write the code inside the actionPerformed() method.
Registration Methods:
• For Button : public void addActionListener(ActionListener a){}
• For MenuItem: public void addActionListener(ActionListener a){}
• For TextField: public void addActionListener(ActionListener a){}
• public void addTextListener(TextListener a){}
• For TextArea public void addTextListener(TextListener a){}
• For Checkbox : public void addItemListener(ItemListener a){}
• For RadioButton: public void addItemListener(ItemListener a){}
• Choice: public void addItemListener(ItemListener a){}
• For List: public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
class EventDemo {
JLabel jlab;
EventDemo() {
JFrame jfrm = new JFrame("An Event Example");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(300, 150);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Alpha was pressed..");
}
});
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Beta was pressed..");
}
});
jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);
jfrm.add(jlab);
jfrm.setVisible(true);
}
import javax.swing.*;
import java.awt.*;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw string
g.drawString("Hello", 40, 40);
// Draw rectangle
g.drawRect(130, 30, 100, 80);
// Fill rectangle
g.fillRect(130, 130, 100, 80);
// Draw oval
g.drawOval(30, 130, 50, 60);
// Fill oval
g.fillOval(130, 130, 50, 60);
// Draw line
g.drawLine(30, 200, 130, 200);
// Draw arc
g.drawArc(30, 250, 80, 80, 90, 180);
// Fill arc
g.fillArc(130, 250, 80, 80, 45, 135);
// Set color
g.setColor(Color.BLUE);
// Set font
g.setFont(new Font("TimesRoman", Font.BOLD, 20));
g.drawString("Swing Drawing Example", 10, 300);
}
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
});
}
}
i) JButton:
• JButton class provides functionality of a button.
• JButton class has 2 constuctors,
1. JButton(Icon ic)
2. JButton(String str)
import javax.swing.*;
class FirstSwing
jf.add(jb);
jf.add(jb1);
jf.setSize(300, 600);
jf.setLayout(null);
jf.setVisible(true);
Output:
package javaapplication4;
import javax.swing.*;
ButtonWithImage1(){
b.setBounds(200,100,200, 100);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new ButtonWithImage1();
} }
Output:
ii) JRadioButton
import javax.swing.*;
import javax.swing.*;
r2.setBounds(50,150,70,30);
bg.add(r1);
bg.add(r2);
f.add(r1);
f.add(r2);
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
Output:
JCheckBox:
• A JCheckBox is the Swing equivalent of the Checkbox component in AWT.
This is sometimes called a ticker box, and is used to represent multiple option selections in a
form.
import javax.swing.*;
class FirstSwing
JCheckBox jb1=new
JCheckBox("Python");
jf.add(jb);
jf.add(jb1);
jf.setSize(300, 600);
jf.setLayout(null);
jf.setVisible(true);
Output:
JComboBox
• At a time only one item can be selected from the item list.
import java.awt.*;
import javax.swing.*;
String Branch[]={"cse","ise","ec","mech"};
jc.setBounds(50,50,80,50);
f.add(jc);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
Output:
JToggleButton:
⚫ A useful variation on the push button is called a toggle button.
⚫ A toggle button looks just like a push button, but it acts differently because it has two
states: pushed and released.
⚫ When you press toggle button first time, it stays pressed(pushed). When you press the
button second time, it will be released(pops up).
⚫ JToggleButton defines several constructors. The one used by the example in this section
is shown here: JToggleButton(String str)
⚫ This creates a toggle button that contains the text passed in str.
⚫ Easiest way to determine the state of the button is by using this method: isSelected( );
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public ToggleButton1() {
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
toggleButton.addActionListener(new ActionListener() {
if (toggleButton.isSelected()) {
statusLabel.setText("Button is selected");
} else {
});
panel.add(toggleButton);
panel.add(statusLabel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
new ToggleButton1();
});
ImageIcon:
• Thus, an object of type ImageIcon can be passed as an argument to the Icon parameter of
JLabel’s constructor.
• ImageIcon(String filename)
import javax.swing.*;
jf.setLayout(null);
f.add(label1);
f.setSize( 300,400);
f.setVisib le(true); } }
c. JPasswordField
• It is a lightweight component that allows the editing of a single line of text where the
view indicates something was typed, but does not show the original characters.
import javax.swing.*;
f.add(namelabel);
f.add( passwordLabel);
f.add(userText);
f.add(passwordText);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
}}
Output:
JScrollpane:
• JScrollPane is a lightweight container that automatically handles the scrolling of another
component
• The component being scrolled can either be an individual component, such as a table, or
a group of components.
• In either case, if the object being scrolled is larger than the viewable area, horizontal
and/or vertical scroll bars are automatically provided, and the component can be scrolled
through the pane.
• In its default behavior, a JScrollPane will dynamically add or remove a scroll bar as
needed. For example, if the component is taller than the viewport, a vertical scroll bar is
added. If the component will completely fit within the viewport, the scroll bars are
removed
import javax.swing.*;
String data[][]={
{"100","CSE","VTU"}
{"101","ISE","VTU"}
{"102","CSE","VTU"}
{"103","ISE","VTU"}
{"105","ISE","VTU"}
{"106","ISE","VTU"}
};
String column[]={"courseID","Branch","University"};
JScrollPane js=new
JScrollPane(jt);
js.setBounds(30,100,300,100);
f.add(js);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
}}
Output:
e. JTabbedpane
• Selecting a tab causes the component associated with that tab to come to the
forefront
• The other two constructors specify the location of the tabs, which can be
along any of the four sides.
• Model-SingleSelectionModel model.
• Tabs -addTab( )
import javax.swing.*;
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JTabbedPaneDemo());
f.setSize(500, 500);
f.setVisible(true);
JTabbedPaneDemo()
makeGUI();
void makeGUI()
add(jtp);}}
public CitiesPanel()
add(b1);
add(b2);
add(b3);
add(b4);
public ColorsPanel()
CheckBox("Red"); add(cb1);
JCheckBox("Green"); add(cb2);
JCheckBox("Blue"); add(cb3);
public FlavorsPanel()
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
Output: