Chapter 10 Swings
Chapter 10 Swings
10 SWINGS
Swing is a set of packages that are built on top of AWT which provides a large number of inbuilt
predefined classes. Swing is a part of Java Foundation Class (JFC). Swing class provides a large set of
components such as toolbars, progressbar, text fields and timers. Swings provide a large set of builtin
controls such as trees, image buttons, sliders, tabbed panes, toolbars, tables, color choosers etc. Swing
is customizable that helps in changing certain properties such as text alignment, adding images,
changing borders or separating the internal appearance from visual appearance. Swing provides
several UI components of which, few are listed below:
JApplet: It is an extended version of java.applet.
JButton: A push or command button.
JCheckBox: A checkbox can be selected or deselected displaying its state.
JColorChooser: It allows a user to select a color.
JComboBox: It is a combination of text field and dropdown list.
JComponent: It is the base class for Swing components.
JDialog: It is the base class for creating a dialog window.
JEditorPane: It is a text component that allows the user to edit various kinds of content.
JFrame: It is an extension to java.awt.Frame
JLabel: It is a display area for a short text string.
JList: It is a component that allows a user to select one or more objects from a list.
JMenu: A popup menu containing JMenuItem object’s that are displayed when the user
selects it in the JMenuBar component.
JOptionPane: Makes it easy to pop up a standard dialog box.
JPanel: A generic lightweight container.
JPasswordField: It allows the editing of a line of text where the user views some special
characters in place of original characters.
JPopupMenu: It provides a popup menu.
JProgressBar: It is a component that displays an integer value within an interval.
JRadioButton: A radio button can be selected or deselected displaying its state.
JScrollBar: It gives an implementation of the scrollbar.
JSeparator: It provides a menu separator.
JSlider: It is a component that lets the user select a value by sliding a knob.
JTable: It presents the data in a twodimensional format.
JTextArea: It provides a multiline area that displays plain text.
JTextField: It allows the editing of a single line of text.
JTextPane: It is a text component that can be marked up with attributes.
JToolBar: It displays the toolbar that is used for displaying commonly used controls.
JTree: It displays a set of hierarchical data as an outline.
JViewport: It provides a viewport through which the user can see the information.
JWindow: It provides a window that can be displayed anywhere on the desktop.
Besides the above listed UI components, Swings in Java provide other features also:
1. Borders: The users can draw borders in various different styles and patterns around the
components using setBorder method.
2. Graphics Debugging: The users can use the setDebuggingGraphicsOptions method to set up
graphics debugging.
3. Mouseless Operations: Swings make it much easier to connect keystrokes to components.
4. Tooltips: The users can use the setToolTipText method of JComponent.
5. Scrolling: Swings overcome an important drawback of AWT, that is, it allows scrolling to
various components.
6. Pluggable look: The users can set the appearance of applets and applications to any of the
standard looks.
7. New layout managers: Swing introduces new layout managers like BoxLayout and
OverlayLayout.
10.1 Lists
Lists are supported in Swings by the JList class. It is a very popular control as it allows the user to
present a list of items in an easier and efficient manner. It also allows hiding the long list of items by
making the lists scrollable. JList has been inherited from a long list of classes. The inheritance diagram
for JList is as follows:
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JList
Figure 1: Inheritance Diagram for JList
The table below shows the constructors of the JList class:
Table 1. Constructors of JList
Constructor Function
JList() Constructs a JList object
JList(ListModel dataModel) Constructs a JList object that displays the
elements in the indicated data model
JList(Object[ ] listData) Constructs a JList object that displays the
elements in the indicated array
JList(Vector listData Constructs a JList object that displays the
elements in the indicated vector
The simple example for creating a list using Swings that displays 15 items and reports which ones the
user clicks is illustrated below.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
/*<APPLET code=list1.class WIDTH=300 HEIGHT=200> </APPLET>*/
public class list1 extends JApplet implements ListSelectionListener
{
JList jlist;
public void init()
{
Container c= getContentPane();
String[] str=new String[15];
for(int i=0;i<15;i++)
{
str[i]="Item_Selection" +(i+1);
}
jlist= new JList(str);
JScrollPane scp= new JScrollPane(jlist);
jlist.setVisibleRowCount(5);
jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jlist.addListSelectionListener(this);
c.setLayout(new FlowLayout());
c.add(scp);
}
public void valueChanged(ListSelectionEvent lse)
{
String st="Choose Item";
st+=jlist.getSelectedIndex();
showStatus(st);
}
}
The output for the same would look like:
10.2 Trees
The JTree class defines a component that displays data organized in a treelike structure. The elements
of the tree are referred to as nodes. The root node is also called the parent node through which other
nodes are attached, and are called the child nodes. The nodes that do not have any children are called
leaf nodes. The table below illustrates the interfaces of JTree class:
Table 2. Constructors of JTree
Constructor Function
MutableTreeNode Defines the requirements for a tree node object that
can change by adding or removing child nodes, or by
changing the contents of a user object stored in the
node
RowMapper Defines the requirements for an object that translates
paths in the tree into display rows
TreeCellRenderer Defines the requirements for an object that displays
a tree node
The example below shows a simple application for creating a tree. Program is an example of JTree
that is showing the Table of Content in Tree format.
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.event.*;
public class SimpleTree extends JFrame {
public static void main(String[] args) {
new SimpleTree();
}
public SimpleTree() {
super("Creating a Simple JTree");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
Object[] hierarchy =
{"1. CHAPTER 1",
new Object[] {"1.1 INTRODUCTION TO JAVA",
"1.1.1 History of JAVA",
"1.1.2 JAVA and Internet",
"1.1.3 JAVA Virtual Machine",
"1.1.4 JAVA’s Magic: The Byte Code",
"1.1.5 Features of JAVA",
"1.1.6 Java Environment"},
new Object[] {"1.2 DATA TYPES & OPERATORS"},
new Object[] {"1.3 ARRAYS",
"1.3.1 Declaration of Array Variables",
"1.3.2 Array Construction",
"1.3.3 Initialization of Array",
"1.3.4 Array Access",
"1.3.5 Arrays of Characters"},
new Object[]{"1.4 CONTROL STATEMENTS"},
new Object[]{"1.5 A SAMPLE PROGRAM IN JAVA"},
new Object[]{"1.6 CLASSES & METHODS",
"1.6.1 Constructor",
"1.6.2 Garbage Collection"},
new Object[]{"1.7 INHERITANCE",
"1.7.1 Single Inheritance",
"1.7.2 Multiple Inheritance",
"1.7.3 Multilevel Inheritance",
"1.7.4 Hybrid Inheritance"},
new Object[]{"1.8 INTERFACE"},
new Object[]{"1.9 PACKAGES"},
new Object[]{"1.10 EXCEPTION HANDLING",
"1.10.1try and catch with multiple catch clause",
"1.10.2throw and throws",
"1.10.3finally"},
new Object[]{"1.11 MULTITHREADING",
"1.11.1States of a Thread"},
new Object[]{"1.12 COLLECTIONS"},
new Object[]{"1.13 I/O STREAMS",
"1.13.1Working with InputStream and OutputStream",
"1.13.2Working with Reader and Writer"},
new Object[]{"1.14 AWT "},
new Object[]{"1.15 APPLET PROGRAMMING"}};
DefaultMutableTreeNode root = processHierarchy(hierarchy);
JTree tree = new JTree(root);
content.add(new JScrollPane(tree), BorderLayout.CENTER);
setSize(275, 300);
setVisible(true);
}
private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(hierarchy[0]);
DefaultMutableTreeNode child;
for(int i=1; i<hierarchy.length; i++) {
Object nodeSpecifier = hierarchy[i];
if (nodeSpecifier instanceof Object[]) // Ie node with children
child = processHierarchy((Object[])nodeSpecifier);
else
child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
node.add(child);
}
return(node);
} }
import javax.swing.*;
import java.awt.*;
public class WindowUtilities {
public static void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting native LAF: " + e);
}
}
public static void setJavaLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting Java LAF: " + e);
}
}
public static void setMotifLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} catch(Exception e) {
System.out.println("Error setting Motif LAF: " + e);
}
}
public static JFrame openInJFrame(Container content,
int width,
int height,
String title,
Color bgColor) {
JFrame frame = new JFrame(title);
frame.setBackground(bgColor);
content.setBackground(bgColor);
frame.setSize(width, height);
frame.setContentPane(content);
frame.addWindowListener(new ExitListener());
frame.setVisible(true);
return(frame);
}
public static JFrame openInJFrame(Container content, int width, int height,
String title)
return(openInJFrame(content, width, height, title, Color.white));
}
public static JFrame openInJFrame(Container content, int width, int height) {
return(openInJFrame(content, width, height,
content.getClass().getName(),
Color.white));
}
import java.awt.*;
import java.awt.event.*;
public class ExitListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
The output interface would look like:
10.3 Tables
The tables are very powerful components in Swing. They were created to provide an interface to JDBC
that makes programming quite flexible for the user. JTable component allows the user to show and
edit tabular data. JTable components display a rectangular array of data on the screen. The items in the
table can have different types of data. The interface for java.swing.JTable are listed in the table below:
Table 3 Interfaces of JTable
Interface Function
TableCellEditor This defines the method any object that would like to be an editor of values for
components such as JListBox, JComboBox, JTree, JTable needs to implement
TableCellRenderer
This defines the method required by any object that would like to be a renderer
for cells in a JTable
TableColumnModel Defines the requirements for a table column model object suitable for use with
JTable
TableModel This specifies the methods the JTable will use to interrogate a tabular data model.
We can create a JTable object directly from such an object by passing a reference of type TableModel
to a JTable constructor as:
JTable table = new JTable(model);
model is a variable of type TableModel that stores a reference to an object that encapsulates the data to
be displayed.
The rows and columns can also be added at runtime after creating TableModel interface. The example
below shows a simple application for creating a table. The application is written in Swing with JDBC.
The motive to design a search form for a AddBook table. That will search on three fields as following:
* Book Title Search by Book Name
* Publisher Search by Publisher Name
* Keywords Search by main topic covered by the book, and this details is already stored in the
database.
It will apply some conditon as AND or OR, so that the user can apply more than one searching criteria
to search the data from AddBook table.
The structure of the table is given below.
The code for the application is:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.swing.table.*;
class Search extends JFrame implements ActionListener{
JCheckBox cbgbooktitle, cbgpublisher, cbgkeyword;
JTextField txtbooktitle,txtpublisher,txtkeyword;
JComboBox cb,cb1;
Container cp;
JButton btsearch,refresh;
ScrollPane sp;
JPanel p;
JTable table;
String escapeStr="%";
Connection con=null;
Vector columnNames;
Vector data;
DefaultTableModel model ;
public Search()
{
model = new DefaultTableModel(new
Object[]{"bookno","accno","name","author","publisher","topic","issued"}, 0);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:MYDSN");
}
catch(SQLException e){System.out.println(e);}
catch(ClassNotFoundException cl){System.out.println(cl);}
cp=getContentPane();
p=new JPanel();
cp.add(p);
p.setLayout(null);
columnNames = new Vector();
data = new Vector(10);
columnNames.addElement("bookno");
columnNames.addElement("accno");
columnNames.addElement("name");
columnNames.addElement("author");
columnNames.addElement("publisher");
columnNames.addElement("topic");
columnNames.addElement("issued");
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane( table );
p.add(scrollPane);
scrollPane.setBounds(20,250,750,200);
cbgbooktitle=new JCheckBox("Book Title");
cbgpublisher=new JCheckBox("Publisher");
cbgkeyword=new JCheckBox("Keyword");
txtbooktitle=new JTextField(30);
txtpublisher=new JTextField(30);
txtkeyword=new JTextField(30);
cb=new JComboBox();
cb.addItem("Or");
cb.addItem("And");
cb1=new JComboBox();
cb1.addItem("Or");
cb1.addItem("And");
btsearch=new JButton("Search");
p.add(cbgbooktitle);
p.add(cbgkeyword);
p.add(cbgpublisher);
p.add(txtkeyword);
p.add(txtpublisher);
p.add(txtbooktitle);
p.add(btsearch);
p.add(cb);
p.add(cb1);
p.setBounds(0,0,270,250);
cbgbooktitle.setBounds(20,20,100,20);
txtbooktitle.setBounds(120,20,250,20);
cb.setBounds(270,60,100,20);
cbgpublisher.setBounds(20,100,100,20);
txtpublisher.setBounds(120,100,250,20);
cb1.setBounds(270,140,100,20);
cbgkeyword.setBounds(20,180,100,20);
txtkeyword.setBounds(120,180,250,20);
btsearch.setBounds(160,210,100,20);
btsearch.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
int a[]=new int[3];
String escapeStr="%";
if(ae.getSource()==btsearch){
int i=0;
for (;i<model.getRowCount(); )
{
model.removeRow(i);
}
String qstr="Select bookno,accno,name,author,publisher,topic,issued from AddBooks where ";
if(cbgbooktitle.isSelected() && !cbgpublisher.isSelected() && !cbgkeyword.isSelected())
{
qstr=qstr+" name like ?";
a[0]=1;
}
else if(cbgbooktitle.isSelected() && cbgpublisher.isSelected() && !cbgkeyword.isSelected())
{
qstr=qstr+" name like ? "+cb.getSelectedItem()+" publisher like ?";
a[0]=1;
a[1]=2;
}
else if(cbgbooktitle.isSelected() && cbgpublisher.isSelected() && cbgkeyword.isSelected())
{
qstr=qstr+" name like ? "+cb.getSelectedItem()+" publisher like ? "+cb1.getSelectedItem()+" topic
like ? ";
a[0]=1;
a[1]=2;
a[2]=3;
}
else if(!cbgbooktitle.isSelected() && cbgpublisher.isSelected() && !cbgkeyword.isSelected()){
qstr=qstr+" publisher like ? ";
a[1]=1;
}
else if(!cbgbooktitle.isSelected() && cbgpublisher.isSelected() && cbgkeyword.isSelected()){
qstr=qstr+" publisher like ? "+cb1.getSelectedItem()+" topic like ? ";
a[1]=1;
a[2]=2;
}
else if(cbgbooktitle.isSelected() && !cbgpublisher.isSelected() && cbgkeyword.isSelected()){
qstr=qstr+" name like ? "+cb.getSelectedItem()+" topic like ? ";
a[0]=1;
a[2]=2;
}
else if(cbgkeyword.isSelected()){
qstr=qstr+"topic like ? ";
a[2]=1;
}
try{
PreparedStatement p=con.prepareStatement(qstr);
if(a[0]>0)
p.setString(a[0],(escapeStr+txtbooktitle.getText()+escapeStr));
if(a[1]>0)
p.setString(a[1],(escapeStr+txtpublisher.getText()+escapeStr));
if(a[2]>0)
p.setString(a[2],(escapeStr+txtkeyword.getText()+escapeStr));
ResultSet rs=p.executeQuery();
String stdata[]=new String[7];
while(rs.next()){
stdata[0]=rs.getString("bookno");
stdata[1]=rs.getString("accno");
stdata[2]=rs.getString("name");
stdata[3]=rs.getString("author");
stdata[4]=rs.getString("publisher");
stdata[5]=rs.getString("topic");
stdata[6]=rs.getString("issued");
model.addRow(stdata);
}}catch(Exception e){e.printStackTrace();}
}}}
public class BookSearch{
public static void main(String args[]){
JFrame jfr=new Search();
jfr.setSize(800,500);
jfr.setVisible(true);
jfr.setResizable(false);
jfr.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
jfr.addWindowListener(new WindowAdapter(){
public void WindowClosing(WindowEvent we){
System.exit(0);
}}}}
The output interface would look like:
10.4 Styled Text Components
This section includes Text Area, Text Field and Editor Pane components of Swing class.
JTextArea
It is the subclass of JTextComponent that allows the editing of multiline text. Scrollbars can easily be
added by placing JTextArea components in a JScrollPane container. The inheritance diagram for
JTextArea is as follows:
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.text.JTextComponent
javax.swing.JTextArea
Figure 2: Inheritence Diagram for JTextArea
The table below shows the constructors of TextArea class:
Table 4 Constructors of TextArea class
Constructors Function
JTextArea() Constructs a new TextArea
JTextArea(Document doc) Constructs a new JTextArea with the given document model, and
defaults for all of the other arguments (null, 0, 0).
JTextArea(Document doc, Constructs a new JTextArea with the specified number of rows and
String text,int rows, columns, and the given model.
int columns)
JTextArea(int rows, Constructs a new empty TextArea with the specified number of rows
int columns) and columns.
JTextArea(String text) Constructs a new TextArea with the specified text displayed.
JTextArea(String text, Constructs a new TextArea with the specified text and number of rows
int rows, int columns) and columns.
JTextField
Swing text fields work like AWT text fields. The inheritance diagram for JTextField class is as
follows:
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.text.JTextComponent
javax.swing.JTextField
Figure 3: Inheritance Diagram for JTextField
The table below shows the constructors of TextField class
Table 5 Constructors of TextField Class
Constructors Function
JTextField() Constructs a new TextField.
JTextField(Document doc, String text, Constructs a new JTextField that uses the given
int columns) text storage model and the given number of
columns.
JTextField(int columns) Constructs a new empty TextField with the
specified number of columns.
JTextField(String text) Constructs a new TextField initialized with the
specified text.
JTextField(String text, int columns) Constructs a new TextField initialized with the
specified text and columns.
JEditorPane
It enables the users to implement sophisticated editing facilities quite easily. The table below shows
the constructors of JEditorPane class:
Table 6 Constructors of JEditorPane Class
Constructors Function
JEditorPane() Creates a new JEditorPane.
JEditorPane(String type, String text) Creates a JEditorPane that has been initialized to the given text.
JEditorPane(URL initialPage) Creates a JEditorPane based on a specified URL for input.
10.5 Progress Indicators
Progress indicators or progress bars are the new controls that give the users some indications of the
progress of an operation. They were originally developed to check the progress of installation
processes but are now frequently used for all timeconsuming operations. When we call JProgressBar,
we can set the maximum and minimum value for the progress bar. The inheritance diagram for
JProgressBar class is as follows:
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JProgressBar
Figure 4: Inheritance Diagram for JProgressBar
The table below shows the fields of JProgressBar class
Table 7 Fields of JProgressBar class
Field Function
changeEvent Only one ChangeEvent is needed per instance since the event's only interesting
property is the immutable source, which is the progress bar.
changeListener Listens for change events sent by the progress bar's model, redispatching them to
changeevent listeners registered upon this progress bar.
model The object that holds the data for the progress bar.
orientation Whether the progress bar is horizontal or vertical.
paintBorder Whether to display a border around the progress bar.
paintString Whether to textually display a string on the progress bar.
progressString An optional string that can be displayed on the progress bar.
The table below shows the Constructors of JProgressBar class
Table 8 Constructors of JProgressBar class
Constructor Function
JProgressBar() Creates a horizontal progress bar that displays a border but no
progress string.
JProgressBar(BoundedRang Creates a horizontal progress bar that uses the specified model to
eModel newModel) hold the progress bar's data.
JProgressBar(int orient) Creates a progress bar with the specified orientation, which can be
either JProgressBar.VERTICAL or JProgressBar.HORIZONTAL.
JProgressBar(int min, Creates a horizontal progress bar with the specified minimum and
int max) maximum.
JProgressBar(int orient, Creates a progress bar using the specified orientation, minimum, and
int min, int max) maximum.
A JProgressBar is a Swing component that indicates progress. A ProgressMonitor is a dialog box that
contains a progress bar. A ProgressMonitorInputStream displays a progress monitor dialog box while
the stream is read. A progress bar is a simple component just a rectangle that is partially filled with
color to indicate the progress of an operation. By default, progress is indicated by a string "n%". You
can see a progress bar in the bottom right of Fig below
You construct a progress bar much as you construct a slider, by supplying the minimum and maximum
value and an optional orientation:
progressBar = new JProgressBar(0, 1000);
progressBar = new JProgressBar(SwingConstants.VERTICAL, 0, 1000);
A progress bar is a simple component that can be placed inside a window. In contrast, a
ProgressMonitor is a complete dialog box that contains a progress bar (see Fig below). The dialog box
contains a Cancel button. If you click it, the monitor dialog box is closed.
You construct a progress monitor by supplying the following:
• The parent component over which the dialog box should pop up;
• An object (which should be a string, icon, or component) that is displayed on the dialog box;
• An optional note to display below the object;
• The minimum and maximum values.
There are two conditions for termination. The activity might have completed, or the user might have
canceled it. In each of these cases, we close down:
• the timer that monitored the activity;
• the progress dialog box;
• the activity itself (by interrupting the thread).
The example below shows a simple application for creating a progress bar.
class ProgressBar extends JFrame
{
JProgressBar current;
JTextArea ta;
int num = 0;
public ProgressBar()
{
Container pane=getContentPane();
ta=new JTextArea("");
pane.setLayout(new GridLayout());
current = new JProgressBar(0, 100);
current.setValue(0);
current.setStringPainted(true);
pane.add(current);
pane.add(ta);
}
public void iterate()
{
while (num <= 100)
{
current.setValue(num);
try
{
Thread.sleep(500);
}
catch (InterruptedException e) { }
num += 10;
If(num>100)break;
else
ta.setText(num+"%completed");
} }
public static void main(String[] arguments) {
ProgressBar pb = new ProgressBar();
pb.pack();
pb.setVisible(true);
pb.iterate( );
} }
10.6 Component Organizers
In this section, we will discuss about JSplitPane, JTabbedPane & Desktope panes. Swing support split
panes to let programs present two components side by side. The inheritance diagram for JSplitPane
class is as follows:
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JSplitPane
Figure 5: Inheritance Diagram for Component Organizers
Split panes split a component into two parts, with an adjustable boundary in between. Fig below shows
a frame with two split panes.
You construct a split pane by specifying the orientation, one of JSplitPane.HORIZONTAL_SPLIT or
JSplitPane.VERTICAL_SPLIT, followed by the two components.
For example,
JSplitPane innerPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, planetList,planetImage);
The example below shows a simple application for creating a split pane.
public class splitpanecmd extends JFrame implements ListSelectionListener
String ab[]={"hi a","hi b","hi c","hi d"};
JList l1=new JList();
JTextArea l1Description=new JTextArea("hello");
DefaultListModel model;
Container c=getContentPane();
public splitpanecmd()
{
String[] b={"a","b","c","d"};
model=new DefaultListModel();
for(int i=0;i<b.length;i++)
model.add(i, b[i]);
l1.setModel(model);
JSplitPane innerPane
= new JSplitPane(JSplitPane.VERTICAL_SPLIT, l1,l1Description);
c.add(innerPane);
l1.addListSelectionListener(this); }
public void valueChanged(ListSelectionEvent e)
{
int g=l1.getSelectedIndex();
l1Description.setText(ab[g]);
}
public static void main(String[] a)
{
splitpanecmd s=new splitpanecmd();
s.setVisible(true);
}
• Tabbed Panes Tabbed panes are a familiar user interface device to break up a complex dialog
box into subsets of related options. You can also use tabs to let a user flip through a set of
documents or images.
To create a tabbed pane, you first construct a JTabbedPane object,
then you add tabs to it.
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab(title, icon, component);
The example below shows a simple application for creating a tabbed pane.
public class tabbedpanedemo extends JApplet
public void init()
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
getContentPane().add(jtp);
class CitiesPanel extends JPanel
public CitiesPanel()
JButton b1 = new JButton("New York");
add(b1);
JButton b2 = new JButton("London");
add(b2);
JButton b3 = new JButton("Hong Kong");
add(b3);
JButton b4 = new JButton("Tokyo");
add(b4);
class ColorsPanel extends JPanel
public ColorsPanel()
{ JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}}
class FlavorsPanel extends JPanel {
public FlavorsPanel() {
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}}
Desktop Panes and Internal Frames Many applications present information in multiple windows
that are all contained inside a large frame. If you minimize the application frame, then all of its
windows are hidden at the same time. In the Windows environment, this user interface is sometimes
called the multiple document interface or MDI.
Review Questions
1. What are Java Swings? How to implement a tree using Java Swings? (MDU,May’2011
Ans. Refer Section 10.2
2.Write an application to implements trees and styled text components.(MDU,May’2007,
May’2009)
Ans. Every computer user who uses a hierarchical file system has encountered tree displays
directories and files in forms of treelike organizations. (Refer Section 10.2, 10.4)
3.Write an application to implements tables and progress indicators. (MDU, Dec’2007,
Dec’2009)
Ans. The tables are very powerful components in Swing. They were created to provide an interface to
JDBC that makes programming quite flexible for the user. Progress indicators or progress bars are the
new controls that give the users some indications of the progress of an operation. They were originally
developed to check the progress of installation processes but are now frequently used for all time
consuming operations. When we call JProgressBar, we can set the maximum and minimum value for
the progress bar. (Refer Section 10.3,10.5)
4. Write short note on lists, Trees, Styled Text Components. (MDU, May’2008, Dec’2008)
Ans. List is a swing component used to show group of elements with scrollbar. Every computer user
who uses a hierarchical file system has encountered tree displays directories and files in forms of
treelike organizations. (Refer Section 10.1,105.2,10.4)
5. What are component organizers? How the Swing components differ from AWT components?
(MDU, May’2012Dec’2008)
Ans. AWT components are heavyweight, whereas Swing components are lightweight. Hence Swing
works faster than AWT. Heavy weight components depend on the local windowing toolkit. For
example, java.awt.Button is a heavy weight component. Pluggable look and feel possible using java
Swing. Also, we can switch from one look and feel to another at runtime in swing which is not possible
in AWT. (Refer 01.6)
6. Name the containers which use Border Layout as their default layout?
Ans. Window, Frame and Dialog classes.
7. Name Container classes.
Ans. Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane
8. How are the elements of different layouts organized?
Ans. A layout manager is an object that is used to organize components in a container. The different
layouts available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and
West) and the center of a container.
CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a
grid.
GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the
elements may be different sizes and may occupy more than one row or column of the grid. In addition,
the rows and columns may have different sizes.
9. What advantage do Java's layout managers provide over traditional windowing systems?
Ans. Java uses layout managers to lay out components in a consistent manner across all windowing
platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to
accommodate platformspecific differences among windowing systems.
10. What are component organizers? Write a program in Java to implement Trees and Tables?
(MDU, May’2012)
Ans. Refer 10.1, 10.2 & 10.6
What is the JFC?
Ans. JFC stands for “Java Foundation Classes”. This is the term for several capabilities included in the
java 2 Platform. (Some pieces are available for JDK 1.1)
Swing components
Accessibility
Pluggable lookandfeel.
Java 2D (JDK 1.2 only)
Drag and drop (JDK 1.2 only)
11. How do you put my information in a table?
Ans. Either subclass AbstractTableModel and implement the required three methods, or use a
DefaultTableModel (which has a builtin Vector). The method required by AbstractTableModel are
very simple to implement, so subclassing is the preferred method. Using DefaultTableModel requires
the expense of copying your data from its native from into DefaultTableModel.
12. How do you add and delete rows in a JTable?
Ans. JTable is only the view onto the real table. To change the table, you need to work with the table
model. Each model will have its own method to do this. If you’ve subclass AbstractTableModel, you’ll
have to create your own add/delete methods. DefaultTableModel contains methods to
add/delete/records rows.
13. How do you hide a column in a table?
Ans. Sometimes it’s done by setting all the column widths (minimum, preferred and maximum) to 0
pixels,but this leaves the column in the table. A better approach is to use the removeColumn()
method:
JTable table = ……
TableColumn deleteColumn = table.getColumn(“Column Title”);
Table.removeColumn(deletedColumn);
It can later be added back into the table by addColumn(). This only affects what column is shownby
the JTable; the model is unaffected.
14. How can you remove a column from JTable?
Ans. You have to remove it from the ColumnModel.
TableColumnModel model = table.getColumnModel();
Model.removeColumn(model.getColumn(index));
15. How can you add a column to a JTable?
Ans.
Use DefaultTableModel’s addColumn method.
Create a new JTable model.
Update your own JTable’s TableModel (Since your TableModel is a subclass of
AbstractTableModel(there isn’t a strong reason for it not to be) you just need to call
fireTableStructureChanged() when the update is complete).