0% found this document useful (0 votes)
16 views

Unit 6 1

The document discusses different Swing components in Java including JLabel, JTextField, JButton, JToggleButton and how to use them. It provides details on their constructors and methods to set text, icons, action listeners and handle user events.

Uploaded by

kafle1292
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Unit 6 1

The document discusses different Swing components in Java including JLabel, JTextField, JButton, JToggleButton and how to use them. It provides details on their constructors and methods to set text, icons, action listeners and handle user events.

Uploaded by

kafle1292
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

Unit 6: Exploring Swing


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 and lightweight components.
The Swing components provide rich functionality and allow a high level of customization.
Some swing components like JLabel, JTextField, JButtons, JToggleButton,
JCheckBox,JComboBox, JRadioButton, JTabbedPane, JList, JComboBox, JTable.
JLabel and ImageIcon
JLabel is Swing’s easiest-to-use component. It creates a label. JLabel can be used to display text
and/or an icon. It is a passive component in that it does not respond to user input. JLabel defines
several constructors

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, Creates a JLabel instance with the specified text, image, and horizontal
int Alignment) alignment. It must be one of the following values: LEFT, RIGHT, CENTER,
LEADING, or TRAILING.

The easiest way to obtain an icon is to use the ImageIcon class. ImageIcon implements Icon and
encapsulates an image. Thus, an object of type ImageIcon can be passed as an argument to the
Icon parameter of JLabel’s constructor.
There are different ImageIcon constructors , two of them are
ImageIcon(String filename)  Creates an ImageIcon from the specified file.
ImageIcon(URL location)  Creates an ImageIcon from the specified URL
The icon and text associated with the label can be obtained by the following methods: Icon getIcon(
) String getText( )

Compiled By: Tara Bahadur Thapa pg. 1


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

The icon and text associated with a label can be set by these methods:
void setIcon(Icon icon)
void setText(String str) Here, icon and str are the icon and text, respectively.
Therefore, using setText( ) it is possible to change the text inside a label during program execution.
//Example:
import javax.swing.*;
public class TestingImageIcon {
JFrame f; JLabel l; ImageIcon ic;
private void makeWindow(){
f = new JFrame("Image Icon Demo");
//create an icon
ic = new ImageIcon("C:\\Users\\HP\\Desktop\\BIM\\img.png");
//create a label having text and Image
l= new JLabel("An Icon",ic,JLabel.RIGHT);
//add the label to frame
f.add(l);
f.setSize(400,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
TestingImageIcon ti= new TestingImageIcon();
ti.makeWindow();
}
}
JTextField
JTextField is the simplest Swing text component. It is also probably its most widely used text
component. JTextField allows you to edit one line of text. It is derived from JTextComponent.
Three of JTextField’s constructors are shown here:
JTextField(int cols)
JTextField(String str, int cols)

Compiled By: Tara Bahadur Thapa pg. 2


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

JTextField(String str)
 Here, str is the string to be initially presented, and cols is the number of columns in the text
field.
 If no string is specified, the text field is initially empty. If the number of columns is not
specified, the text field is sized to fit the specified string
To obtain the text currently in the text field, call getText( )
import java.awt.event.*;
import javax.swing.*;
public class TextFieldExample implements ActionListener {
JFrame f = new JFrame("Example");
JTextField t= new JTextField();
JLabel l = new JLabel();
void makeGui(){
f.setSize(300,300);
f.setVisible(true);
f.setLayout(null);
t.setBounds(20,20,200,20);
t.addActionListener(this);
l.setBounds(20,50,200,20);
f.add(t);f.add(l);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent e){
String s = t.getText();
l.setText(s);
}
public static void main(String[] args) {
TextFieldExample te = new TextFieldExample();
te.makeGui();
}
}

Compiled By: Tara Bahadur Thapa pg. 3


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

The Swing Buttons


Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and JRadioButton. All
are subclasses of the AbstractButton class, which extends JComponent
JButton
 The JButton class provides the functionality of a push button.
 JButton allows an icon, a string, or both to be associated with the push button. Three of its
constructors are shown here:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the button. When the button is pressed, an
ActionEvent is generated. Using the ActionEvent object passed to the actionPerformed( ) method
of the registered ActionListener
You can obtain the action command by calling setActionCommand():This method changes the
action command string, but does not affect the string used to label the button.
getActionCommand(): The action command identifies the button.
Thus, when using two or more buttons within the same application, the action command gives you
an easy way to determine which button was pressed.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonsEx implements ActionListener
{
JFrame f = new JFrame("Buttons with Icons");
JLabel l1 = new JLabel();
JLabel l2= new JLabel();
JButton b1,b2;
void makeWindow()
{
b1=new JButton("Ok");
b1.addActionListener(this);

Compiled By: Tara Bahadur Thapa pg. 4


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

b1.setActionCommand("Ok_button");
b2=new JButton("Click");
b2.setActionCommand("Click_button");
b2.addActionListener(this);
f.setSize(500,500);
f.setVisible(true);
f.setLayout(new GridLayout(2,2,5,5));
f.add(b1);f.add(l1);f.add(b2);f.add(l2);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand()=="Ok_button")
l1.setText("Ok button is Clicked!");
if(e.getActionCommand()=="Click_button")
l2.setText("Click button is Clicked");
}
public static void main(String[] args) {
ButtonsEx bwi = new ButtonsEx();
bwi.makeWindow();
}
}
JToggleButton
 A toggle button looks just like a push button, but it acts differently because it has two states:
