1. QUESTION BANK
UNIT –II
Q.1 How to divide the jFrame intotwo parts? Explainwith code specification?
Ans: A JSplitPanedisplaystwo components,eithersideby side or oneon top of the other.By dragging thedividerthat
appearsbetween thecomponents,theusercan specify how much of the split pane'stotal area goesto each
component.You can dividescreen spaceamong threeor morecomponentsby putting splitpanesinside of split
panes.
Example:
importjava.awt.BorderLayout;
importjavax.swing.JFrame;
importjavax.swing.JSplitPane;
publicclassSwingSplitSample{
publicstaticvoidmain(String args[]) {
JFrameframe= new JFrame("JSplitPaneSample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSplitPanesplitPane= new JSplitPane();
splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
frame.getContentPane().add(splitPane, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Q.2 Explainthe new featuresofJFC(Explainthe featuresof Swings) ?
Ans: The Java Foundation Classes(JFC) /Swings area comprehensivesetof GUIcomponentsand serviceswhich
dramatically simplify the developmentof desktop applications
1. Truly cross-platform:Being partof the Java Platform,allJFC componentsand servicesaredesigned to work
everywhere.Forexample,Drag and Drop services within JFC workthe samebetween the Java Platformand
all operating systems.
2. Fullycustomizable:Developerscan easily extend thesecomponentsto createothermore customized
components.In addition,even thelookand feel of these componentscan bechangeby eitherdevelopersor
usersthrough thePluggableLookand Feel architecturein JFC.
3. JavaBeanscomponents:All JFCcomponentsareJavaBeanscomponents.JFCcomponentshaveallthe
benefitsthatJavaBeanscomponentsoffer -- reusability,interoperability,and portability.
4. There is noframework lock-in:Developerscan easily bring in otherthird-party JavaBeanscomponentsto
enhancetheir applicationswritten using JFC.JFCoffersan open architecture.
Q.3 How can the userbe made aware of the software loadingprocess? Whichcomponenetisfacilitatingthe same?
2. Explainwith code specification
Ans:
importjava.awt.BorderLayout;
importjava.awt.Container;
importjavax.swing.BorderFactory;
importjavax.swing.JFrame;
importjavax.swing.JProgressBar;
importjavax.swing.border.Border;
publicclassProgressSample{
publicstaticvoidmain(String args[]) {
JFramef = new JFrame("JProgressBarSample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Containercontent= f.getContentPane();
JProgressBarprogressBar=new JProgressBar();
progressBar.setValue(25);
progressBar.setStringPainted(true);
Border border= BorderFactory.createTitledBorder("Reading...");
progressBar.setBorder(border);
content.add(progressBar, BorderLayout.NORTH);
f.setSize(300, 100);
f.setVisible(true);
}
}
Q.4 Write a java swing program that createsthe hierarchical tree data structure?
Ans:
Treeexample.java
importjavax.swing.JFrame;
importjavax.swing.JTree;
importjavax.swing.SwingUtilities;
importjavax.swing.tree.DefaultMutableTreeNode;
public class TreeExampleextendsJFrame
{
private JTree tree;
public TreeExample()
{
//createthe rootnode
DefaultMutableTreeNoderoot=newDefaultMutableTreeNode("Root");
//createthe child nodes
DefaultMutableTreeNodevegetableNode=new DefaultMutableTreeNode("Vegetables")
3. vegetableNode.add(new DefaultMutableTreeNode("Capsicum"));
vegetableNode.add(new DefaultMutableTreeNode("Carrot"));
vegetableNode.add(new DefaultMutableTreeNode("Tomato"));
vegetableNode.add(new DefaultMutableTreeNode("Potato"));
DefaultMutableTreeNodefruitNode=new DefaultMutableTreeNode("Fruits");
fruitNode.add(newDefaultMutableTreeNode("Banana"));
fruitNode.add(newDefaultMutableTreeNode("Mango"));
fruitNode.add(newDefaultMutableTreeNode("Apple"));
fruitNode.add(newDefaultMutableTreeNode("Grapes"));
fruitNode.add(newDefaultMutableTreeNode("Orange"));
//add thechild nodesto the rootnode
root.add(vegetableNode);
root.add(fruitNode);
//create thetree by passing in theroot node
tree = new JTree(root);
add(tree);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("JTreeExample");
this.pack();
this.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(newRunnable() {
@Override
public void run() {
newTreeExample();
}
});
}
}
Q.5 Write a java program usingsplitpane to demonstrate that a screendividedintwo parts. One part contains the
examinationseat numberof students.Whenuser selectsthe examseat number, photo ofthe studentshould get
displayedinanother pane.
Ans: Sameas yourjournalplanetprogram
Q.6 Explainthe use ofprogress bar control withsuitable example.
Ans:
4. importjava.awt.BorderLayout;
importjava.awt.Container;
importjavax.swing.BorderFactory;
importjavax.swing.JFrame;
importjavax.swing.JProgressBar;
importjavax.swing.border.Border;
publicclassProgressSample{
publicstaticvoidmain(String args[]) {
JFramef = new JFrame("JProgressBarSample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Containercontent= f.getContentPane();
JProgressBarprogressBar=new JProgressBar();
progressBar.setValue(25);
progressBar.setStringPainted(true);
Border border= BorderFactory.createTitledBorder("Reading...");
progressBar.setBorder(border);
content.add(progressBar, BorderLayout.NORTH);
f.setSize(300, 100);
f.setVisible(true);
}
}
Q.7. Withthe helpof an example explainjColorChoosercomponent.
Ans: The class JColorChooserprovidesa paneof controlsdesigned to allow a user to manipulateand selecta color.
Example:
importjava.awt.Color;
importjavax.swing.JColorChooser;
publicclassMain {
publicstaticvoidmain(String[] argv) {
Color initialColor = Color.red;
Color newColor= JColorChooser.showDialog(null, "Dialog Title", initialColor);
}
}
Q.8. Compare and contrast AWTand SWING.
Ans:
Swing AWT
Swing is also called as JFC’s(Java Foundation
classes).
AWT standsforAbstractwindows toolkit.
Swingsare called light weightcomponent
becauseswing componentssitson thetop of
AWT componentsand do thework.
AWT componentsarecalled Heavyweight
component.
5. Swing componentsrequirejavax.swing
package.
AWT componentsrequirejava.awtpackage.
Swing componentsaremadein purely java
and they are platformindependent.
AWT componentsareplatformdependent.
We can havedifferentlookand feel in Swing. This featureis not supported in AWT.
Swing hasmany advanced featureslike
JTabel, Jtabbed panewhich is notavailable in
AWT. Also.Swing componentsarecalled
"lightweight"becausethey do not requirea
nativeOS objectto implement their
functionality.JDialog and JFrameare
heavyweight,becausethey do havea peer.So
componentslikeJButton,JTextArea,etc.,are
lightweightbecausethey do not havean OS
peer.
These featureis notavailablein AWT.
Swing hasthembuilt in. Using AWT, you haveto implement a lot of
thingsyourself.
Q.9 ExplainjScrollPane with example
Ans: A JScrollPaneprovidesa scrollable view of a component.When screen real estateis limited, usea scroll paneto
display a componentthatislarge or onewhose size can changedynamically.
Example:
importjava.awt.BorderLayout;
importjavax.swing.Icon;
importjavax.swing.ImageIcon;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JScrollPane;
publicclassScrollSample{
publicstaticvoidmain(String args[]) {
String title = (args.length ==0 ? "JScrollPaneSample": args[0]);
JFrameframe= new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Icon icon = new ImageIcon("dog.jpg");
JLabel dogLabel= new JLabel(icon);
JScrollPanescrollPane= new JScrollPane();
scrollPane.setViewportView(dogLabel);
// scrollPane.getViewport().setView(dogLabel);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Q.10 How are menuscreatedin java ? what are the classesused for creating menus?Explainwith example
6. Ans: Performthefollowing stepsfordesigning the JFRAMEformwith a menu:
Right click on the projectand create a new JFrameform
Drag a menubarfromtheswing Menusonto theform
Right click on the menubaradd menu
Right click on the menu and add menuitem
Doubleclick on theexit meni item and write thefollowing code
Example:
importjava.awt.Toolkit;
importjava.awt.event.WindowEvent;
importjavax.swing.JOptionPane;
public class Menueg extendsjavax.swing.JFrame{
public Menueg() {
initComponents();
}
// performthefollowing action on Exit button click
privatevoid jMenuItem6ActionPerformed(java.awt.event.ActionEventevt) {
int p=JOptionPane.showConfirmDialog(null,"Areu Sureto Close");
if(p==0){
WindowEventwinclose=newWindowEvent(this,WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winclose);}
}
Q.11 Explainwith suitable example how siblingsandchild node are added in a tree
Ans:
Treeexample.java
importjavax.swing.JFrame;
importjavax.swing.JTree;
importjavax.swing.SwingUtilities;
importjavax.swing.tree.DefaultMutableTreeNode;
public class TreeExampleextendsJFrame
{
private JTree tree;
public TreeExample()
{
//createthe rootnode
DefaultMutableTreeNoderoot=newDefaultMutableTreeNode("Root");
//createthe child nodes
DefaultMutableTreeNodevegetableNode=new DefaultMutableTreeNode("Vegetables")
7. vegetableNode.add(new DefaultMutableTreeNode("Capsicum"));
vegetableNode.add(new DefaultMutableTreeNode("Carrot"));
vegetableNode.add(new DefaultMutableTreeNode("Tomato"));
vegetableNode.add(new DefaultMutableTreeNode("Potato"));
DefaultMutableTreeNodefruitNode=new DefaultMutableTreeNode("Fruits");
fruitNode.add(newDefaultMutableTreeNode("Banana"));
fruitNode.add(newDefaultMutableTreeNode("Mango"));
fruitNode.add(newDefaultMutableTreeNode("Apple"));
fruitNode.add(newDefaultMutableTreeNode("Grapes"));
fruitNode.add(newDefaultMutableTreeNode("Orange"));
//add thechild nodesto the rootnode
root.add(vegetableNode);
root.add(fruitNode);
//create thetree by passing in theroot node
tree = new JTree(root);
add(tree);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("JTreeExample");
this.pack();
this.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(newRunnable() {
@Override
public void run() {
newTreeExample();
}
});
}
}
Q.12 Explainwith suitable example the needof a table model
Ans: The DefaultTableModelclassis a subclass of the AbstractTableModel.Asthenamesuggestsitis the tablemodel
thatis used by a JTable when no table modelis specifically defined by the programmer.TheDefaultTableModel
storesthe dataforthe JTable in a Vectorof Vectors.
The advantageofusingtheDefaultTableModel over a customAbstractTableModel is
you don'thaveto codethe methodslike add,insertor delete rowsand columns.
They already existto changethedata held in the VectorofVectors.
8. This makesit a quick and easy table modelto implement.
Q.13 List and explainthe layout orientationsusedfor jList. Give a suitable example
Ans: The class JList is a component which displays a list of objects and allows the user to select one or more items. A
separatemodel,ListModel, maintainsthecontentsof the list.
Followingarethe differentlayoutorientationused for javax.swing.JListclass:
1. static intHORIZONTAL_WRAP --Indicatesa "newspaperstyle"layoutwith cells flowing
horizontally then vertically.
2. static intVERTICAL -- Indicatesa vertical layoutof cells, in a singlecolumn;the default
layout.
3. static intVERTICAL_WRAP -- Indicatesa "newspaperstyle"layoutwith cells flowing
4. vertically then horizontally.
Example:
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
class ListExampleextendsJFrame
{ // Instanceattributesused in this example
private JPanel topPanel;
private JList listbox;
publicListExample()
{
// Set theframecharacteristics
setTitle( "Simple ListBox Application");
setSize( 300, 100 );
setBackground(Color.gray );
// Createa panelto hold all othercomponents
topPanel= newJPanel();
topPanel.setLayout(newBorderLayout());
getContentPane().add(topPanel);
// Createsomeitems to add to the list
String listData[] =
{ "Item1",
"Item2",
"Item3",
"Item4" };
// Createa newlistbox control
listbox = newJList( listData);
topPanel.add( listbox,BorderLayout.CENTER);
}
// Main entry point forthis example
public static void main( String args[] )
{
9. // Createan instanceof the test application
ListExamplemainFrame= new ListExample();
mainFrame.setVisible( true);
}
}
Q.14 What is the purpose oftabbed panes?Explain with suitable examples.
Ans: A tabbed panescomponentletsthe user switch between a group of componentsby clicking on a tab with a
given title and/oricon.
The user chooseswhich componentto view by selecting the tab corresponding to thedesired component.
Tabs/componentsareadded to a TabbedPaneobjectby using theaddTab and insertTab methods.
A tab is represented by an index corresponding to theposition it was added in,wherethe first tab hasan
index equalto 0 and the last tab hasan index equalto thetab countminus1.
The TabbedPaneusesa SingleSelectionModelto representtheset of tab indices and the currently selected
index.If the tab countis greaterthan 0, then there will alwaysbea selected index,which by defaultwill be
initialized to the first tab.If the tab countis 0, then theselected index will be -1.
JTabbedPaneConstructor
1. JTabbedPane()
Createsan emptyTabbedPanewith a defaulttab placementof JTabbedPane.TOP.
2. JTabbedPane(inttabPlacement)
Createsan emptyTabbedPanewith thespecified tab placementof either: JTabbedPane.TOP,
JTabbedPane.BOTTOM,JTabbedPane.LEFT,orJTabbedPane.RIGHT.
3. JTabbedPane(inttabPlacement,inttabLayoutPolicy)
Createsan emptyTabbedPanewith thespecified tab placementand tab layoutpolicy.
Example:
JTabbedPanetabbedPane=newJTabbedPane();
ImageIcon icon = createImageIcon("images/middle.gif");
JComponentpanel1=makeTextPanel("Panel#1");
tabbedPane.addTab("Tab1",icon,panel1,
"Doesnothing");
tabbedPane.setMnemonicAt(0,KeyEvent.VK_1);
JComponentpanel2=makeTextPanel("Panel#2");
tabbedPane.addTab("Tab2",icon,panel2,
"Doestwice asmuch nothing");
tabbedPane.setMnemonicAt(1,KeyEvent.VK_2);
JComponentpanel3=makeTextPanel("Panel#3");
tabbedPane.addTab("Tab3",icon,panel3,
"Still doesnothing");
tabbedPane.setMnemonicAt(2,KeyEvent.VK_3);