Sunday, April 1, 2012

SWING - Java


SWING
Swing
  * It is a set of classes that provides more powerful and flexible components that are possible with   the AWT.
  * Additional components
  -------------------------
  TabbedPane
  ScrollPane
  Tree
  Table
  * It has a light weight component
      it means the components are implemented by the platform independent code Java.

  * package
  javax.swing

  * Swing component classes
  ImageIcon - Encapsulates an icon
  JApplet - swing version of Applet
  JButton - swing push button class
  JCheckBox - swing check box class
  JComboBox - swing combo box
  JLabel - swing version of label
  JRadioButton - swing version of Radio Button
  JScrollPane - encapsulates a scrollable window
  JTabbedPane - encapsulates a tabbed window
  JTable - encapsulates a table based control
  JTextField - swing version of textfield
  JTree - encapsulates a tree based control

Understanding Root Panes
----------------------------------
The JRootPane class is the class that manages the appearance of Japplet and Jframe objects.
The root pane contains the
  ContentPane
  GlassPane
   LayeredPane.
We usually work with the content pane of the root pane.  The content pane itself, however, is part of another pane-the layered pane.

A Container is a collection of related components. In applications with Jframes and in applets, we attach components to the content pane, which is an object of class Container.Class Container defines the common attributes and behaviors for all subclasses of Container. One method that originates in class Container is add for adding components to a Container. Another method that originates in class Container is setLayout, which enables a program to specify the layout manager that helps a Container position and size its components.




Swing AWT
----- ---
1)Additional components like 1)Not present
Tree,Table,Scrollpane,Tabbed pane
are present

2)Components are light weight 2)Components are heavy weight
because the components are because they are developed by c and
developed by Java codings                      c++ codings

3)Look and feel good               3)Not look and feel good

4)Default layout is flow layout 4)Default layout is border layout


5)Able to insert picture in 5)Not able to insert picture in button and label
button and label

6)Components are present in 6)Components are present in
java.awt
javax.swing

7)JApplet is used 7)Applet is used


TIP:
Swing  content panes use a border layout manager by default, whereas AWT applets use a flow layout by default, although AWT frame windows do use border layouts by default.

  ContentPane can be obtained via the method
  ---------------
  Container getContentPane()

  to add a component to a content pane
  ------------------------
  add(component)


  Icons and Labels:
  ---------------
  ImageIcon:
  ----------
  constructors
  ------
  ImageIcon(String filename)
  ImageIcon(URL url)

  Methods:
  ---------
  int getIconHeight()
  int getIconWidth();

  Label:
  -----
  constructors:
  --------
  JLabel(Icon i)
  JLabel(String s)
  JLabel(String s,Icon i,int align);

  align- LEFT,RIGHT,CENTER
  methods:
  --------
  Icon getIcon()
  String getText()
  void setIcon(Icon i)
  void setText(String s)
import java.awt.*;
import javax.swing.*;

public class jlabel extends JFrame
{
jlabel()
{
Container cp=getContentPane();
ImageIcon ic=new ImageIcon("rose1.jpg");
JLabel jl=new JLabel("Flower",ic,JLabel.RIGHT);
cp.add(jl);
}
public static void main(String args[])
{
jlabel j1=new jlabel();
j1.setSize(200,200);
j1.setVisible(true);
}
}

import java.awt.*;
import javax.swing.*;
/* <applet code="jlabeldemo" width=300 height=300>
</applet> */
public class jlabeldemo extends JApplet
{
public void init()
{
Container cp=getContentPane();
ImageIcon ic=new ImageIcon("rose1.jpg");
JLabel jl=new JLabel("Flower",ic,JLabel.RIGHT);
cp.add(jl);
}
}
============================
 JTextField
  ----------
  constructors
  JTextField()
  JTextField(int cols)
  JTextField(String s,int cols)
  JTextField(String s)

  JButton:
  --------
  constructors
  JButton(Icon i)
  JButton(String s)
  JButton(String s,Icon i)


  Methods
  void setDisabledIcon(Icon)
  void setPressedIcon(Icon)
  void setSelectedIcon(Icon)
  void setRolloverIcon(Icon)

  text associated with the button can be read and written  by
  String getText();
  void setText(String);

  Listeners can be applied by
  --------
  void addActionListener(ActionListener)
  void removeActionListener(ActionListener)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//<applet code="jbuttondemo" height=400 width=400></applet>