pushed and released.
Toggle buttons are objects of the JToggleButton class. JToggleButton implements AbstractButton.
In addition to creating standard toggle buttons, JToggleButton is a superclass for two other Swing
components that also represent two-state controls. These are JCheckBox and JRadioButton.
JToggleButton defines several constructors. One of them is shown here: JToggleButton(String str)
This creates a toggle button that contains the text passed in str. By default, the button is in the off
position.
To handle item events, you must implement the ItemListener interface.

Compiled By: Tara Bahadur Thapa pg. 5


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

 Each time an item event is generated, it is passed to the itemStateChanged( ) method defined by
ItemListener. Inside itemStateChanged( ), the getItem( ) method can be called on the ItemEvent
object to obtain a reference to the JToggleButton instance that generated the event. It is shown
here: Object getItem( ) A reference to the button is returned. You will need to cast this reference
to JToggleButton.
 The easiest way to determine a toggle button’s state is by calling the isSelected( ) method
(inherited from AbstractButton) on the button that generated the event. It is shown here: boolean
isSelected( ) It returns true if the button is selected and false otherwise.
import java.awt.event.*;
import javax.swing.*;
public class ToggleExample implements ItemListener
{
JToggleButton jbt;
JFrame f;
void prepareWindow()
{
f = new JFrame("Toggle Button Demo");
jbt = new JToggleButton("Toggle");
jbt.setBounds(50,50,100,80);
jbt.addItemListener(this);
f.add(jbt);
f.setLayout(null);
f.setSize(300,300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent e)
{
if(jbt.isSelected())
jbt.setText("OFF");
else

Compiled By: Tara Bahadur Thapa pg. 6


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

jbt.setText("ON");
}
public static void main(String[] args) {
ToggleExample te = new ToggleExample();
te.prepareWindow();
}
}
Check Boxes
 The JCheckBox class provides the functionality of a check box. Its immediate superclass is
JToggleButton, which provides support for two-state buttons.
 JCheckBox defines several constructors. The one used here is JCheckBox(String str)
When the user selects or deselects a check box, an ItemEvent is generated. You can obtain a
reference to the JCheckBox that generated the event by calling getItem( ) on the ItemEvent passed
to the itemStateChanged( ) method defined by ItemListener.
 The easiest way to determine the selected state of a check box is to call isSelected( ) on the
JCheckBox instance.
import javax.swing.*;
import java.awt.event.*;
public class CheckBoxEg extends JFrame implements ActionListener
{
JLabel l;
JCheckBox cb1,cb2,cb3;
JButton b;
void makeWindow()
{
setTitle("FOOD Service Nepal");
l=new JLabel("Please choose the food(s) to order");
l.setBounds(50,50,300,20);
cb1=new JCheckBox("Mo:Mo @ Rs.150");
cb1.setBounds(100,100,150,20);
cb2=new JCheckBox("Chow mein @ Rs.130");

Compiled By: Tara Bahadur Thapa pg. 7


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

cb2.setBounds(100,150,150,20);
cb3=new JCheckBox("Tea @ Rs.30");
cb3.setBounds(100,200,150,20);
b=new JButton("Order");
b.setBounds(100,250,80,30);
b.addActionListener(this);
add(l);add(cb1);add(cb2);add(cb3);add(b);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
float amount=0;
String msg="";
if(cb1.isSelected()){
amount+=150;
msg="Mo:Mo : Rs.150\n";
}
if(cb2.isSelected()){
amount+=130;
msg+="Chow mein : Rs.130\n";
}
if(cb3.isSelected()){
amount+=30;
msg+="Tea: Rs.30\n";
}
msg+="-----------------\n";
msg+="\n Total:Rs."+amount;
//to show message in MessageDialog

Compiled By: Tara Bahadur Thapa pg. 8


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

JOptionPane.showMessageDialog(this, msg, "Your Orders",


JOptionPane.OK_CANCEL_OPTION);
}
public static void main(String[] args) {
CheckBoxEg order = new CheckBoxEg();
order.makeWindow();
}
}
Radio Buttons
 Radio buttons are a group of mutually exclusive buttons, in which only one button can be selected
at any one time. They are supported by the JRadioButton class, which extends JToggleButton

In order for their mutually exclusive nature to be activated, radio buttons must be configured into
a group. Only one of the buttons in the group can be selected at any time. A button group is created
by the ButtonGroup class.
Elements are then added to the button group via the following method: void add(AbstractButton
ab) Here, ab is a reference to the button to be added to the group.
import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements
ActionListener{
JRadioButton rb1,rb2, rb3;
JLabel l1,l2;
void manageWindow(){

Compiled By: Tara Bahadur Thapa pg. 9


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

l1 = new JLabel("Please select the Course:");


l1.setBounds(50,40,200,30);
rb1=new JRadioButton("BIM",true);
rb1.setBounds(100,100,100,30);
rb1.setActionCommand("bim");
rb1.addActionListener(this);
rb2=new JRadioButton("Bsc.CSIT");
rb2.setBounds(200,100,100,30);
rb2.setActionCommand("csit");
rb2.addActionListener(this);
rb3=new JRadioButton("BCA");
rb3.setBounds(300,100,100,30);
rb3.setActionCommand("bca");
rb3.addActionListener(this);
//adding buttons to button group
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);bg.add(rb3);
l2 = new JLabel();
l2.setBounds(50,200,300,30);
//adding componennts to frame
add(l1);add(rb1);add(rb2);add(rb3);add(l2);
setTitle("Courses Available");
setSize(500,300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
String s = e.getActionCommand();
l2.setText("You have selected "+s+ " Program");
}

Compiled By: Tara Bahadur Thapa pg. 10


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

public static void main(String args[]){


RadioButtonExample rbe =new RadioButtonExample();
rbe.manageWindow();
}
}
JTabbedPane
JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking them with
tabs. Selecting a tab causes the component associated with that tab to come to the forefront.

JTabbedPane uses the SingleSelectionModel model.


