0% found this document useful (0 votes)
35 views14 pages

Swings 1

The Java Foundation Classes (JFC) include key APIs for building graphical user interfaces (GUIs) in Java applications, including the Abstract Window Toolkit (AWT), Swing, Java 2D, and Applets. Swing is a GUI toolkit that provides a set of widgets for building user interfaces. It is built on top of AWT but is lighter weight and more powerful. Key features of Swing include being platform independent, lightweight components, a pluggable architecture, and following the model-view-controller (MVC) pattern.

Uploaded by

Vishal R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views14 pages

Swings 1

The Java Foundation Classes (JFC) include key APIs for building graphical user interfaces (GUIs) in Java applications, including the Abstract Window Toolkit (AWT), Swing, Java 2D, and Applets. Swing is a GUI toolkit that provides a set of widgets for building user interfaces. It is built on top of AWT but is lighter weight and more powerful. Key features of Swing include being platform independent, lightweight components, a pluggable architecture, and following the model-view-controller (MVC) pattern.

Uploaded by

Vishal R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Swings

Java Foundation Classes


The Java Foundation Classes, or JFC, is a loose collection of standard Java APIs for client-side
graphics, graphical user interfaces (GUIs), and related programming tasks. They are foundation
classes in the sense that most client-side Java applications are built upon these APIs. These
include
 AWT
 Swings
 Java2D
 Applet

Swing in Java is a Graphical User Interface (GUI) toolkit that includes a rich set of widgets. It is
a part of Java Foundation Classes(JFC), which is an API for Java programs that provide GUI.
Swing includes packages that let you make a sophisticated set of GUI components for your Java
applications and it is platform-independent.

The Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older, platform
dependent GUI toolkit.

Features of Swings

1. Platform Independent: It is platform independent, the swing components that are used to
build the program are not platform specific. It can be used at any platform and anywhere.
2. Lightweight: Swing components are lightweight which helps in creating the UI lighter.
Swings component allows it to plug into the operating system user interface framework
that includes the mappings for screens or device and other user interactions like key press
and mouse movements.
3. Plugging: It has a powerful component that can be extended to provide the support for the
user interface that helps in good look and feel to the application. It refers to the highly
modular-based architecture that allows it to plug into other customized implementations
and framework for user interfaces. Its components are imported through a package called
java.swing.
4. Manageable: It is easy to manage and configure. Its mechanism and composition pattern
allows changing the settings at run time as well. The uniform changes can be provided to
the user interface without doing any changes to application code.
5. MVC: They mainly follows the concept of MVC that is Model View Controller. With the
help of this, we can do the changes in one component without impacting or touching
other components. It is known as loosely coupled architecture as well.
6. Customizable: Swing controls can be easily customized. It can be changed and the visual
appearance of the swing component application is independent of its internal
representation.
Difference between AWT and Swings

Window Panes
A Window pane represents a free area of a window where some text or components can
be displayed. For example, we can create a frame using the JFrame class in the
javax.swing package, which contains a free area inside it. This free area is called
'Window pane'.

Glass pane
 The Glass Pane
o The glass pane is very close to the monitors screen. It is useful when you want to
be able to catch events or paint over an area that already contains one or more
components.
o For example, you can deactivate mouse events for a multi-component region by
having the glass pane intercept the events.
o Or you can display an image over multiple components using the glass pane.
 The Root Pane
o The pane below the glass pane. Any components to be displayed in the
background are displayed in root pane.
 The Layered Pane
o A layered pane is a container with depth such that overlapping components can
appear one on top of the other.
o Each root pane places its menu bar and content pane in an instance of
JLayeredPane.
 The content pane
o The container of the root pane's visible components, excluding the menu bar.

Important classes of Swings

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.

Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
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.

Creating a JFrame
o By creating the object of Frame class (association)
o By extending Frame class (inheritance)