public class jbuttondemo extends JApplet implements ActionListener
{
JTextField jft;
public void init()
{
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
ImageIcon ic=new ImageIcon("rose4.jpg");

JButton jb=new JButton(ic);

jft=new JTextField(20);
jb.addActionListener(this);
cp.add(jb);

cp.add(jft);
}
public void actionPerformed(ActionEvent ae)
{
jft.setText("Have a good day");
}
}

  Checkbox
  --------
  constructors:
  -------------
  JCheckBox(Icon i)
  JCheckBox(Icon i,boolean state)
  JCheckBox(String s)
  JCheckBox(String s,boolean state)
  JCheckBox(String s,Icon i)
  JCheckBox(String s,Icon i,boolean state)

  state of the checkbox can be changed via
  void setSelected(boolean state)
  import java.awt.*;
  import java.awt.event.*;
  import javax.swing.*;
  /* <applet code="jcheckboxdemo" width=300 height=300>
  </applet> */
  public class jcheckboxdemo extends JApplet implements ItemListener
  {
  JTextField jft;
  public void init()
  {
  Container cp=getContentPane();
  ImageIcon ic=new ImageIcon("Flower7.jpg");
  ImageIcon ic1=new ImageIcon("Flower8.jpg");
  ImageIcon ic2=new ImageIcon("Flower9.jpg");
  ImageIcon ic3=new ImageIcon("Flower4.jpg");


  cp.setLayout(new FlowLayout());

  JCheckBox cb=new JCheckBox("C",ic);
  cb.setRolloverIcon(ic1);
  cb.setSelectedIcon(ic2);
  cb.setPressedIcon(ic3);
  cb.addItemListener(this);
  cp.add(cb);
   cb=new JCheckBox("C++",ic);
  cb.setRolloverIcon(ic1);
  cb.setSelectedIcon(ic2);
  cb.setPressedIcon(ic3);
  cb.addItemListener(this);
  cp.add(cb);
  cb=new JCheckBox("Java",ic);
  cb.setRolloverIcon(ic1);
  cb.setSelectedIcon(ic2);
  cb.setPressedIcon(ic3);
  cb.addItemListener(this);
  cp.add(cb);
  jft=new JTextField(15);
  cp.add(jft);
  }
  public void itemStateChanged(ItemEvent ie)
  {
  JCheckBox cb=(JCheckBox)ie.getItem();
  jft.setText(cb.getText());
}}
===============================


  import java.awt.event.*;
  import javax.swing.*;
  import java.awt.*;
  class check extends JFrame implements ItemListener
  {
  JCheckBox jcb,jcb1;
  JTextArea ta;
  check()
  {
  Container c=getContentPane();
  ImageIcon ic=new ImageIcon("MSN.GIF");
  ImageIcon ic1=new ImageIcon("tomcat.GIF");
  ImageIcon ic2=new ImageIcon("SPADES.GIF");
  jcb=new JCheckBox("Green",ic);
  jcb.setRolloverIcon(ic1);
  jcb.setSelectedIcon(ic2);

  jcb1=new JCheckBox("Blue");
  ta=new JTextArea(5,20);
  c.setLayout(new FlowLayout());
  c.add(jcb);
  c.add(jcb1);
  c.add(ta);

  ButtonGroup bg=new ButtonGroup();
  bg.add(jcb);
  bg.add(jcb1);
  jcb.addItemListener(this);
  jcb1.addItemListener(this);
  pack();
  setVisible(true);
  }
  public void itemStateChanged(ItemEvent ie)
  {
  if(ie.getSource()==jcb)
  ta.setBackground(Color.green);
  else
  ta.setBackground(Color.blue);
  }
  public static void main(String args[])
  {
  check ck=new check();
  }
}
  RadioButton:
  ------------
  constructors:
  ------
  JRadioButton(Icon i)
  JRadioButton(Icon i,boolean state)
  JRadioButton(String s)
  JRadioButton(String s,boolean state)
  JRadioButton(String s,Icon i)
  JRadioButton(String s,Icon i,boolean state)

  ButtonGroup - used to create a button group
     elements are added into this by
         void add(button);
         import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* <applet code="jrbdemo"  width=400 height=400>
