Swings 1
Swings 1
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.
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
Methods
Methods Description
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, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.
Methods Description
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(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.
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);
setLayout(null);
setSize(600, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
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));
}
}
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(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.
Methods Description
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(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
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.
JRadioButton(String s, boolean Creates a radio button with the specified text and selected
selected) status.
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
Methods Description
void removeAllItems() It is used to remove all the items from the list.
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(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.
Methods Description
ListModel getModel() It is used to return the data model that holds a list of items
displayed by the JList component.
@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