 Tabs are added by calling addTab( ). Here is one of its forms: void addTab(String name,
Component comp) Here, name is the name for the tab, and comp is the component that should be
added to the tab.
 Often, the component added to a tab is a JPanel that contains a group of related components.
This technique allows a tab to hold a set of components.
 The general procedure to use a tabbed pane is outlined here:
1. Create an instance of JTabbedPane.
2. Add each tab by calling addTab( ).
3. Add the tabbed pane to the content pane.
import javax.swing.*;
public class TabbedPaneDemo {
JFrame f;

Compiled By: Tara Bahadur Thapa pg. 11


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

JPanel p1,p2,p3;
JLabel l1,l2,l3;
void makeMyTabbedPane(){
f=new JFrame("TabbedPane Example");
//Creating Panels and adding labels to them
p1=new JPanel();
l1 =new JLabel("Welcome to Dashboard");
p1.add(l1);
p2=new JPanel();
l2 = new JLabel("Your Profile");
p2.add(l2);
p3=new JPanel();
l3 = new JLabel ("Help Section");
p3.add(l3);
//Creating JTabbedPane
JTabbedPane tp=new JTabbedPane();
//setting position
tp.setBounds(50,10,200,200);
//adding components
tp.add("Dashboard",p1);
tp.add("Profile",p2);
tp.add("Help",p3);
//adding TabbedPane to frame
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
TabbedPaneDemo tpd = new TabbedPaneDemo();

Compiled By: Tara Bahadur Thapa pg. 12


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

tpd.makeMyTabbedPane();
}
}
JList
In Swing, the basic list class is called JList. It supports the selection of one or more items from a
list. Although the list often consists of strings, it is possible to create a list of just about any object
that can be displayed.

JList is based on two models. The first is ListModel. This interface defines how access to the list
data is achieved. The second model is the ListSelectionModel interface, which defines methods
that determine what list item or items are selected.
A JList generates a ListSelectionEvent when the user makes or changes a selection. This event is
also generated when the user deselects an item. It is handled by implementing
ListSelectionListener. This listener specifies only one method, called valueChanged( ), which is
shown here: void valueChanged(ListSelectionEvent le)
By default, a JList allows the user to select multiple ranges of items within the list, but you can
change this behavior by calling setSelectionMode( ), which is defined by JList. It is shown here:
void setSelectionMode(int mode) Here, mode specifies the selection mode. It must be one of these
values defined by ListSelectionModel: SINGLE_SELECTION,
MULTIPLE_INTERVAL_SELECTION
You can obtain the index of the first item selected, which will also be the index of the only selected
item when using single-selection mode, by calling getSelectedIndex( ), shown here: int
getSelectedIndex( ) Indexing begins at zero. So, if the first item is selected, this method will return
0. If no item is selected, –1 is returned. Instead of obtaining the index of a selection, you can obtain
the value associated with the selection by calling getSelectedValue( ).

Compiled By: Tara Bahadur Thapa pg. 13


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

import javax.swing.*;
import javax.swing.event.*;
public class JListDemo implements ListSelectionListener{
JFrame f = new JFrame("JList Demo");
JList<String> jlst;
JLabel l;
JScrollPane p;
//creating an array of cities
String Cities[]={"Kathmandu","Pokhara","Hetauda","Birgunj",
"Dharan","Biratnagar","Butwal","Dhangadhi","Nepalgunj",
"Damak","Dharan","Bharatpur","Janakpur","Itahari"};
void makeGUI(){
jlst = new JList<String>(Cities);
//setting the list selection mode
jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//adding the list to scroll pane
p = new JScrollPane(jlst);
//setting size of scroll pane
p.setSize(150, 200);
//making label that displays the selection
l = new JLabel("Choose a city");
//adding selection listener for the list
jlst.addListSelectionListener(this);
//adding scroll pane and label to frame
f.add(p);f.add(l);
f.setSize(400, 500);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//handling list selection event
public void valueChanged(ListSelectionEvent lse){

Compiled By: Tara Bahadur Thapa pg. 14


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

//get the index of the changed item


int idx = jlst.getSelectedIndex();
//display selection if item was selected
if(idx!=-1)
l.setText("Current City : "+Cities[idx]);
else
l.setText("Choose a city");
}
public static void main(String[] args) {
JListDemo jd = new JListDemo();
jd.makeGUI();
}
}
JComboBox
Swing provides a combo box (a combination of a text field and a drop-down list) through the
JComboBox class. A combo box normally displays one entry, but it will also display a drop-down
list that allows a user to select a different entry.

import javax.swing.*;
import java.awt.event.*;
public class JComboBoxExample implements ActionListener{
JFrame f=new JFrame("JComboBox Demo");
JLabel l1 = new JLabel();
JComboBox cb1;
void makeMyWindow(){
JLabel l2 = new JLabel("Select Your Birth Month");

Compiled By: Tara Bahadur Thapa pg. 15


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

l2.setBounds(50, 50, 200, 30);


l1.setBounds(50, 300,200, 20);
//array to store months
String months[]={"January", "February", "March",
"April","May", "June", "July", "August",
"September", "October", "November", "December"};
//comboBox
cb1 =new JComboBox(months);
cb1.setBounds(50, 100,90,20);
cb1.addActionListener(this);
f.add(cb1); f.add(l1); f.add(l2);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae){
String m =(String)cb1.getSelectedItem();
l1.setText("Your Birth Month is "+m);
}
public static void main(String[] args) {
JComboBoxExample cmb= new JComboBoxExample();
cmb.makeMyWindow();
}
}
JTable
JTable is a component that displays rows and columns of data. JTable supplies several
constructors. One of them is: JTable(Object data[ ][ ], Object colHeads[ ]) Here, data is a two-
dimensional array of the information to be presented, and colHeads is a one-dimensional array
with the column headings.
import javax.swing.*;

Compiled By: Tara Bahadur Thapa pg. 16


Unit 6: Exploring Swing Java Programming II BIM 5TH SEMESTER

public class JTableDemo {


JFrame f;
JTableDemo(){
f=new JFrame();
String data[][]={ {"101","Tara","Pokhara"},
{"102","Aabhi","Kathmandu"},
{"103","Ruby","Damauli"},
{"104","Sandhya","Baglung"}
};
String column[]={"Roll No.","Name","Address"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
JTableDemo jt=new JTableDemo();
}
}

Compiled By: Tara Bahadur Thapa pg. 17

You might also like