</applet> */
public class jrbdemo extends JApplet implements ActionListener
{
JLabel jl;
ImageIcon i1,i2,i3;
public void init()
{
 Container con=getContentPane();
 con.setLayout(new FlowLayout());
 i1=new ImageIcon("MSN.GIF");
 i2=new ImageIcon("SPADES.GIF");
 i3=new ImageIcon("rose6.jpg");
JRadioButton b1=new JRadioButton("France");
b1.addActionListener(this);
con.add(b1);
JRadioButton b2=new JRadioButton("USA");
b2.addActionListener(this);
con.add(b2);
JRadioButton b3=new JRadioButton("Germany");
b3.addActionListener(this);
con.add(b3);
jl=new JLabel("France",i1,JLabel.CENTER);
con.add(jl);
ButtonGroup bg=new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("France"))
{
jl.setIcon(i1);
jl.setText("France");
}
else if(ae.getActionCommand().equals("USA"))
{
jl.setIcon(i2);
jl.setText("USA");
}
else if(ae.getActionCommand()=="Germany")
{
jl.setIcon(i3);
jl.setText("Germany");
}
}
}
=====================
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* <applet code="jrbutton"  width=400 height=400>
</applet> */
public class jrbutton extends JApplet implements ItemListener
{
JRadioButton j1,j2,j3;
JTextField tf;
ButtonGroup g;
public void init()
{
Container c1=getContentPane();
c1.setLayout(new FlowLayout());
g=new ButtonGroup();
j1=new JRadioButton("Red");
j2=new JRadioButton("Green");
j3=new JRadioButton("Blue");
g.add(j1);
g.add(j2);
g.add(j3);
j1.addItemListener(this);
j2.addItemListener(this);
j3.addItemListener(this);
tf=new JTextField(20);
c1.add(j1);
c1.add(j2);
c1.add(j3);
c1.add(tf);
}
public void itemStateChanged(ItemEvent ae)
{
if(ae.getItemSelectable()==j1)
{
j1.setBackground(Color.red);
// j1.setForeground(Color.red);
tf.setText("Red");
}

else if(ae.getItemSelectable()==j2)
{
j2.setForeground(Color.green);
tf.setText("Green");
}
else if(ae.getItemSelectable()==j3)
{
j3.setForeground(Color.blue);
tf.setText("Blue");
}

}
}
==================

  ComboBox:
  -------
  constructors
  JComboBox();
  JComboBox(Vector v)
     v is a vector that initializes the combo box

items are added into the combobox by
void addItem(Object obj)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//<applet code="jcombo" width=400 height=400></applet>
public class jcombo extends JApplet implements ItemListener
{
JLabel j1;
public void init()
{
Container c1=getContentPane();
c1.setLayout(new FlowLayout());
JComboBox jc=new JComboBox();
jc.addItem("Flower4");
jc.addItem("Flower5");
jc.addItem("Flower8");
jc.addItem("Flower12");
c1.add(jc);
jc.addItemListener(this);
j1=new JLabel(new ImageIcon("Flower11.jpg"));
c1.add(j1);
}
public void itemStateChanged(ItemEvent ie)
{
String s=(String)ie.getItem();
j1.setIcon(new ImageIcon(s+".jpg"));
}
}

TabbedPane:
-------------
- it a component that appears as a group of folders in a file cabinet
constructor:
--------
JTabbedPane();

Tabs are defined via the following method
-----------
void addTab(String str,Component comp);


Steps:
------
1)create a JTabbedPane object
2)call addTab() to add a tab to the pane.
3)Repeat step 2 for each tab
4)Add the tabbed pane to the contentpane of the applet

import javax.swing.*;
/* <applet code=tabpane width=400 height=400>
</applet> */
public class tabpane extends JApplet
{
public void init()
{
JTabbedPane jtp=new JTabbedPane();
jtp.add("Cities",new city());
jtp.add("Colors",new color());
jtp.add("Flavours",new flavour());
getContentPane().add(jtp);
}
}
class city extends JPanel
{
public city()
{
JButton b1=new JButton("New York");
add(b1);
JButton b2=new JButton("USA");
add(b2);
JButton b3=new JButton("Washington");
add(b3);
JButton b4=new JButton("California");
add(b4);
}
}
class color extends JPanel
{
public color()
{
JCheckBox cb1=new JCheckBox("Red");
add(cb1);
JCheckBox cb2=new JCheckBox("Green");
add(cb2);
JCheckBox cb3=new JCheckBox("Blue");
add(cb3);
}
}
class flavour extends JPanel
{
public flavour()
{
JComboBox jcb=new JComboBox();
jcb.addItem("Pista");
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
add(jcb);
}
}


ScrollPane:
-------
constructors
------
JScrollPane(Component comp)
JScrollPane(int vsb,int hsb)
JScrollPane(Component comp,int vsb,int hsb)


hsb & vsb constants
----------
HORIZONTAL_SCROLLBAR_ALWAYS
HORIZONTAL_SCROLLBAR_AS_NEEDED
VERTICAL_SCROLLBAR_ALWAYS
VERTICAL_SCROLLBAR_AS_NEEDED

Steps:
-------
1)Create a Jcomponent object
2)Create a JScrollPane object
3)add the scrollpane to the content pane of the applet

import java.awt.*;
import javax.swing.*;
/* <applet code=scrollpane width=300 height=400>
</applet> */
public class scrollpane extends JApplet
{
public void init()
{
Container c=getContentPane();
JPanel jp=new JPanel();
jp.setLayout(new GridLayout(10,10));
int b=1;
for(int i=0;i<10;i++)
{
  for(int j=0;j<10;j++)
{
jp.add(new JButton("Button "+b));
++b;
}
 }
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
JScrollPane jsp=new JScrollPane(jp,v,h);
c.add(jsp);
}
}

