The Swing components offer rich functionality and enable high-level customisation. The following components are described in this section.
- JLabel
- JTextField
- JButton
- JToggleButton
- JCheckBox
- JRadioButton
- JTabbedPane
- JScrollPane
- JList
- JComboBox
- JTree
- JTable
JLabel
JLabel is Swing’s easiest-to-use component.
JLabel can be used to
display text and/or an icon.
JLabel defines several constructors. Here are three of them:
- JLabel(Icon icon)
- JLabel(String str)
- JLabel(String str, Icon icon, int align)
The align argument specifies the
horizontal alignment of the text and/or icon within the label. 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. An object of type ImageIcon can be passed as an
argument to the Icon parameter of JLabel’s constructor.
Methods in JLabel
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)
Program using JLabel
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame
{
JLabel l;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
l = new JLabel("This is a label!");
add(l);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}
JTextField
JTextField is the simplest and most widely used Swing 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.
Events handled in JTextField
ActionEvent - when the user presses the Enter key
CaretEvent - each time the cursor changes position
Methods in JTextField
setText() - to display text
getText() - to retrieve text from the text field
Program using JTextField
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame
{
JTextField jtf;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
jtf = new JTextField(20);
add(jtf);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}
Swing Buttons
Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and
JRadioButton.
A button
generates an action event when it is pressed.
JButton
The JButton class provides the functionality of a push button. Three of its constructors are shown here:
- JButton(Icon icon)
- JButton(String str)
- JButton(String str, Icon icon)
When the button is pressed, an ActionEvent is generated.
getActionCommand() - used to identify the button pressed when two or more buttons are present.
Program using JButton
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame
{
JButton b;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
b = new JButton("Click Me");
add(b);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}
JToggleButton
A toggle button looks just like
a push button, but it acts differently because it has two states: pushed and released. JToggleButton defines several constructors. The most commonly used one is:
JToggleButton(String str)
JToggleButton generates an action event each time it is pressed.
JToggleButton also generates an item event.
- When a JToggleButton is pressed, it is
selected. When it is popped out, it is deselected.
- To handle ItemEvent, the ItemListener interface is implemented. This interface provides itemStateChanged() method. Inside itemStateChanged( ),
getItem( ) - method can
be used to identify the item selected.
isSelected() - used to check whether an item is selected or not.
Program using JToggleButton
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame
{
JToggleButton b;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
b = new JToggleButton("Click Me");
add(b);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}
Check Boxes
The JCheckBox class provides the functionality of a check box. JCheckBox
defines several constructors. The one used here is
When the user selects or deselects a check box, an ItemEvent is generated.
A call to isSelected( ) determines if the box was selected or cleared. The
getText( ) method gets the text for that check box.
Program using JCheckBox
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame
{
JCheckBox c1;
JCheckBox c2;
JCheckBox c3;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
c1 = new JCheckBox("C");
c2 = new JCheckBox("C++");
c3 = new JCheckBox("Java");
add(c1);
add(c2);
add(c3);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}
Radio Buttons
Radio buttons are a group of mutually exclusive buttons, where only one button can be
selected at any time. They are supported by the JRadioButton class, which extends
JToggleButton. JRadioButton provides several constructors.
JRadioButton(String str)
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)
Methods
getActionCommand() - returns the label of the radio button
isSelected() - used to check whether a radio button is selected
getSource() - used to identify the radio button pressed
Program using JRadioButton
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame
{
JRadioButton r1;
JRadioButton r2;
ButtonGroup bg;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
r1 = new JRadioButton("Male");
r2 = new JRadioButton("Female");
add(r1);
add(r2);
bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}
JTabbedPane
Tabbed panes are very common in the modern GUI. 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 defines three constructors.
JTabbedPane()
JTabbedPane(int tabPlacement)
After creating a TabbedPane object, tabs are added using the following method:
void addTab(String name, Component comp)
The general procedure to use a tabbed pane is outlined here:
- Create an instance of JTabbedPane.
- Add each tab by calling addTab( ).
- Add the tabbed pane to the content pane
Program Using JTabbedPane
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame
{
JCheckBox c1;
JCheckBox c2;
JCheckBox c3;
JRadioButton r1;
JRadioButton r2;
ButtonGroup bg;
JLabel l;
JTextField jtf;
JPanel langs;
JPanel gender;
JPanel name;
JTabbedPane jtp;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
c1 = new JCheckBox("C");
c2 = new JCheckBox("C++");
c3 = new JCheckBox("Java");
langs = new JPanel();
langs.add(c1);
langs.add(c2);
langs.add(c3);
r1 = new JRadioButton("Male");
r2 = new JRadioButton("Female");
bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
gender = new JPanel();
gender.add(r1);
gender.add(r2);
l = new JLabel("Enter Name: ");
jtf = new JTextField(20);
name = new JPanel();
name.add(l);
name.add(jtf);
jtp = new JTabbedPane();
jtp.addTab("Languages", langs);
jtp.addTab("Gender", gender);
jtp.addTab("Name", name);
add(jtp);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}
JScrollPane
JScrollPane is a lightweight container that automatically handles the scrolling of another
component. The component being scrolled can be either an individual component or a group of components. In either case, if the object being scrolled is larger than the viewable area, horizontal
and/or vertical scroll bars are automatically provided.
The viewable area of a scroll pane is called the viewport. It is a window in which the
component being scrolled is displayed. The scroll bars scroll the component through the viewport. A JScrollPane will dynamically add or remove a scroll bar as needed. JScrollPane defines several constructors. The simplest one is hown here:
JScrollPane(Component comp)
Here are the steps to follow to use a scroll pane:
- Create the component to be scrolled.
- Create an instance of JScrollPane, passing to it the object to scroll.
- Add the scroll pane to the content pane
Program using JScrollPane
import javax.swing.*;
public class
JScrollPaneExample
{
public static void main(String[] args)
{
// Create a JFrame
JFrame frame = new
JFrame("JScrollPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
// Create a JTextArea
JTextArea textArea = new JTextArea(10,
30);
textArea.setText("This is a sample
text.
\nYou can add more
lines to see the scroll effect.
\nKeep typing to test
scrolling!");
// Wrap the JTextArea inside a
JScrollPane
JScrollPane scrollPane = new
JScrollPane(textArea);
// Add the JScrollPane to the frame
frame.add(scrollPane);
// Make the frame visible
frame.setVisible(true);
}
}
JList
In Swing, the basic list class is called JList. It supports the selection of one or more items
from a list..
JList provides several constructors. The one used here is
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. It is handled by implementing
ListSelectionListener. This listener specifies only one method, called valueChanged( ),
By default, a JList allows the user to select multiple ranges of items within the list. The method
void setSelectionMode(int mode)
is used to change the selection mode. It must be one of these values defined by
ListSelectionModel:
SINGLE_SELECTION
SINGLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION
Methods to get the selected items
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.
getSelectedValue( )
It returns a reference to the first selected value. If no value has been selected, it returns null.
Program using JList
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame
{
JList<String> jl;
JScrollPane jsp;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
String[] branches = {"CSE", "ECE", "EEE", "IT", "MECH", "CIV"};
jl = new JList<String>(branches);
jsp = new JScrollPane(jl);
jsp.setPreferredSize(new Dimension(120, 80));
add(jsp);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}
JComboBox
A combo box (a combination of a text field and a drop-down list)
A combo box displays one entry, but it will also display a drop-down list that allows a user to select a different entry.
The JComboBox constructor used by the example is shown here:
JComboBox(E[ ] items)
Items can
be dynamically added to the list of choices via the addItem( ) method, shown here:
void addItem(E obj)
JComboBox generates an
action event when the user selects an item from the list.
item event - when the state of selection changes, which occurs
when an item is selected or deselected.
getSelectedItem( ) - to obtain the item selected in the list
Program using JComboBox
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame
{
JComboBox<String> jc;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
String[] branches = {"CSE", "ECE", "EEE", "IT", "MECH", "CIV"};
jc = new JComboBox<String>(branches);
add(jc);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}
Trees
A tree is a component that presents a hierarchical view of data. Trees are implemented in Swing by the
JTree class. A sampling of its constructors is shown here:
- JTree(Object[ ] obj)
- JTree(Vector v)
- JTree(TreeNode tn)
Although JTree is packaged in javax.swing, its support classes and interfaces are
packaged in javax.swing.tree.
JTree relies on two models: TreeModel and TreeSelectionModel.
Events generated
TreeExpansionEvent events occur when a node is expanded or collapsed.
TreeSelectionEvent is generated when the user selects or deselects a node within the tree.
TreeModelEvent is fired when the data or structure of the tree changes.
The listeners for
these events are TreeExpansionListener, TreeSelectionListener, and TreeModelListener,
respectively. The tree event classes and listener interfaces are packaged in javax.swing.event.
Here are the steps to follow to use a tree:
- Create an instance of JTree.
- Create a JScrollPane and specify the tree as the object to be scrolled.
- Add the scroll pane to the content pane.
Program using JTree
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class SimpleJTreeExample {
public static void main(String[] args) {
// Create the root node
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
// Add child nodes
DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");
root.add(child1);
root.add(child2);
// Add sub-child nodes
child1.add(new DefaultMutableTreeNode("Sub-child 1.1"));
child1.add(new DefaultMutableTreeNode("Sub-child 1.2"));
child2.add(new DefaultMutableTreeNode("Sub-child 2.1"));
// Create the JTree
JTree tree = new JTree(root);
// Add the tree to a scroll pane
JScrollPane treeView = new JScrollPane(tree);
// Create a JFrame to display the tree
JFrame frame = new JFrame("Simple JTree Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(treeView);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
JTable
JTable is a component that displays rows and columns of data. It is also possible to select a row, column, or cell within the
table, and to change the data within a cell. JTable has many classes and interfaces associated with it. These are packaged
in javax.swing.table.
JTable supplies several constructors. The one used here 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.
JTable relies on three models.
TableModel - defines those things related to displaying data in a
two-dimensional format
TableColumnModel - defines a table in terms of columns
ListSelectionModel - determines how items are selected in the table
A JTable can generate several different events.
ListSelectionEvent is
generated when the user selects something in the table
TableModelEvent is fired when
that table’s data changes in some way
Here are the steps required to set up a simple JTable that can be used to display data:
Create an instance of JTable.
Create a JScrollPane object, specifying the table as the object to scroll.
Add the scroll pane to the content pane.
Program using JTable
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame
{
JTable jt;
JScrollPane jsp;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
String[] colHeads = {"Student", "JP", "FLAT", "CO"};
String[][] data = { {"Ramesh", "77", "80", "75"},
{"Suresh", "89", "86", "83"},
{"Mahesh", "74", "80", "75"},
{"Dinesh", "78", "80", "75"},
{"Gireesh", "89", "86", "83"},
{"Paramesh", "77", "84", "72"} };
jt = new JTable(data, colHeads);
jsp = new JScrollPane(jt);
jsp.setPreferredSize(new Dimension(450, 100));
add(jsp);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}
No comments:
Post a Comment