import javax.swing.*;
public class swing_example extends JFrame{
swing_example(){
setTitle("Swing Example");
JButton b=new JButton("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]){
swing_example f=new swing_example();
}
}

JButton
Constructors
Constructor Description

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

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

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.

void setIcon(Icon b) It is used to set the specified Icon on the button.

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

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

void addActionListener(ActionListener a) It is used to add the action listener to this object.

//Program to display different types of buttons


package bcaswings;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Button_Example {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 180,20);
JButton b=new JButton("Click Here");
b.setMnemonic('c');//shortcut key alt+c
b.setBounds(50,100,95,30);
ImageIcon icon=new ImageIcon("D:\\Kanchana\\bcaswings\\src\\bcaswings\\tomcat.gif");
JButton b1=new JButton(icon);
b1.setBounds(50,150,100,50);
Border br=BorderFactory.createBevelBorder(BevelBorder.RAISED);
JButton b2=new JButton("Different Border");
b2.setBounds(50,230,95,30);
b2.setBorder(br);
b2.setBackground(Color.YELLOW);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("You have clicked plain button.");
}
});
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("You have clicked image.");
}
});
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("You have clicked border button.");
}
});
f.add(b);
f.add(b1);
f.add(b2);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

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.
Constructor Description

JLabel() Creates a JLabel instance with no image and with an empty string
for the title.

JLabel(String s) Creates a JLabel instance with the specified


text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.

Methods Description

String getText() It returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will
display.

void setHorizontalAlignment(int It sets the alignment of the label's contents along the X
alignment) axis.

Icon getIcon() It returns the graphic image that the label displays.

int getHorizontalAlignment() It returns the alignment of the label's contents along the X
axis.

JTextField
The object of a JTextField class is a text component that allows the editing of a single line text.
Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int columns) Creates a new TextField initialized with the specified text
and columns.

JTextField(int columns) Creates a new empty TextField with the specified number of
columns.

Methods:
1. setColumns(int n) :set the number of columns of the text field.
2. setFont(Font f) : set the font of text displayed in text field.
3. addActionListener(ActionListener l) : set an ActionListener to the text field.
4. int getColumns() :get the number of columns in the textfield.
5. String getText(): It returns the text string that a label displays.
6. void setText(String text): It defines the single line of text this component will display.

/* Program to add two numbers. */

package bcaswings;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Calculate extends JFrame implements ActionListener {

JButton jb1;
JTextField jt1, jt2;
JLabel lbl,l1,l2;

Calculate() {
l1 = new JLabel("Number1 :");
l1.setBounds(20, 50, 150, 30);
add(l1);

jt1 = new JTextField();


jt1.setBounds(90, 50, 150, 30);
add(jt1);
l2 = new JLabel("Number2 :");
l2.setBounds(20, 100, 150, 30);
add(l2);

jt2 = new JTextField();


jt2.setBounds(90, 100, 150, 30);
add(jt2);

lbl = new JLabel("Result :");


lbl.setBounds(90, 140, 150, 30);
add(lbl);

jb1 = new JButton("+");


jb1.setBounds(90, 200, 100, 30);
add(jb1);
jb1.addActionListener(this);

setLayout(null);
setSize(600, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e) {

int a = Integer.parseInt(jt1.getText());
int b = Integer.parseInt(jt2.getText());
int c = 0;

if (e.getSource().equals(jb1)) {
c = a + b;
lbl.setText(String.valueOf(c));
}
}

public static void main(String args[]) {


Calculate t = new Calculate();
}
}

JTextArea

The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text.

Constructor Description

JTextArea() Creates a text area that displays no text initially.

JTextArea(String s) Creates a text area that displays specified text initially.

JTextArea(int row, Creates a text area with the specified number of rows and
int column) columns that displays no text initially.

JTextArea(String s, Creates a text area with the specified number of rows and
int row, int column) columns that displays specified text.

Commonly used Methods:

Methods Description

void setRows(int rows) It is used to set specified number of rows.


void setColumns(int cols) It is used to set specified number of columns.

void setFont(Font f) It is used to set the specified font.

void insert(String s, int It is used to insert the specified text on the specified position.
position)

void append(String s) It is used to append the given text to the end of the document.

JPasswordField

The object of a JPasswordField class is a text component specialized for password entry. It
allows the editing of a single line of text. It inherits JTextField class.

Constructor Description

JPasswordField() Constructs a new JPasswordField, with a default document, null


starting text string, and 0 column width.

JPasswordField(int columns) Constructs a new empty JPasswordField with the specified number of
columns.

JPasswordField(String text) Constructs a new JPasswordField initialized with the specified text.

JPasswordField(String text, int Construct a new JPasswordField initialized with the specified text and
columns) columns.

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 ".

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 Creates a check box with text and specifies whether or
selected) not it is initially selected.

JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.
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.


Constructors:
Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified text.

JRadioButton(String s, boolean Creates a radio button with the specified text and selected
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.

void setIcon(Icon b) It is used to set the specified Icon on the button.

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

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

void addActionListener(ActionListener a) It is used to add the action listener to this object.

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.

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] items) Creates a JComboBox that contains the elements in the