Tree:
-----
   it is a component that presents a hierarchical view of data
   constructors:
   -----------
   JTree(Hashtable ht)
   JTree(Object obj[])
   JTree(TreeNode tn)
   JTree(Vector v)

   Listeners:
   ---------------------
   addTreeExpansionListener()
   removeTreeExpansionListener()

   getPathForLocation(int x,int y)- used to translate a mouse click on a specific point
   of the tree to a tree path.

   TreePath - information about a path to a particular node in a tree
   TreeNode - to obtain information about a tree node
   MutableTreeNode - used to insert and remove child nodes or change the parent node.It
   is in DefaultMutableTreeNode class
    constructor is:
    ---------
    DefaultMutableTreeNode(Object obj)

   To create a hierarchy of tree nodes the add() method is used
   syntax
   void add(MutableTreeNode child)

   Steps:
   ------
   1)Create a JTree object
   2)Create a JScrollPane object
   3)Add the tree to the scroll pane
   4)Add the scroll pane to the content pane of the applet.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;

public class treeevents extends JApplet
{
JTree tree;
JTextField jft;
public void init()
{
Container c=getContentPane();
c.setLayout(new BorderLayout());
DefaultMutableTreeNode top=new DefaultMutableTreeNode("Country");

DefaultMutableTreeNode a=new DefaultMutableTreeNode("INDIA");
top.add(a);
DefaultMutableTreeNode aa=new DefaultMutableTreeNode("SriLanka");
top.add(aa);
DefaultMutableTreeNode b=new DefaultMutableTreeNode("USA");
top.add(b);
DefaultMutableTreeNode bb=new DefaultMutableTreeNode("UK");
top.add(bb);

DefaultMutableTreeNode a1=new DefaultMutableTreeNode("Chennai");
a.add(a1);
DefaultMutableTreeNode a2=new DefaultMutableTreeNode("Delhi");
a.add(a2);
DefaultMutableTreeNode a3=new DefaultMutableTreeNode("Mumbai");
a.add(a3);

DefaultMutableTreeNode aa1=new DefaultMutableTreeNode("columbu");
aa.add(aa1);

DefaultMutableTreeNode b1=new DefaultMutableTreeNode("NewYork");
b.add(b1);
DefaultMutableTreeNode b2=new DefaultMutableTreeNode("Washington");
b.add(b2);
DefaultMutableTreeNode b3=new DefaultMutableTreeNode("Canada");
b.add(b3);

DefaultMutableTreeNode bb1=new DefaultMutableTreeNode("London");
bb.add(bb1);
DefaultMutableTreeNode abc=new DefaultMutableTreeNode("ABC");
bb1.add(abc);
DefaultMutableTreeNode bb2=new DefaultMutableTreeNode("Sheifield");
bb.add(bb2);

tree=new JTree(top);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp=new JScrollPane(tree,v,h);
c.add(jsp,BorderLayout.CENTER);
jft=new JTextField(" ",20);
c.add(jft,BorderLayout.SOUTH);
tree.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
doMouseClicked(me);
}
}
);
}
void doMouseClicked(MouseEvent me)
{
TreePath tp=tree.getPathForLocation(me.getX(),me.getY());
if(tp!=null)
jft.setText(tp.toString());
else
jft.setText("");
}
}

   Table:
   -------
   it is a component that displays rows and columns of data
   constructors:
   -------
   JTable(Object data[][],Object colHeads[]);

   Steps:
   -----
   1)Create a JTable object
   2)Create a JScrollPane
   3)Add the table to the ScrollPane
   4)Add the scrollpane to the content pane of the applet
   import java.awt.*;
   import javax.swing.*;
   /* <applet code=tabledemo width=400 height=400>
   </applet> */
   public class tabledemo extends JApplet
   {
   public void init()
   {
   Container c=getContentPane();
   final String col[]={"Name","Phone","Fax"};
   final String [][] data={{"Rama","2090567","536"},
      {"Sita","3208162","123"},
       {"Shiva","2523098","586"}};
   JTable table=new JTable(data,col);
   int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
   int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
   JScrollPane jsp=new JScrollPane(table,v,h);
   c.add(jsp);
   }
}
Creating Color Choosers
------------------------------
Methods
static Color showDialog(Component component,String title,Color initialColor)
Shows a modal color chooser dialog box.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//<applet code=colorchooser width=200 height=200></applet>
public class colorchooser extends JApplet implements ActionListener
{
JPanel jp=new JPanel();
JButton jb;
public void init()
{
Container cp=getContentPane();
jb=new JButton("Click me to change colors.");
jb.addActionListener(this);
jp.add(jb);
cp.add(jp);
}
public void actionPerformed(ActionEvent ae)
{
Color c=JColorChooser.showDialog(colorchooser.this,"Select a new color...",Color.white);
jp.setBackground(c);
}
}
Creating File Chooser
--------------------------
we can use the JFileChooser class’s showOpenDialog method to show a file chooser for finding files to open, and we can use the showSaveDialog method to show a file chooser for specifying the file name and path to use to save a file.
These methods returns the following values:
APPROVE_OPTION - Returned if the user clicks an approve button, such as Save or Open.

