Unit 6 1
Unit 6 1
Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty string for the title.
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( )
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)
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();
}
}
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.
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
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");
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
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(){
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();
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( ).
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){
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");