specified array.

JComboBox(Vector<?> items) Creates a JComboBox that contains the 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.

void removeAllItems() It is used to remove all the items from the list.

void setEditable(boolean b) It is used to determine whether the 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.

JList
The object of JList class represents a list of text items. The list of text items can be set up so that
the user can choose either one item or multiple items.
Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the specified
array.

JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified,
non-null, model.

Commonly used Methods:

Methods Description

Void addListSelectionListener ( It is used to add a listener to the list, to be notified each


ListSelectionListener listener) time a change to the selection occurs.

int getSelectedIndex() It is used to return the smallest selected cell index.

ListModel getModel() It is used to return the data model that holds a list of items
displayed by the JList component.

void setListData(Object[] listData) It is used to create a read-only ListModel from an array of


objects.
//program to develop registration form
package bcaswings;
import javax.swing.*;
import java.awt.event.*;
public class swingform extends JFrame implements ActionListener{
JLabel l1,l2,l3,l4,l5,l6;
JTextField t1,t2,t3;
JTextArea ta1,ta2;
JRadioButton r1,r2;
JComboBox c1;
JCheckBox ck;
JButton b;
swingform(){
setTitle("Registration Form");
setSize(800,800);
setLayout(null);
l1=new JLabel("Name ");
l1.setBounds(65, 31, 46, 14);
t1=new JTextField();
t1.setBounds(128, 28, 86, 20);
l2=new JLabel("Phone# ");
l2.setBounds(65, 68, 46, 14);
t2=new JTextField();
t2.setBounds(128, 65, 86, 20);
l3=new JLabel("Email ID");
l3.setBounds(65, 98, 55, 14);
t3=new JTextField();
t3.setBounds(128, 95, 86, 20);
l4=new JLabel("Address ");
l4.setBounds(65, 128, 46, 14);
ta1=new JTextArea();
ta1.setBounds(128, 125, 212, 40);
l5=new JLabel("Gender");
l5.setBounds(65, 178, 46, 14);
ButtonGroup bg=new ButtonGroup();
r1=new JRadioButton("Male");
r1.setBounds(128, 178, 60, 14);
r2=new JRadioButton("Female");
r2.setBounds(198, 178, 80, 14);
bg.add(r1);
bg.add(r2);
l6=new JLabel("Occupation");
l6.setBounds(65, 220, 80, 14);
c1=new JComboBox();
c1.setBounds(150, 220, 100, 25);
c1.addItem("Select");
c1.addItem("Business");
c1.addItem("Engineer");
c1.addItem("Doctor");
c1.addItem("Student");
c1.addItem("Others");
ck=new JCheckBox("I Accept the Terms and Conditions");
ck.setBounds(65, 255, 250, 14);
b=new JButton("Submit");
b.setBounds(100, 300, 80, 30);
b.addActionListener(this);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(l4);
add(ta1);
add(l5);
add(r1);
add(r2);
add(l6);
add(c1);
add(ck);
add(b);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
swingform s=new swingform();
}

@Override
public void actionPerformed(ActionEvent e) {
ta2=new JTextArea();
ta2.setBounds(400,31,300,300);
String str=l1.getText()+" "+t1.getText();
str=str+"\n"+l2.getText()+" "+t2.getText();
str=str+"\n"+l3.getText()+" "+t3.getText();
str=str+"\n"+l4.getText()+" "+ta1.getText();
String gen;
if(r1.isSelected())
gen=r1.getText();
else
gen=r2.getText();
str=str+"\n"+l5.getText()+" "+gen;
str=str+"\n"+l6.getText()+" "+c1.getSelectedItem().toString();
ta2.append(str);
add(ta2);
setVisible(true);
}

}
Assignment Questions
1. What is difference between AWT and Swing?
2. What are the methods of component class in Java Swing?
3. How many ways to create a frame in Java Swing ?
4. How to change a button from enable to disable after click ?
5. Why Swing is called light weight ? explain.
6. Show the code that creates a label displaying the following text, with the italics and
boldface as shown in this screenshot:

7. Write an application called SwingApp1 that has two buttons and one label, arranged as
shown in the following screenshot:

8. Write an application called Helloswing. In which you enter your name in a JTextField,
once you click the add button the name should be inserted to the JList. There is also a
clear button when you click it will clear all the contents of the list box

JList

You might also like