CANCEL_OPTION – Returned if the user clicks Cancel.

ERROR_OPTION – Returned if there was an error.

import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
public class filechooser extends JFrame implements ActionListener
{
JFileChooser chooser=new JFileChooser();
JButton jb=new JButton("Display file chooser");
JTextField jt=new JTextField(30);

public filechooser()
{
super();
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
cp.add(jb);
cp.add(jt);

jb.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
int result=chooser.showOpenDialog(null);
File fileobj=chooser.getSelectedFile();

if(result==JFileChooser.APPROVE_OPTION){
jt.setText("You choose "+fileobj.getPath());
}
else if(result==JFileChooser.CANCEL_OPTION){
jt.setText("You clicked Cancel");
}
}
public static void main(String args[])
{
JFrame f=new filechooser();

f.setBounds(200,200,400,200);

f.setVisible(true);

// f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}

import java.awt.*;
import javax.swing.*;
//<applet code=layered.class width=300 height=350></applet>
public class layered extends JApplet
{
JLabel labels[];
public void init()
{
Container cp=getContentPane();
cp.setLayout(null);

labels=new JLabel[6];

labels[0]=new JLabel("Label  0");
labels[0].setOpaque(true);
labels[0].setBorder(BorderFactory.createEtchedBorder());
cp.add(labels[0]);

labels[1]=new JLabel("Label  1");
labels[1].setOpaque(true);
labels[1].setBorder(BorderFactory.createEtchedBorder());
cp.add(labels[1]);

labels[2]=new JLabel("Label  2");
labels[2].setOpaque(true);
labels[2].setBorder(BorderFactory.createEtchedBorder());
cp.add(labels[2]);

labels[3]=new JLabel("Label  3");
labels[3].setOpaque(true);
labels[3].setBorder(BorderFactory.createEtchedBorder());
cp.add(labels[3]);

labels[4]=new JLabel("Label  4");
labels[4].setOpaque(true);
labels[4].setBorder(BorderFactory.createEtchedBorder());
cp.add(labels[4]);

labels[5]=new JLabel("Label  5");
labels[5].setOpaque(true);
labels[5].setBorder(BorderFactory.createEtchedBorder());
cp.add(labels[5]);

for(int i=0;i<6;i++){
labels[i].setBounds(40*i,40*i,100,60);
}
}
}
we might also notice that we used the setOpaque method for each label to make sure that the labels underneath.

Making Swing Components Transparent
---------------
import java.awt.*;
import javax.swing.*;
//<applet code=tarlayered.class width=300 height=350></applet>
public class tarlayered extends JApplet
{
JLabel labels[];
public void init()
{
Container cp=getContentPane();
cp.setLayout(null);

labels=new JLabel[6];

labels[0]=new JLabel("Label  0");
labels[0].setOpaque(false);
labels[0].setBorder(BorderFactory.createEtchedBorder());
cp.add(labels[0]);

labels[1]=new JLabel("Label  1");
// labels[1].setOpaque(true);
labels[1].setBorder(BorderFactory.createEtchedBorder());
cp.add(labels[1]);

labels[2]=new JLabel("Label  2");
// labels[2].setOpaque(true);
labels[2].setBorder(BorderFactory.createEtchedBorder());
cp.add(labels[2]);

labels[3]=new JLabel("Label  3");
// labels[3].setOpaque(true);
labels[3].setBorder(BorderFactory.createEtchedBorder());
cp.add(labels[3]);

labels[4]=new JLabel("Label  4");
labels[4].setOpaque(false);
labels[4].setBorder(BorderFactory.createEtchedBorder());
cp.add(labels[4]);

labels[5]=new JLabel("Label  5");
// labels[5].setOpaque(true);
labels[5].setBorder(BorderFactory.createEtchedBorder());
cp.add(labels[5]);

for(int i=0;i<6;i++){
labels[i].setBounds(40*i,40*i,100,60);
}
}
}
====================================================================
======================================================================

import javax.swing.*;
class nat
{
   public static void main(String args[])
   {
      int i,n,s=0;
      String s1=JOptionPane.showInputDialog("Enter a number");
      n=Integer.parseInt(s1);
      for(i=1;i<=n;i++)
       {
          s=s+i;
       }
      System.out.println("sum of natural:  "+s);
    }
}
================
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//<applet code="colorchooser" width=200 height-200></applet>
public class colorchooser extends JApplet implements ActionListener
{
JPanel j=new JPanel();
JButton b;
public void init()
{
b=new JButton("Click here to change the colors");
b.addActionListener(this);
j.add(b);
getContentPane().add(j);
}
public void actionPerformed(ActionEvent ae)
{
Color c=JColorChooser.showDialog(colorchooser.this,"Select a new Color",Color.pink);
j.setBackground(c);
}
}
============================
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class filechooser extends JFrame implements ActionListener
{
JFileChooser jf;
JTextArea ta;
JMenuBar jmb;
JMenu jfile;
JMenuItem fnew,fopen,fsave,fclose;
Font font;
filechooser()
{
Container ca=getContentPane();
font=new Font("Times new roman",Font.BOLD,20);
ta=new JTextArea(5,20);
ta.setFont(font);
ca.setLayout(new FlowLayout());
ca.add(ta);
jfile=new JMenu("File");
fnew=new JMenuItem("New");
fopen=new JMenuItem("Open");
fsave=new JMenuItem("Save");
fclose=new JMenuItem("Close");
jmb=new JMenuBar();
jfile.add(fnew);
jfile.add(fopen);
jfile.add(fsave);
jfile.add(fclose);
jmb.add(jfile);
setJMenuBar(jmb);
jf=new JFileChooser();
jf.setCurrentDirectory(new File("c:/"));
fnew.addActionListener(this);
fopen.addActionListener(this);
fsave.addActionListener(this);
fclose.addActionListener(this);
ca.add(new JScrollPane(ta));
setSize(300,300);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
try
{
if(ae.getActionCommand()=="New")
ta.setText("");
else if(ae.getActionCommand()=="Open")
{
jf.setDialogType(JFileChooser.OPEN_DIALOG);
jf.showOpenDialog(this);
File s=jf.getSelectedFile();
if(s!=null)
{
FileInputStream fin=new FileInputStream(s);
byte b[]=new byte[fin.available()];
fin.read(b);
ta.setText(new String(b));
fin.close();
}
}
else if(ae.getActionCommand()=="Save")
{
jf.setDialogType(JFileChooser.SAVE_DIALOG);
jf.showSaveDialog(this);
File s=jf.getSelectedFile();
if(s!=null)
{
FileOutputStream fout=new FileOutputStream(s);
fout.write(ta.getText().getBytes());
fout.close();
}
}
else
{
System.exit(0);
}
}catch(Exception e)
{System.out.println(e);}
}
public static void main(String args[])
{
filechooser fs=new filechooser();
}
}

==============
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class popupmenu extends JPanel
{
static JFrame jf;
JLabel jl;
JPopupMenu jpm;
JMenuItem jm1=new JMenuItem("Orange");
JMenuItem jm2=new JMenuItem("Apple");
JMenuItem jm3=new JMenuItem("Mango");
public popupmenu()
{
jl=new JLabel("Click mouse right button");
jpm=new JPopupMenu();
jpm.add(jm1);
jpm.add(jm2);
jpm.add(jm3);
jm1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
jl.setText("Orange");
}
});
jm2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
jl.setText("Apple");
}
});
jm3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
jl.setText("Mango");
}
});

