UNIT II
UNIT II
UNIT II
Swing Components
1.1 Swing
1.2 Difference Between Swing & AWT
1.3 Hierarchy of Java Swing Classes
1.4 Swing Components
1.4.1 JApplet class
1.4.2 JLabel Class
1.4.3 JTextField Class
1.4.4 JComboBox Class
1.4.5 JRadioButton Class
1.4.6 JTabbedPane
1.4.7 JScrollPane
1.4.8 Jtree
1.4.9 JProgressBar
1.4.10 JTable
Java Swing
Java Swing 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.
Unlike AWT, Java Swing provides platform-independent & lightweight
components.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify
the development of desktop applications.
The methods of Component class are widely used in java swing that are given
below.
Sr. Method Description
No
1 public void add(Component c) add a component on another
component.
2 public void setSize(int width,int sets size of the component.
height)
3 public void sets the layout manager for the
setLayout(LayoutManager m) component.
4 public void setVisible(boolean b) sets the visibility of the
component. It is by default false.
P a g e 4 | 21
UNIT – II SWINGS
P a g e 5 | 21
UNIT – II SWINGS
Swing Components
1. JApplet class
As we prefer Swing to AWT. Now we can use JApplet that can have all the
controls of swing. The JApplet class extends the Applet class.
Example of EventHandling in JApplet :
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
myapplet.html
<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>
P a g e 6 | 21
UNIT – II SWINGS
2. JLabelClass
The class JLabel can display either text, an image, or both. Label's contents are
aligned by setting the vertical and horizontal alignment in its display area. By
default, labels are vertically centered in their display area. Text-only labels are
leading edge aligned, by default; image-only labels are horizontally centered,
by default.
Class Constructors
Sr. Description
No
1 JLabel()
Creates a JLabel instance with no image and with an empty string for
the title.
2 JLabel(Icon image)
Creates a JLabel instance with the specified image.
3 JLabel(Icon image, int horizontalAlignment)
Creates a JLabel instance with the specified image and horizontal
alignment.
4 JLabel(String text)
Creates a JLabel instance with the specified text.
5 JLabel(String text, Icon icon, int horizontalAlignment)
Creates a JLabel instance with the specified text, image, and
horizontal alignment.
6 JLabel(String text, int horizontalAlignment)
Creates a JLabel instance with the specified text and horizontal
alignment.
P a g e 7 | 21
UNIT – II SWINGS
JLabel Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showLabelDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showLabelDemo(){
headerLabel.setText("Control in action: JLabel");
JLabel label = new JLabel("", JLabel.CENTER);
label.setText("Welcome to TutorialsPoint Swing Tutorial.");
label.setOpaque(true);
label.setBackground(Color.GRAY);
label.setForeground(Color.WHITE);
P a g e 8 | 21
UNIT – II SWINGS
controlPanel.add(label);
mainFrame.setVisible(true);
}
}
3. JTextField Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showTextFieldDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTextFieldDemo(){
headerLabel.setText("Control in action: JTextField");
P a g e 9 | 21
UNIT – II SWINGS
P a g e 10 | 21
UNIT – II SWINGS
4. JComboBox Class
The class JComboBox is a component which combines a button or editable
field and a drop-down list.
Class Constructors
Sr.No. Constructor & Description
JComboBox()
1
Creates a JComboBox with a default data model.
JComboBox(ComboBoxModel aModel)
2 Creates a JComboBox that takes its items from an existing
ComboBoxModel.
JComboBox(Object[] items)
3 Creates a JComboBox that contains the elements in the
specified array.
JComboBox Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showComboboxDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
P a g e 11 | 21
UNIT – II SWINGS
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showComboboxDemo(){
headerLabel.setText("Control in action: JComboBox");
final DefaultComboBoxModel fruitsName = new DefaultComboBoxModel();
fruitsName.addElement("Apple");
fruitsName.addElement("Grapes");
fruitsName.addElement("Mango");
fruitsName.addElement("Peer");
showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "";
if (fruitCombo.getSelectedIndex() != -1) {
data = "Fruits Selected: "
+ fruitCombo.getItemAt
(fruitCombo.getSelectedIndex());
}
statusLabel.setText(data);
}
});
controlPanel.add(fruitListScrollPane);
controlPanel.add(showButton);
mainFrame.setVisible(true);
}
}
5. JRadioButton Class
The class JRadioButton is an implementation of a radio button - an item that
can be selected or deselected, and which displays its state to the user.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
P a g e 12 | 21
UNIT – II SWINGS
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showRadioButtonDemo(){
headerLabel.setText("Control in action: RadioButton");
radApple.setMnemonic(KeyEvent.VK_C);
radMango.setMnemonic(KeyEvent.VK_M);
radPeer.setMnemonic(KeyEvent.VK_P);
radApple.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Apple RadioButton: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
radMango.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Mango RadioButton: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
radPeer.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Peer RadioButton: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
P a g e 13 | 21
UNIT – II SWINGS
group.add(radApple);
group.add(radMango);
group.add(radPeer);
controlPanel.add(radApple);
controlPanel.add(radMango);
controlPanel.add(radPeer);
mainFrame.setVisible(true);
}
}
6. 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
JTabbedPane Example
import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
f.setSize(400,400);
P a g e 14 | 21
UNIT – II SWINGS
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new TabbedPaneExample();
}}
Output :
7. 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.
JScrollPane Example
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
P a g e 15 | 21
UNIT – II SWINGS
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZO
NTAL_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:
8. 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 Example
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
Output:
P a g e 17 | 21
UNIT – II SWINGS
9. JProgressBar
The JProgressBar class is used to display the progress of the task. It inherits
JComponent class.
Constructor Description
P a g e 18 | 21
UNIT – II SWINGS
Method Description
JProgressBar Example
import javax.swing.*;
public class ProgressBarExample extends JFrame{
JProgressBar jb;
int i=0,num=0;
ProgressBarExample(){
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setLayout(null);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{Thread.sleep(150);}catch(Exception e){}
}
}
public static void main(String[] args) {
ProgressBarExample m=new ProgressBarExample();
m.setVisible(true);
P a g e 19 | 21
UNIT – II SWINGS
m.iterate();
}
}
Output :
10. JTable
The JTable class is used to display data in tabular form. It is composed of rows and
columns.
Constructor Description
P a g e 20 | 21
UNIT – II SWINGS
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Output:
MVC Architecture
Swing API architecture follows loosely based MVC architecture in the following
manner.
Model represents component's data.
View represents visual representation of the component's data.
Controller takes the input from the user on the view and reflects the changes in
Component's data.
Swing component has Model as a seperate element, while the View and
Controller part are clubbed in the User Interface elements. Because of which,
Swing has a pluggable look-and-feel architecture.
P a g e 21 | 21