Java Networking
Java Networking
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, MacOs etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides
1 life cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).
To execute the applet by html file, create an applet and compile it. After that create an html
file and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
Note: class must be public because its object is created by Java Plugin
software that resides on the browser.
//myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
1. public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with
the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw
oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval
with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract booleandrawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, intstartAngle,
intarcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, intstartAngle,
intarcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to
the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to
the specified font.
setBackground(Color.red);
}
}
setForeground(Color.red);
g.drawString("Foreground color set to red", 50, 50);
}
}
//Draw Smiley In Applet Example
importjava.awt.*;
importjava.applet.*;
resize(300,300);
g.drawString("Window has been resized to 300,300", 50, 50);
}
}
//Draw Arc in Applet Window Example
importjava.applet.Applet;
importjava.awt.Color;
importjava.awt.Graphics;
}
}
//Draw Oval & Circle in Applet Window Example
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
}}
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet
{ public void paint(Graphics g)
{ g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
/*<applet code="GraphicsDemo.class" width="300" height="300">
</applet>*/
Applet is mostly used in games and animation. For this purpose image is required to be
displayed. The java.awt.Graphics class provide a method drawImage() to display the image.
The java.applet.Applet class provides getImage() method that returns the object of Image.
Syntax:
1. public Image getImage(URL u, String image){}
1. public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.
import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet
{
Image picture;
In the above example, drawImage() method of Graphics class is used to display the
image.The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object would
also be treated as ImageObserver because Applet class indirectly extends the Component
class.
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be
moved.
import java.awt.*;
import java.applet.*;
Dambal Sir (Sangola Collge,Sangola) 7
public class AnimationExample extends Applet
{
Image picture;
try{Thread.sleep(100);}catch(Exception e){}
}
}
}
/*<applet code="DisplayImage.class" width="300" height="300">
</applet> */
In the above example, drawImage() method of Graphics class is used to display the image.
The 4th argument of drawImage() method of is ImageObserver object. The Component
class implements ImageObserver interface. So current class object would also be treated
as ImageObserver because Applet class indirectly extends the Component class.
Container
The Container is a component in AWT that can contain another components like
buttons, textfields, labels etc. The classes that extends Container class are known
as container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have
other components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can
have other components like button, textfield etc.
Useful Methods of Component class
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int sets the size (width and height) of the
height) component.
public void defines the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean changes the visibility of the component, by
status) default false.
//register listener
b.addActionListener(this);//passing current instance
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
Dambal Sir (Sangola Collge,Sangola) 12
}
}
p.add(b1);p.add(b2);p.add(b3);p.add(b4);p.add(b5);p.add(b6);p.a
dd(b7);p.add(b8);p.add(b9);
p.add(b10);p.add(b11);p.add(b12);p.add(b13);p.add(b14);p.add(
b15);p.add(b16);p.add(b17);
f.add(p);
f.setSize(300,300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==b1)
{
s3 = tf.getText();
s4 = "0";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b2)
{
s3 = tf.getText();
s4 = "1";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b3)
{
s3 = tf.getText();
s4 = "2";
s5 = s3+s4;
tf.setText(s5);
}if(e.getSource()==b4)
{
s3 = tf.getText();
s4 = "3";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b5)
{
s3 = tf.getText();
s4 = "4";
Dambal Sir (Sangola Collge,Sangola) 22
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b6)
{
s3 = tf.getText();
s4 = "5";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b7)
{
s3 = tf.getText();
s4 = "6";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b8)
{
s3 = tf.getText();
s4 = "7";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b9)
{
s3 = tf.getText();
s4 = "8";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b10)
{
s3 = tf.getText();
s4 = "9";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b11)
{
s1 = tf.getText();
tf.setText("");
c=1;
}
if(e.getSource()==b12)
{
s1 = tf.getText();
tf.setText("");
c=2;
}
if(e.getSource()==b13)
{
s1 = tf.getText();
tf.setText("");
c=3;
}
Dambal Sir (Sangola Collge,Sangola) 23
if(e.getSource()==b14)
{
s1 = tf.getText();
tf.setText("");
c=4;
}
if(e.getSource()==b15)
{
s1 = tf.getText();
tf.setText("");
c=5;
}
if(e.getSource()==b16)
{
s2 = tf.getText();
if(c==1)
{
n=
Integer.parseInt(s1)+Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==2)
{
n = Integer.parseInt(s1)-
Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==3)
{
n=
Integer.parseInt(s1)*Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
if(c==4)
{
try
{
int p=Integer.parseInt(s2);
if(p!=0)
{
n=
Integer.parseInt(s1)/Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
tf.setText("infinite");
}
catch(Exception i){}
}
if(c==5)
{
n=
Integer.parseInt(s1)%Integer.parseInt(s2);
tf.setText(String.valueOf(n));
Dambal Sir (Sangola Collge,Sangola) 24
}
}
if(e.getSource()==b17)
{
tf.setText("");
}
}
privateFrame mainFrame;
privateLabel headerLabel;
privateLabel statusLabel;
privatePanel controlPanel;
publicAwtControlDemo()
Dambal Sir (Sangola Collge,Sangola) 25
{
prepareGUI();
}
privatevoid prepareGUI(){
mainFrame =newFrame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(newGridLayout(3,1));
mainFrame.addWindowListener(newWindowAdapter(){
publicvoid windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel =newLabel();
headerLabel.setAlignment(Label.CENTER);
statusLabel =newLabel();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel =newPanel();
controlPanel.setLayout(newFlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
privatevoid showListDemo(){
fruitList.add("Apple");
fruitList.add("Grapes");
fruitList.add("Mango");
fruitList.add("Peer");
vegetableList.add("Lady Finger");
vegetableList.add("Onion");
vegetableList.add("Potato");
vegetableList.add("Tomato");
showButton.addActionListener(newActionListener(){
publicstaticvoidmain(String[] args)
{
// needed on mac os x
System.setProperty("apple.laf.useScreenMenuBar", "true");
// the proper way to show a jframe (invokeLater)
SwingUtilities.invokeLater(newJavaMenuBarExample());
}
publicvoidrun()
{
frame = newJFrame("Java Menubar Example");
menuBar = newJMenuBar();
// build the File menu
fileMenu = newJMenu("File");
openMenuItem = newJMenuItem("Open");
openMenuItem.addActionListener(this);
fileMenu.add(openMenuItem);
// build the Edit menu
editMenu = newJMenu("Edit");
cutMenuItem = newJMenuItem("Cut");
copyMenuItem = newJMenuItem("Copy");
pasteMenuItem = newJMenuItem("Paste");
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
// add menus to menubar
menuBar.add(fileMenu);
menuBar.add(editMenu);
// put the menubar on the frame
frame.setJMenuBar(menuBar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(newDimension(400, 300));
Dambal Sir (Sangola Collge,Sangola) 27
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
/**
* This handles the action for the File/Open event, and demonstrates
* the implementation of an ActionListener.
* In a real-world program you'd handle this differently.
*/
publicvoidactionPerformed(ActionEvent ev)
{
SampleDialog dialog = newSampleDialog();
dialog.setModal(true);
dialog.setVisible(true);
}
/**
* This dialog is displayed when the user selects the File/Open menu item.
*/
privateclassSampleDialog extendsJDialog implementsActionListener
{
privateJButton okButton = newJButton("OK");
privateSampleDialog()
{
super(frame, "Sample Dialog", true);
JPanel panel = newJPanel(newFlowLayout());
panel.add(okButton);
getContentPane().add(panel);
okButton.addActionListener(this);
setPreferredSize(newDimension(300, 200));
pack();
setLocationRelativeTo(frame);
}
publicvoidactionPerformed(ActionEvent ev)
{
setVisible(false);
}
}
}
LayoutManagers:
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout
managers. There are following classes that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south,
east, west and center. Each region (area) may contain one component only. It is the
default layout of frame or window. The BorderLayout provides five constants for
each region:
Dambal Sir (Sangola Collge,Sangola) 28
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
BorderLayout(): creates a border layout but with no gaps between the
components.
JBorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
BoxLayout class
The BoxLayout is used to arrange the components either vertically or horizontally.
For this purpose, BoxLayout provides four constants. They are as follows:
Note: BoxLayout class is found in javax.swing package.
Fields of BoxLayout class:
1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS
Constructor of BoxLayout class:
1. BoxLayout(Container c, int axis): creates a box layout that arranges the
components with the given axis.
Java Swing tutorial 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 javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Difference between AWT and Swing
There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing
1) AWT components are platform-dependent. Java swing components are
platform-independent.
2) AWT components are heavyweight. Swing components are
lightweight.
3) AWT doesn't support pluggable look and Swing supports pluggable look
feel. and feel.
4) AWT provides less components than Swing provides more powerful
Swing. components such as tables,
lists, scrollpanes, colorchooser,
tabbedpane etc.
5) AWT doesn't follows MVC(Model View Swing follows MVC.
Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and
view.
Main Features of Swing Toolkit
1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Rich Controls
7. Pluggable Look and Feel
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Features of JFC
Swing GUI components.
Look and Feel support.
Java 2D.
Swing and JFC
JFC is an abbreviation for Java Foundation classes, which encompass a
group of features for building Graphical User Interfaces(GUI) and adding
rich graphical functionalities and interactivity to Java applications. Java
Swing is a part of Java Foundation Classes (JFC).
Commonly used Methods of Component class
The methods of Component class are widely used in java swing that are given
below.
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int sets size of the component.
height)
public void sets the layout manager for the component.
setLayout(LayoutManager m)
public void setVisible(boolean b) sets the visibility of the component. It is by
default false.
Dambal Sir (Sangola Collge,Sangola) 34
Hierarchy of Java Swing classes
JPanel : JPanel is Swing's version of AWT class Panel and uses the same default
layout, FlowLayout. JPanel is descended directly from JComponent.
JFrame : JFrame is Swing's version of Frame and is descended directly
from Frame class. The component which is added to the Frame, is
refered as its Content.
JWindow : This is Swing's version of Window and has descended directly
from Window class. Like Window it uses BorderLayout by default.
JLabel : JLabel has descended from JComponent, and is used to create text labels.
JButton : JButton class provides the functioning of push button. JButton allows
an icon, string or both associated with a button.
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.
It inherits AbstractButton class.
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Sangola.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java JTextField
The object of a JTextField class is a text component that allows the editing of a
single line text. It inherits JTextComponent class.
public class JTextField extends JTextComponent implements SwingConstant
s
Commonly used Constructors:
Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized with the
specified text.
JTextField(String text, int Creates a new TextField initialized with the
columns) specified text and columns.
Dambal Sir (Sangola Collge,Sangola) 37
JTextField(int columns) Creates a new empty TextField with the specified
number of columns.
Commonly used Methods:
Methods Description
void addActionListener(ActionListener It is used to add the specified action
listener to receive action events from this
textfield.
Action getAction() It returns the currently set Action for this
ActionEvent source, or null if no Action is
set.
void setFont(Font f) It is used to set the current font.
void It is used to remove the specified action
removeActionListener(ActionListener l) listener so that it no longer receives action
events from this textfield.
import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}}
import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JCheckBox checkbox1 = new JCheckBox("C++");
checkbox1.setBounds(150,100, 50,50);
JCheckBox checkbox2 = new JCheckBox("Java");
checkbox2.setBounds(150,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Dambal Sir (Sangola Collge,Sangola) 40
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one
option from multiple options. It is widely used in exam systems or quiz.
public class JRadioButton extends JToggleButton implements Accessible
The object of Choice class is used to show popup menu of choices. Choice selected
by user is shown on the top of a menu. It inherits JComponent class.
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
final JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
f.add(cb); f.add(label); f.add(b);
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "
+ cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
The JTable class is used to display data in tabular form. It is composed of rows and
columns.
Commonly used Constructors:
Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
Java JTable Example
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Java JTable Example with ListSelectionListener
import javax.swing.*;
import javax.swing.event.*;
public class TableExample {
public static void main(String[] a) {
JFrame f = new JFrame("Table Example");
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
final JTable jt=new JTable(data,column);
jt.setCellSelectionEnabled(true);
ListSelectionModel select= jt.getSelectionModel();
select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
select.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String Data = null;
int[] row = jt.getSelectedRows();
int[] columns = jt.getSelectedColumns();
for (int i = 0; i < row.length; i++) {
for (int j = 0; j < columns.length; j++) {
Data = (String) jt.getValueAt(row[i], columns[j]);
}}
System.out.println("Table element selected is: " + Data);
}
});
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300, 200);
f.setVisible(true);
Dambal Sir (Sangola Collge,Sangola) 43
}
}
If you select an element in column NAME, name of the element will be displayed on
the console:
Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message
dialog box, confirm dialog box and input dialog box. These dialog boxes are used to
display information or get input from the user. The JOptionPane class inherits
JComponent class.
Common Constructors of JOptionPane class
Constructor Description
JOptionPane() It is used to create a JOptionPane with a test
message.
JOptionPane(Object message) It is used to create an instance of JOptionPane to
display a message.
JOptionPane(Object message, It is used to create an instance of JOptionPane to
int messageType display a message with specified message type and
default options.
Methods Description
JDialog createDialog(String title) It is used to create and return a
new parentless JDialog with the
specified title.
static void showMessageDialog(Component It is used to create an information-
parentComponent, Object message) message dialog titled "Message".
static void showMessageDialog(Component It is used to create a message
parentComponent, Object message, String dialog with given title and
title, int messageType) messageType.
static int showConfirmDialog(Component It is used to create a dialog with
parentComponent, Object message) the options Yes, No and Cancel;
with the title, Select an Option.
static String showInputDialog(Component It is used to show a question-
parentComponent, Object message) message dialog requesting input
from the user parented to
parentComponent.
void setInputValue(Object newValue) It is used to set the input value
that was selected or input by the
user.
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Hello, Welcome to Sangola.");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
import javax.swing.*;
Dambal Sir (Sangola Collge,Sangola) 44
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPa
ne.WARNING_MESSAGE);
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
String name=JOptionPane.showInputDialog(f,"Enter Name");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
import javax.swing.*;
import java.awt.event.*;
public class OptionPaneExample extends WindowAdapter{
JFrame f;
OptionPaneExample(){
f=new JFrame();
f.addWindowListener(this);
f.setSize(300, 300);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setVisible(true);
}
public void windowClosing(WindowEvent e) {
int a=JOptionPane.showConfirmDialog(f,"Are you sure?");
if(a==JOptionPane.YES_OPTION){
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
The JMenuBar class is used to display menubar on the window or frame. It may
have several menus.The object of JMenu class is a pull down menu component
which is displayed from the menu bar. It inherits the JMenuItem class.The object
of JMenuItem class adds a simple labeled menu item. The items used in a menu
must belong to the JMenuItem or any of its subclass.
JMenuBar class declaration
Dambal Sir (Sangola Collge,Sangola) 45
public class JMenuBar extends JComponent implements MenuElement, Accessible
import javax.swing.*;
import java.awt.event.*;
public class MenuExample implements ActionListener{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;
MenuExample(){
f=new JFrame();
cut=new JMenuItem("cut");
copy=new JMenuItem("copy");
paste=new JMenuItem("paste");
selectAll=new JMenuItem("selectAll");
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
mb=new JMenuBar();
file=new JMenu("File");
Dambal Sir (Sangola Collge,Sangola) 46
edit=new JMenu("Edit");
help=new JMenu("Help");
edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
mb.add(file);mb.add(edit);mb.add(help);
ta=new JTextArea();
ta.setBounds(5,5,360,320);
f.add(mb);f.add(ta);
f.setJMenuBar(mb);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==cut)
ta.cut();
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();
}
public static void main(String[] args) {
new MenuExample();
}}
Java JProgressBar
The JProgressBar class is used to display the progress of the task. It inherits
JComponent class.
Commonly used Constructors:
Constructor Description
JProgressBar() It is used to create a horizontal progress bar but no string
text.
JProgressBar(int It is used to create a horizontal progress bar with the
min, int max) specified minimum and maximum value.
JProgressBar(int It is used to create a progress bar with the specified
orient) orientation, it can be either Vertical or Horizontal by using
SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
JProgressBar(int It is used to create a progress bar with the specified
orient, int min, int orientation, minimum and maximum value.
max)
Commonly used Methods:
Method Description
void setStringPainted(boolean It is used to determine whether string should be
b) displayed.
void setString(String s) It is used to set value to the progress string.
void setOrientation(int It is used to set the orientation, it may be either
orientation) vertical or horizontal by using
SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
void setValue(int value) It is used to set the current value on the progress
bar.
Java JTabbedPane