addMouseListener(new MouseAdapter()
{
public void mouseReleased(MouseEvent me)
{
if(me.isPopupTrigger())
{
jpm.show(me.getComponent(),me.getX(),me.getY());
}
}
});
add(jl);
}
public static void main(String args[])
{
jf=new JFrame();
popupmenu pm=new popupmenu();
jf.getContentPane().add("Center",pm);
jf.setSize(200,200);
jf.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
jf.setVisible(true);
}
}
==============
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
class progress extends JFrame implements ActionListener
{
JLabel jl=new JLabel("Enter a score out of 1000");
JProgressBar bar1,bar2;
JButton done;
JTextField jft;
Container cp;
public static final int max=1000;
public progress()
{
super("ProgressBar Demo");
try
{
done=new JButton("Done");
done.addActionListener(this);
bar1=new JProgressBar(0,max);
bar1.setStringPainted(true);
bar1.setValue(max);
jft=new JTextField(10);
cp=getContentPane();
cp.setLayout(new FlowLayout());
cp.add(jl);
cp.add(jft);
cp.add(done);
cp.add(bar1);

}catch(Exception n)
{
System.out.println(n);
}
}
public void actionPerformed(ActionEvent ae)
{try{
if(ae.getSource()==done)
{
String sco=jft.getText();
int sc=Integer.parseInt(sco);
bar2=new JProgressBar(0,max);
cp.add(bar2);
bar2.setValue(sc);
bar2.setStringPainted(true);

}
}catch(NumberFormatException n)
{
System.out.println("Please Enter number");
}
}
public static void main(String args[])
{
progress jf=new progress();
jf.setSize(200,400);
jf.setVisible(true);
}
}
=================
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import java.sql.*;
class Swingemp extends Frame implements ActionListener
{
 int no;
 int sal,id;
 String name;
 JButton b1,b2,b3,b4,b5,b6;
 JLabel l1,l2,l3;
 JTextField t1,t2,t3;
 JPanel pa;
Connection c;
Statement s;
String msg=" ";
Swingemp()
{
try
{
 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
 c=DriverManager.getConnection("jdbc:odbc:deepa","sa","");
 s=c.createStatement();
}catch(Exception e)
{
System.out.println(e);
}
 pa=new JPanel();
 pa.setLayout(new GridLayout(6,1));
 b1=new JButton("Insert");
 b2=new JButton("Modify");
 b3=new JButton("Delete");
 b4=new JButton("List all");
 b5=new JButton("Exit");
 b6=new JButton("Clear All");
 l1=new JLabel("id");
 l2=new JLabel("Name");
 l3=new JLabel("Salary");
 t1=new JTextField(10);
 t2=new JTextField(20);
 t3=new JTextField(10);
 pa.add(l1);
 pa.add(t1);
 pa.add(l2);
 pa.add(t2);
 pa.add(l3);
pa.add(t3);
pa.add(b1);
pa.add(b2);
pa.add(b3);
pa.add(b4);
pa.add(b5);
pa.add(b6);
add(pa);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
 pack();
 show();
}
public void actionPerformed(ActionEvent ae)
{
try
{
 if(ae.getActionCommand()=="Insert")
{
  int id=Integer.parseInt(t1.getText());
  String name =t2.getText();
  int sal=Integer.parseInt(t3.getText());
  PreparedStatement p=c.prepareStatement("insert into emp1 values(?,?,?)");
  p.setInt(1,id);
  p.setString(2,name);
  p.setInt(3,sal);
  p.executeUpdate();
  t1.setText("");
  t2.setText("");
  t3.setText("");

}
else if(ae.getActionCommand()=="Modify")
{
        no=Integer.parseInt(t1.getText());
        ResultSet r=s.executeQuery("select * from emp1 where id="+no);
        if (r.next())
 {
          System.out.println(r.getInt(1));
          System.out.println(r.getString(2));
          System.out.println(r.getInt(3));
          name=t2.getText();
 sal=Integer.parseInt(t3.getText());
      s.executeUpdate("update emp1 set name='"+name+"',sa="+sal+" where id= "+no);
         System.out.println("Record Updated");
  }
else
 {
        System.out.println("Invalid Id Number");
 }

}
else if(ae.getActionCommand()=="Delete")
{
         id=Integer.parseInt(t1.getText());
         ResultSet r=s.executeQuery("select * from emp1 where id="+id);
if (r.next())
{
          System.out.println(r.getInt(1));
          System.out.println(r.getString(2));
          System.out.println(r.getInt(3));
          int i=s.executeUpdate("Delete From emp1 where id="+id);
        msg= "Records deleted"+i;
      }
else
{
   System.out.println("Invalid Id Number");
      }
}
else if(ae.getActionCommand()=="List all")
{
ResultSet r=s.executeQuery("select * from emp1");
         while(r.next())
         {
          System.out.println(r.getInt(1));
          System.out.println(r.getString(2));
          System.out.println(r.getInt(3));
         }
}
else if(ae.getActionCommand()=="Clear All")
{
  t1.setText("");
  t2.setText("");
  t3.setText("");
}
else if(ae.getActionCommand()=="Exit")
System.exit(0);
}catch(Exception e)
{
System.out.println(e);
}
}
 public static void main(String args[])
{
Swingemp e=new Swingemp();
}
}
===============
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;
import javax.swing.*;
import java.awt.*;
class time extends JFrame
{
private GregorianCalendar gcal;
private String timeformat;
private SimpleDateFormat formatter;
JLabel jlbl;
Font f;
public time()
{
Container c=getContentPane();
f=new Font("Times new Roman",Font.BOLD,50);
jlbl=new JLabel();
jlbl.setFont(f);
gcal=new GregorianCalendar();
timeformat="hh:mm:ss";
formatter=new SimpleDateFormat(timeformat);
gcal.add(Calendar.SECOND,1);
String timetxt=formatter.format(gcal.getTime());
c.add(jlbl);
if(jlbl!=null)
jlbl.setText(timetxt);
pack();
setVisible(true);
}
public static void main(String args[])
{
time t=new time();
}
}
===============================


No comments:

Post a Comment

Slider

Image Slider By engineerportal.blogspot.in The slide is a linking image  Welcome to Engineer Portal... #htmlcaption

Tamil Short Film Laptaap

Tamil Short Film Laptaap
Laptapp

Labels

About Blogging (1) Advance Data Structure (2) ADVANCED COMPUTER ARCHITECTURE (4) Advanced Database (4) ADVANCED DATABASE TECHNOLOGY (4) ADVANCED JAVA PROGRAMMING (1) ADVANCED OPERATING SYSTEMS (3) ADVANCED OPERATING SYSTEMS LAB (2) Agriculture and Technology (1) Analag and Digital Communication (1) Android (1) Applet (1) ARTIFICIAL INTELLIGENCE (3) aspiration 2020 (3) assignment cse (12) AT (1) AT - key (1) Attacker World (6) Basic Electrical Engineering (1) C (1) C Aptitude (20) C Program (87) C# AND .NET FRAMEWORK (11) C++ (1) Calculator (1) Chemistry (1) Cloud Computing Lab (1) Compiler Design (8) Computer Graphics Lab (31) COMPUTER GRAPHICS LABORATORY (1) COMPUTER GRAPHICS Theory (1) COMPUTER NETWORKS (3) computer organisation and architecture (1) Course Plan (2) Cricket (1) cryptography and network security (3) CS 810 (2) cse syllabus (29) Cyberoam (1) Data Mining Techniques (5) Data structures (3) DATA WAREHOUSING AND DATA MINING (4) DATABASE MANAGEMENT SYSTEMS (8) DBMS Lab (11) Design and Analysis Algorithm CS 41 (1) Design and Management of Computer Networks (2) Development in Transportation (1) Digital Principles and System Design (1) Digital Signal Processing (15) DISCRETE MATHEMATICS (1) dos box (1) Download (1) ebooks (11) electronic circuits and electron devices (1) Embedded Software Development (4) Embedded systems lab (4) Embedded systems theory (1) Engineer Portal (1) ENGINEERING ECONOMICS AND FINANCIAL ACCOUNTING (5) ENGINEERING PHYSICS (1) english lab (7) Entertainment (1) Facebook (2) fact (31) FUNDAMENTALS OF COMPUTING AND PROGRAMMING (3) Gate (3) General (3) gitlab (1) Global warming (1) GRAPH THEORY (1) Grid Computing (11) hacking (4) HIGH SPEED NETWORKS (1) Horizon (1) III year (1) INFORMATION SECURITY (1) Installation (1) INTELLECTUAL PROPERTY RIGHTS (IPR) (1) Internal Test (13) internet programming lab (20) IPL (1) Java (38) java lab (1) Java Programs (28) jdbc (1) jsp (1) KNOWLEDGE MANAGEMENT (1) lab syllabus (4) MATHEMATICS (3) Mechanical Engineering (1) Microprocessor and Microcontroller (1) Microprocessor and Microcontroller lab (11) migration (1) Mini Projects (1) MOBILE AND PERVASIVE COMPUTING (15) MOBILE COMPUTING (1) Multicore Architecute (1) MULTICORE PROGRAMMING (2) Multiprocessor Programming (2) NANOTECHNOLOGY (1) NATURAL LANGUAGE PROCESSING (1) NETWORK PROGRAMMING AND MANAGEMENT (1) NETWORKPROGNMGMNT (1) networks lab (16) News (14) Nova (1) NUMERICAL METHODS (2) Object Oriented Programming (1) ooad lab (6) ooad theory (9) OPEN SOURCE LAB (22) openGL (10) Openstack (1) Operating System CS45 (2) operating systems lab (20) other (4) parallel computing (1) parallel processing (1) PARALLEL PROGRAMMING (1) Parallel Programming Paradigms (4) Perl (1) Placement (3) Placement - Interview Questions (64) PRINCIPLES OF COMMUNICATION (1) PROBABILITY AND QUEUING THEORY (3) PROGRAMMING PARADIGMS (1) Python (3) Question Bank (1) question of the day (8) Question Paper (13) Question Paper and Answer Key (3) Railway Airport and Harbor (1) REAL TIME SYSTEMS (1) RESOURCE MANAGEMENT TECHNIQUES (1) results (3) semester 4 (5) semester 5 (1) Semester 6 (5) SERVICE ORIENTED ARCHITECTURE (1) Skill Test (1) software (1) Software Engineering (4) SOFTWARE TESTING (1) Structural Analysis (1) syllabus (34) SYSTEM SOFTWARE (1) system software lab (2) SYSTEMS MODELING AND SIMULATION (1) Tansat (2) Tansat 2011 (1) Tansat 2013 (1) TCP/IP DESIGN AND IMPLEMENTATION (1) TECHNICAL ENGLISH (7) Technology and National Security (1) Theory of Computation (3) Thought for the Day (1) Timetable (4) tips (4) Topic Notes (7) tot (1) TOTAL QUALITY MANAGEMENT (4) tutorial (8) Ubuntu LTS 12.04 (1) Unit Wise Notes (1) University Question Paper (1) UNIX INTERNALS (1) UNIX Lab (21) USER INTERFACE DESIGN (3) VIDEO TUTORIALS (1) Virtual Instrumentation Lab (1) Visual Programming (2) Web Technology (11) WIRELESS NETWORKS (1)

LinkWithin