You are on page 1of 27

JAVA PRACTICALs

/* Program to create a frame window that contains a text area. At the


bottom of window are the check buttons for formatting the text viz. bold,
italics and underline. It also contains a combo box for selecting font.
Let the user enter the text area and change the formatting of the text as
user changes these settings. The text area should be scrollable.*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class TAreaCBCDemo
{
public static void main(String args[])
{
JFrame frame1 = new TFrame();
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.show();
}
}
class TFrame extends JFrame implements ActionListener
{
JCheckBox bold,italic;
JComboBox combobox;

JTextField textfield;
JLabel label;

JTextArea TArea;
JPanel BPanel;
JScrollPane scrollpane;

public TFrame()
{
setTitle("Text Area Demo");
setSize(500,300);

BPanel = new JPanel();

bold = new JCheckBox("Bold");


italic = new JCheckBox("Italic");

combobox = new JComboBox();

combobox.addItem("Serif");
combobox.addItem("SansSerif");
combobox.addItem("Monospaced");
combobox.addItem("Dialog");
combobox.addItem("DialogInput");

textfield = new JTextField("36",10);


label = new JLabel("Font Size");

BPanel.add(label);
BPanel.add(textfield);

BPanel.add(combobox);
BPanel.add(bold);
BPanel.add(italic);

getContentPane().add(BPanel,"South");

bold.addActionListener(this);
italic.addActionListener(this);
combobox.addActionListener(this);

TArea = new JTextArea(8,40);


scrollpane = new JScrollPane(TArea);
getContentPane().add(scrollpane,"Center");

TArea.setFont(new Font("Serif",Font.PLAIN,36));
TArea.setText("I'll find a way or make one");
}
public void actionPerformed(ActionEvent e)
{
int mode = 0;
String str = String.valueOf(combobox.getSelectedItem());

int size = Integer.parseInt(textfield.getText());

mode = ((bold.isSelected() ? Font.BOLD : 0) +


(italic.isSelected() ? Font.ITALIC : 0));
TArea.setFont(new Font(str,mode,size));
}
}

=======================================================================

/* Applicatiobn that reads a series of strings and outputs only those


strings begining with the letter 'h'.The result should be displayed to a
textarea.*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class SString
{
public static void main(String args[])
{
SFrame frame = new SFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class SFrame extends JFrame implements ActionListener


{
JButton check;
JTextArea TArea,TArea1;
JPanel BPanel;
JScrollPane scrollpane,scrollpane1;
String str[];
int n;

public SFrame()
{
setTitle("Text Area Demo");
setSize(300,300);

BPanel = new JPanel();

check = new JButton("Check");

BPanel.add(check);

getContentPane().add(BPanel,"South");

check.addActionListener(this);
TArea = new JTextArea(8,40);
scrollpane = new JScrollPane(TArea);
getContentPane().add(scrollpane,"Center");

TArea1 = new JTextArea(8,40);


scrollpane1 = new JScrollPane(TArea1);
getContentPane().add(scrollpane1,"North");

n=Integer.parseInt(JOptionPane.showInputDialog("Enter the
number of Elements "));
str=new String[n];

TArea1.append("Total Strings : -");


TArea1.setLineWrap(true);
scrollpane.validate();

TArea.append("Strings starting with 'h' : -");


TArea.setLineWrap(true);
scrollpane.validate();

for(int i=0;i<n;i++)
{
str[i]=JOptionPane.showInputDialog("Enter the string");
TArea1.append(str[i]+"\t");
}
}
public void actionPerformed(ActionEvent e)
{
for(int i=0;i<n;i++)
{
String str1 = str[i];
//if(str1.endsWith(String.valueOf('h')))
if(str1.startsWith(String.valueOf('h')))
TArea.append(str[i]+" ");
}
}
}
========================================================================

/* Application program with three vertical scrollbars for red, blue,


green color,on the left side of the frame window. Each scroll bar has a
range of 0-255 Let the user adjust the position on each scrollbar display
the value of each scrollbar just below the scroll bar. Change the
background color as the bars gets adjusted. */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class VScrollBarTest
{
public static void main(String args[])
{
ScrollFrame frame = new ScrollFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class ScrollFrame extends JFrame implements AdjustmentListener


{
JLabel redLabel,greenLabel,blueLabel;
JScrollBar red,green,blue;
JPanel panel,ColorPanel;
public ScrollFrame()
{
setTitle("Scroll Bar Test Demo");
setSize(300,200);

panel = new JPanel();


ColorPanel = new JPanel();

Container contentpane = getContentPane();


panel.setLayout(new GridLayout(6,1));
contentpane.add(panel,"West");
ColorPanel.setBackground(new Color(0,0,0));
contentpane.add(ColorPanel,"Center");

panel.add(red = new
JScrollBar(Adjustable.VERTICAL,0,0,0,255));
panel.add(redLabel=new JLabel("Red 0"));

panel.add(green = new
JScrollBar(Adjustable.VERTICAL,0,0,0,255));
panel.add(greenLabel=new JLabel("Green 0"));

panel.add(blue = new
JScrollBar(Adjustable.VERTICAL,0,0,0,255));
panel.add(blueLabel=new JLabel("Blue 0"));

red.setBlockIncrement(16);
green.setBlockIncrement(16);
blue.setBlockIncrement(16);

red.addAdjustmentListener(this);
green.addAdjustmentListener(this);
blue.addAdjustmentListener(this);
}

public void adjustmentValueChanged(AdjustmentEvent e)


{
redLabel.setText("Red :- "+ red.getValue());
greenLabel.setText("Green :- " + green.getValue());
blueLabel.setText("Blue :- " + blue.getValue());
ColorPanel.setBackground(new Color(red.getValue(),

green.getValue(),blue.getValue()));
ColorPanel.repaint();
}
}

====================================================================

/* Program that allows you to enter an integer number using input dialog
box and check whether the entered number is Prime or Not. */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Prime
{
public static void main(String args[])
{
int
result=Integer.parseInt(JOptionPane.showInputDialog("Enter the Number"));
for(int i=2;i<result;i++)
{
if((result%i)==0)
{
System.out.println(result + " not a Prime
Number");
System.exit(0);
}
}
System.out.println(result + " is a Prime Number");
System.exit(0);
}
}
=====================================================================

/* Program to generate first 20 terms of Fibonacci series */

import java.lang.*;
import java.io.*;

class Fibo
{
public static void main(String args[])
{
int a=0,b=1,c=0;
try
{
System.out.println("First 20 terms Fibonacci Series is -
");
System.out.print(a + "\t" + b + "\t");
for(int i=3;i<=20;i++)
{
c=a+b;
System.out.print(c + "\t");
a=b;
b=c;
}
System.out.println("\n");
}
catch(Exception e)
{}
}
}

======================================================================
/* Program to demostrate atleast 5 file management functions. For each
function use a seperate menu item. Display the result in the window. */
import javax.swing.*;
import javax.swing.filechooser.*;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

class FileMgmt
{
public static void main(String args[])
{
FFrame frame = new FFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class FFrame extends JFrame implements ActionListener
{
JTextField TField;
JMenuBar mb;
JMenu file;
JMenuItem isfile,isdir,path,makedir,exit1;
public FFrame()
{
setSize(500,100);
setTitle("File management");

TField = new JTextField(25);

getContentPane().add(TField);

mb = new JMenuBar();
file = new JMenu("File");
mb.add(file);

isfile = new JMenuItem("Is a file ");


isfile.addActionListener(this);
file.add(isfile);

isdir = new JMenuItem("Is a Directory ");


isdir.addActionListener(this);
file.add(isdir);

path = new JMenuItem("Path ");


path.addActionListener(this);
file.add(path);

makedir = new JMenuItem("Make Directory ");


makedir.addActionListener(this);
file.add(makedir);

exit1 = new JMenuItem("Exit");


exit1.addActionListener(this);
file.add(exit1);

setJMenuBar(mb);
}

public void actionPerformed(ActionEvent e)


{
Object source = e.getSource();
JFileChooser ch;

TField.setFont(new Font("Arial",Font.BOLD,26));
if(source==exit1)
System.exit(0);

String s = JOptionPane.showInputDialog(this,"Enter the File


name :- " ,"test",3);

File f = new File(s);

if(source == isfile)
{
if(f.exists())
{TField.setText("File Exist's\n");
ch=new JFileChooser();
ch.showOpenDialog(this);}
else
TField.setText("File does not exist");
}
else if(source == isdir)
{
if(f.isDirectory())
TField.setText("Directory Exist's");
else
TField.setText("Directory Not Present");
}
else if(source==path)
{
if(f.exists() && f.isFile())
TField.setText("Path of a File is :->
"+f.getAbsolutePath());
}
else if(source == makedir)
{
if(f.mkdir())
TField.setText("Directory created ");
else
TField.setText("Directory not created ");
}
}
}

======================================================================
/* Program that allows you to select a shape from a combo box.
Draw the selected shape 20 times with ramdom locations and ramdom color.
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//import java.util.*;

class DShapes
{
public static void main(String args[])
{
DFrame frame = new DFrame();
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class DFrame extends JFrame implements ActionListener


{
JComboBox combobox;
Toolkit kit;
Dimension size;

public DFrame()
{
setTitle("Draw Shapes");
setSize(600,300);
combobox = new JComboBox();

kit = Toolkit.getDefaultToolkit();
size = kit.getScreenSize();

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

combobox.addItem("Rectangle");
combobox.addItem("Circle");
combobox.addItem("Line");
combobox.addItem("Ellipse");
combobox.addItem("Oval");

combobox.addActionListener(this);
getContentPane().add(combobox,"South");
}

public void actionPerformed(ActionEvent e)


{

int x,y;
String str = String.valueOf(combobox.getSelectedItem());
Graphics g = getGraphics();
if(str.equals("Rectangle"))
{
for(int i=0;i<20;i++)
{
x = (int)(Math.random() * size.width/2);
y = (int)(Math.random() * size.height/2);
g.setColor(new Color((int)(Math.random() *
255),(int)(Math.random() * 255),(int)(Math.random() * 255)));
g.drawRect(x,y,x+10,y+10);
}
}
else if(str.equals("Circle"))
{
for(int i=0;i<20;i++)
{
x = (int)(Math.random() * size.width/2);
y = (int)(Math.random() * size.height/2);
g.setColor(new Color((int)(Math.random() *
255),(int)(Math.random() * 255),(int)(Math.random() * 255)));
g.drawOval(x,y,x+10,y+10);
}
}
else if(str.equals("Line"))
{
for(int i=0;i<20;i++)
{
x = (int)(Math.random() * size.width/2);
y = (int)(Math.random() * size.height/2);
g.setColor(new Color((int)(Math.random() *
255),(int)(Math.random() * 255),(int)(Math.random() * 255)));
g.drawLine(x,y,x+10,y+10);
}
}
else if(str.equals("Ellipse"))
{
for(int i=0;i<20;i++)
{
x = (int)(Math.random() * size.width/2);
y = (int)(Math.random() * size.height/2);
g.setColor(new Color((int)(Math.random() *
255),(int)(Math.random() * 255),(int)(Math.random() * 255)));
g.drawOval(x,y,x+10,y+20);
}
}
else
{
for(int i=0;i<20;i++)
{
x = (int)(Math.random() * size.width/2);
y = (int)(Math.random() * size.height/2);
g.setColor(new Color((int)(Math.random() *
255),(int)(Math.random() * 255),(int)(Math.random() * 255)));
g.drawOval(x,y,x+20,y+10);
}
}
}
}
======================================================================
/* progrma for calculator */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator extends JApplet


{
public void init()
{
getContentPane().add(new CalculatorPanel());
}
}

class CalculatorPanel extends JPanel implements ActionL istener


{
JTextField display;
JButton clear;
double args = 0.0;
String op = "=";
boolean start = true;
JPanel p,panel;
public CalculatorPanel()
{
setLayout(new BorderLayout());

display = new JTextField(12);


display.setEditable(false);
display.setBackground(Color.white);

clear = new JButton("C");

panel = new JPanel();


panel.add(display);
panel.add(clear);

add(panel,"North");

p = new JPanel();
p.setLayout(new GridLayout(4,4));

String buttons = "789/456*123-0.=+";


for(int i=0;i<buttons.length();i++)
addButtons(buttons.substring(i,i+1));
add(p,"Center");

clear.addActionListener(this);
}

void addButtons(String s)
{
JButton b = new JButton(s);
p.add(b);
b.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{
String s = e.getActionCommand();
if(s.equals("C"))
display.setText("");
else
{
if(s.charAt(0) >= '0' && s.charAt(0) <= '9' ||
s.equals("."))
{
if(start)
display.setText(s);
else
display.setText(display.getText()+s);
start = false;
}
else
{
if(start)
{
if(s.equals("-"))
{
display.setText(s);
start = false;
}
else
op = s;
}
else
{

calculate(Double.parseDouble(display.getText()));
op = s;
start = true;
}
}
}
}
void calculate(double x)
{
if(op.equals("+"))
args += x;
if(op.equals("-"))
args -= x;
if(op.equals("*"))
args *= x;
if(op.equals("/"))
args /= x;
if(op.equals("="))
args = x;
display.setText(""+args);
}
}

=======================================================================
/* Program that draws a rectangle by dragging the mouse on the
application window.The upper left coordinate should be the location where
you press the mouse button and lower right coordinate should be the
location where you release the mouse button. Also display volume of the
rectangle in a JLabel.*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class RDraw
{
public static void main(String args[])
{
RFrame frame = new RFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class RFrame extends JFrame
{
public RFrame()
{
setTitle("Rectangle Draw");
setSize(300,300);
RPanel panel = new RPanel();
getContentPane().add(panel);
}
}
class RPanel extends JPanel implements MouseListener
{
int x=0,y=0,x1=0,y1=0;
JLabel label;
public RPanel()
{
label=new JLabel("");
add(label,"South");

addMouseListener(this);
}
public void mousePressed(MouseEvent e)
{
x=e.getX();
y=e.getY();
}
public void mouseReleased(MouseEvent e)
{
x1=e.getX();
y1=e.getY();
repaint();
}
public void mouseClicked(MouseEvent e)
{}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawRect(x,y,x1-x,y1-y);

String str=String.valueOf((x1-x)*(y1-y));
str="Area of Rectangle is " + str;
label.setText(str);
}
}

======================================================================
/* Program that randomly draw characters in different font sizes and
colors */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

class RCharacters
{
public static void main(String args[])
{
DFrame frame = new DFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class DFrame extends JFrame


{
public DFrame()
{
setTitle("Random Characters");
setSize(200,200);

DPanel panel = new DPanel();


getContentPane().add(panel);
}
}
class DPanel extends JPanel implements ActionListener
{
JButton random;
Toolkit kit;
Dimension size;
public DPanel()
{
kit = Toolkit.getDefaultToolkit();
size = kit.getScreenSize();

random = new JButton("Random");


add(random,"South");
random.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{
draw();
}
void draw()
{
int x,y,s=0;
String str="Amol A Kinage";
Graphics g=getGraphics();

x = (int)(Math.random() * size.width);
y = (int)(Math.random() * size.height);

s=(int)(Math.random() * 60);
g.setFont(new Font("SansSerif",0,s));
g.setColor(new
Color((int)(Math.random()*255),(int)(Math.random()*255),( int)(Math.random
()*255)));
g.drawString(str,x,y);
}
}

=======================================================================
/* Program to create a frame window with two buttons- Start and Stop.
Whenever user clicks on start button a bouncing rectangle appears on the
screen it bounces in vertical direction for 10 times. Whenever user
clicks on the stop button it stops all bouncing rectangles.*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class BounceRect
{
public static void main(String args[])
{
BFrame frame = new BFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class BFrame extends JFrame implements ActionListener


{
JButton start,stop;
JPanel panel,canvas;

public BFrame()
{
setTitle("Bouncing Rectangle");
setSize(200,200);

panel = new JPanel();


canvas = new JPanel();

start = new JButton("Start");


stop = new JButton("Stop");

panel.add(start);
panel.add(stop);

start.addActionListener(this);
stop.addActionListener(this);

getContentPane().add(panel,"South");
getContentPane().add(canvas,"Center");
}
public void actionPerformed(ActionEvent e)
{
Object obj = e.getSource();
if(obj==start)
{
Rect r = new Rect(canvas);
r.bounce();
}
else
{
System.exit(0);
}
}
}

class Rect
{
int x=50,y=0;
static final int XSIZE=10;
static final int YSIZE=10;
int dx=2,dy=2;
JPanel RPanel;

public Rect(JPanel canvas)


{
RPanel=canvas;
}
public void draw()
{
Graphics g = RPanel.getGraphics();
g.fillRect(x, y, XSIZE, YSIZE);
g.dispose();
}
public void move()
{
Graphics g = RPanel.getGraphics();
g.setXORMode(RPanel.getBackground());

g.fillRect(x, y, XSIZE, YSIZE);

//x += dx;
y += dy;

Dimension d = RPanel.getSize();
if (x < 0)
{
x = 0;
//dx = -dx;
}
if (x + XSIZE >= d.width)
{
x = d.width - XSIZE;
dx = -dx;
}
if (y < 0)
{
y = 0;
dy = -dy;
}
if (y + YSIZE >= d.height)
{
y = d.height - YSIZE;
dy = -dy;
}
g.fillRect(x, y, XSIZE, YSIZE);

g.dispose();
}
public void bounce()
{
draw();
for (int i = 1; i <= 1000; i++)
{
move();
try
{
Thread.sleep(5);
}
catch(InterruptedException e) {}
}
}
}

=======================================================================
/* Program that include a TextField and Three Buttons. When you press
each button make some different text to appear in the text field.*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class TextBut
{
public static void main(String args[])
{
BFrame frame = new BFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class BFrame extends JFrame implements ActionListener
{
JButton FText,SText,TText;
JTextField TField;
JPanel panel;
public BFrame()
{
setTitle("TextField and Button Demo");
setSize(300,100);

panel=new JPanel();

FText=new JButton("First");
SText=new JButton("Second");
TText=new JButton("Third");

panel.add(FText);
panel.add(SText);
panel.add(TText);

getContentPane().add(panel,"South");

TField=new JTextField(25);
getContentPane().add(TField,"Center");

FText.addActionListener(this);
SText.addActionListener(this);
TText.addActionListener(this);
TField.setText("An Apple a day, keeps the Doctor away");
}
public void actionPerformed(ActionEvent e)
{
Object obj=e.getSource();
if(obj==FText)
TField.setText("Work is Workship");
if(obj==SText)
TField.setText("I will find my way, otherwise I will
make one");
if(obj==TText)
TField.setText("Health is Wealth");
}
}
=======================================================================

/* Program that draws a circle. Provide a group of radio buttons at the


bottom of the window that lists :- Red, Black, Magenta, Blue, Green and
Yellow. When a radio Button is selected circle should get filled with
that color.*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class RCircle
{
public static void main(String[] args)
{
RadioButtonFrame frame = new RadioButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class RadioButtonFrame extends JFrame implements ActionListener


{
JPanel buttonPanel;
JRadioButton red,black,magenta,blue,green,yellow;
JPanel drawPanel;

public RadioButtonFrame()
{
setTitle("RadioButtonTest");
setSize(600,300);

Container contentPane = getContentPane();


ButtonGroup bg=new ButtonGroup();

red=new JRadioButton("Red",true);
black=new JRadioButton("Black");
magenta=new JRadioButton("Magenta");
blue=new JRadioButton("Blue");
green=new JRadioButton("Green");
yellow=new JRadioButton("Yellow");

buttonPanel = new JPanel();

bg.add(red);
bg.add(black);
bg.add(magenta);
bg.add(blue);
bg.add(green);
bg.add(yellow);

buttonPanel.add(red);
buttonPanel.add(black);
buttonPanel.add(magenta);
buttonPanel.add(blue);
buttonPanel.add(green);
buttonPanel.add(yellow);

contentPane.add(buttonPanel,"South");

drawPanel = new JPanel();


contentPane.add(drawPanel,"Center");

red.addActionListener(this);
black.addActionListener(this);
magenta.addActionListener(this);
blue.addActionListener(this);
green.addActionListener(this);
yellow.addActionListener(this);
}

public void actionPerformed(ActionEvent evt)


{
Object source=evt.getSource();
Graphics g = drawPanel.getGraphics();
if(source==red)
g.setColor(Color.red);
else if(source==black)
g.setColor(Color.black);
else if(source==magenta)
g.setColor(Color.magenta);
else if(source==blue)
g.setColor(Color.blue);
else if(source==green)
g.setColor(Color.green);
else
g.setColor(Color.yellow);
g.fillOval(200,50,150,150);
g.dispose();
}
}
=======================================================================
/*Application program in Java that draws a circle at first mouse click,
a rectangle at second, and a line at third mouse click. The application
window get cleared at fourth mouse click.*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class RMShapes
{
public static void main(String args[])
{
RFrame frame = new RFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class RFrame extends JFrame


{
static int count=0;
public RFrame()
{
setTitle("RM Test");
setSize(300,300);
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
count++;
Graphics g = getGraphics();
if(count==3)

g.drawLine(e.getX(),e.getY(),e.getX()+20,e.getY()+20);
else if(count==2)

g.drawRect(e.getX(),e.getY(),e.getX()+20,e.getY()+20);
else if(count==1)

g.drawOval(e.getX(),e.getY(),e.getX()+20,e.getY()+20);
else
{
count=0;
repaint();
}
}
});
}
}

=======================================================================
/* Program that displays a popup menu with menuitems having color as -
Red, Green and Blue. Based on the menu item selected by the user change
the color of the panel.*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class PopMenu
{
public static void main(String[] args)
{
PFrame frame = new PFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class PFrame extends JFrame implements ActionListener


{
JMenuItem red,blue,green;
JPopupMenu popup;
JPanel panel;

public PFrame()
{
setTitle("MenuTest");
setSize(400, 400);

panel = new JPanel();

popup = new JPopupMenu();

red = new JMenuItem("Red");


blue = new JMenuItem("Blue");
green = new JMenuItem("Green");

popup.add(red);
red.addActionListener(this);
popup.addSeparator();

popup.add(blue);
blue.addActionListener(this);
popup.addSeparator();

popup.add(green);
green.addActionListener(this);

getContentPane().add(panel,"Center");

panel.addMouseListener(new MouseAdapter()
{
public void mouseReleased(MouseEvent e)
{
if(e.isPopupTrigger())

popup.show(e.getComponent(),e.getX(),e.getY());
}
});

}
public void actionPerformed(ActionEvent e)
{
Object obj = e.getSource();
if(obj==red)
panel.setBackground(Color.red);
if(obj==blue)
panel.setBackground(Color.blue);
if(obj==green)
panel.setBackground(Color.green);
}
}

=======================================================================
/* Program that takes string from user and checks whether the inputted
string is palimdrome or not.*/

import java.lang.*;
import javax.swing.*;
/**********************************************************
To check whether the given String is Palimdrome or not.
**********************************************************/

class PaliStr
{
public static void main(String args[])
{
String str;
String str1="";
int l,i;
str=JOptionPane.showInputDialog(null,"Enter the String");
l=str.length();
for(i=l-1;i>=0;i--)
str1=str1+str.charAt(i);
if(str.equals(str1))
JOptionPane.showMessageDialog(null,"Palimdrome");
else
JOptionPane.showMessageDialog(null,"Not a Palimdrome");
}
}

/**********************************************************
To check whether the given number is Palimdrome or not.
**********************************************************/
/*
class PaliStr
{
public static void main(String args[])
{
String str,str1;
int n,no,res;
str1="";
str=JOptionPane.showInputDialog(null,"Enter the Number");
n = Integer.parseInt(str);
while(n>0)
{
str1=str1+(n%10);
n=n/10;
}
if(str.equals(str1))
JOptionPane.showMessageDialog(null,"Palimdrome");
else
JOptionPane.showMessageDialog(null,"Not a Palimdrome");
}
}
*/
/**********************************************************************
To check whether the given number is Palimdrome or not using reverse
function.
**********************************************************************/
/*
class PaliStr
{
public static void main(String args[])
{
String str,str1;
str=JOptionPane.showInputDialog(null,"Enter the String");
str1=str;
StringBuffer str2=new StringBuffer(str);
str2.reverse();
if(str.equals(str2))
JOptionPane.showMessageDialog(null,"equal");
else
JOptionPane.showMessageDialog(null,"not equal");
}
}
*/
=======================================================================
/* Program that draws a shapes by dragging the mouse on the application
window.The upper left coordinate should be the location where you press
the mouse button and lower right coordinate should be the location where
you release the mouse button. The shapes to draw is determine by using
keys-
C - to draw Circle,
O - to draw Oval
R - to draw Rectangle
L - to draw a Line
The initial shape should default to Circle.*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class RKDraw
{
public static void main(String args[])
{
RFrame frame = new RFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class RFrame extends JFrame implements MouseListener,KeyListener


{
int x=0,y=0,x1=0,y1=0;
char keychar='c';
String msg="Pressed only C - to draw Circle, O - to draw Oval, R -
to draw Rectangle, L - to draw a Line";
public RFrame()
{
setTitle("Rectangle Draw");
setSize(300,300);
JPanel panel = new JPanel();
getContentPane().add(panel);

addMouseListener(this);
addKeyListener(this);
JOptionPane.showMessageDialog(this,msg,"Shapes",1);
}
public void mousePressed(MouseEvent e)
{
x=e.getX();
y=e.getY();
}
public void mouseReleased(MouseEvent e)
{
x1=e.getX();
y1=e.getY();
draw();
}
public void mouseClicked(MouseEvent e)
{}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void keyTyped(KeyEvent e)
{
keychar=e.getKeyChar();
}
public void keyReleased(KeyEvent e)
{}
public void keyPressed(KeyEvent e)
{}
public void draw()
{
Graphics g = getGraphics();
keychar=Character.toLowerCase(keychar);

if(keychar=='c')
g.drawOval(x,y,x1-x,x1-x);
else if(keychar=='o')
g.drawOval(x,y,x1-x,y1-y);
else if(keychar=='r')
g.drawRect(x,y,x1-x,x1-x);
else if(keychar=='l')
g.drawLine(x,y,x1,y1);
else
JOptionPane.showMessageDialog(this,msg,"Warning",2);

keychar='\0';
}

}
=======================================================================
/* Program that displays an input dialog box displaying choices as
follows-
Draw Lines
Draw rectangles
Draw Circles
Draw the shapes 10 times with ramdom locations with ramdom dimensions and
color as per the integer value entered by the user. If user enters number
other than display the error message. */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

class LROShapes
{
public static void main(String args[])
{
DFrame frame = new DFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class DFrame extends JFrame


{
public DFrame()
{
setTitle("Draw Shapes");
setSize(600,300);

DPanel panel = new DPanel();


getContentPane().add(panel);
}
}
class DPanel extends JPanel
{
Toolkit kit;
Dimension size;
int choice=0;
int rcolor=0,gcolor=0,bcolor=0;
int x,y;
String msg="To Draw give option as :- 1. Line, 2. Rectangle, 3.
Ovals";

public DPanel()
{
kit = Toolkit.getDefaultToolkit();
size = kit.getScreenSize();

choice =
Integer.parseInt(JOptionPane.showInputDialog(this,msg));

rcolor =
Integer.parseInt(JOptionPane.showInputDialog(this,"Enter Red Value"));
gcolor =
Integer.parseInt(JOptionPane.showInputDialog(this,"Enter Green Value"));
bcolor =
Integer.parseInt(JOptionPane.showInputDialog(this,"Enter Blue Value"));
if(rcolor>255)
rcolor=255;
if(bcolor>255)
bcolor=255;
if(gcolor>255)
gcolor=255;
}

public void paintComponent(Graphics g)


{
super.paintComponent(g);
g.setColor(new Color(rcolor,gcolor,bcolor));
if(choice==2)
{
for(int i=0;i<10;i++)
{
x = (int)(Math.random() * size.width/2);
y = (int)(Math.random() * size.height/2);
g.drawRect(x,y,x+10,y+10);
x=0;
y=0;
}
}
else if(choice==3)
{
for(int i=0;i<10;i++)
{
x = (int)(Math.random() * size.width/2);
y = (int)(Math.random() * size.height/2);
g.drawOval(x,y,x+10,x+10);
x=0;
y=0;
}
}
else if(choice==1)
{
for(int i=0;i<10;i++)
{
x = (int)(Math.random() * size.width/2);
y = (int)(Math.random() * size.height/2);
g.drawLine(x,y,x+50,y+50);
x=0;
y=0;
}
}
else
{
JOptionPane.showMessageDialog(this,"Wrong Choice");
}
}
}

=======================================================================
/* Create an Applet, add a password field to it. When user types in the
password provide a message to the user showing success or failure about
guessing the password. Message should be displayed in the Message Box.*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JOptionPane;
public class CPassWordDemo extends JApplet implements KeyListener
{
JPasswordField pf;
JLabel l1;
JPanel p;
String a,b,t;
public void init()
{
setLayout(new FlowLayout());
setSize(300,300);
a="ram";
b="omsai";
pf=new JPasswordField(10);
l1=new JLabel("Password");
p=new JPanel();
p.add(l1);
p.add(pf);
add(p);
pf.setEchoChar('*');
pf.addKeyListener(this);

}
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode()==ke.VK_ENTER)
{
t=new String(pf.getPassword());
System.out.print(" "+t);
if(t.equals(a)||t.equals(b))
JOptionPane.showMessageDialog(null,"Success");
else

JOptionPane.showMessageDialog(null,"Failure....Hint->abc ");
}
}
public void keyReleased(KeyEvent ke)
{

}
public void keyTyped(KeyEvent ke)
{

}
public void paint(Graphics g)
{

}
}

/* HTML File
-------------------------------
<HTML>
<APPLET>
<APPLET CODE="myapplet1.class" WIDTH=300 HEIGHT=300>
</APPLET>
*/

=======================================================================
/*Program to store the employee information in the Employee table created
in MSACCESS. Create a data entry form for getting employee information
from user and when user clicks on insert button save the record to the
Employee table. Provide clear Button to clear all the textFields on the
dataEntry form.*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;

class JDBCMgmt
{
public static void main(String args[])
{
CFrame frame = new CFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class CFrame extends JFrame implements ActionListener


{
JButton insert,update,delete,clear;
JLabel lbl1,lbl2,lbl3,lbl4;
JTextField EmpNo,EmpName,Department,Salary;

JPanel panel,DPanel;

public CFrame()
{
insert = new JButton("Insert");
update = new JButton("Update");
delete = new JButton("Delete");
clear = new JButton("Clear");

lbl1 = new JLabel("Employee No ");


lbl2 = new JLabel("Employee Name ");
lbl3 = new JLabel("Department ");
lbl4 = new JLabel("Salary ");

EmpNo = new JTextField(5);


EmpName = new JTextField(15);
Department = new JTextField(25);
Salary = new JTextField(5);

panel = new JPanel();


DPanel = new JPanel();

getContentPane().add(panel,"South");
getContentPane().add(DPanel,"Center");

DPanel.setLayout(new GridLayout(4,2));

DPanel.add(lbl1);
DPanel.add(EmpNo);
DPanel.add(lbl2);
DPanel.add(EmpName);
DPanel.add(lbl3);
DPanel.add(Department);
DPanel.add(lbl4);
DPanel.add(Salary);

panel.add(insert);
panel.add(update);
panel.add(delete);
panel.add(clear);

insert.addActionListener(this);
update.addActionListener(this);
delete.addActionListener(this);
clear.addActionListener(this);

setSize(300,200);
setTitle("Employee Details");

}
public void actionPerformed(ActionEvent e)
{
Object obj = e.getSource();
PreparedStatement ps;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:Emp","","");

if(obj == insert)
{
ps = con.prepareStatement("insert into
Emp(EmpNo,EmpName,Department,Salary) values(?,?,?,?)");
ps.setString(1,EmpNo.getText());
ps.setString(2,EmpName.getText());
ps.setString(3,Department.getText());
ps.setString(4,Salary.getText());
ps.executeUpdate();

JOptionPane.showMessageDialog(null,"Record
Inserted");
}
else if(obj == update)
{
ps = con.prepareStatement("update Emp set EmpName
= ?,Department = ?, Salary = ? where EmpNo = ?");
ps.setString(1,EmpName.getText());
ps.setString(2,Department.getText());
ps.setString(3,Salary.getText());
ps.setString(4,EmpNo.getText());
ps.executeUpdate();

JOptionPane.showMessageDialog(null,"Record
Updated");
}
else if(obj == delete)
{
ps = con.prepareStatement("delete from Emp where
EmpNo = ?");
ps.setString(1,EmpNo.getText());
ps.executeUpdate();

JOptionPane.showMessageDialog(null,"Record
Deleted");
}
else
{
EmpNo.setText("");
EmpName.setText("");
Department.setText("");
Salary.setText("");
}

con.close();
}
catch(ClassNotFoundException e1)
{
}
catch(SQLException e2)
{
}
}
}

=======================================================================
/* Program that allows an integer containing 0's and 1's as input and
prints its decimal equivalent. */

import java.lang.*;
import java.io.*;

class BinToDec
{
public static void main(String args[])
{
int n,no,i,x;
int dec=0;
try
{
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Binary Number : - ");
String str = in.readLine();
no=str.length();
for(i=0;i<str.length();i++)
{
x=--no;
n=Integer.parseInt(str.substring(i,i+1));
dec += n*Math.pow(2,x);
}
System.out.println(dec);
}
catch(Exception e)
{}
}
}

=======================================================================
/* Program that displays a menu with menuitems having color as - Red,
Green and Blue. Based on the menu item selected by the user change the
color of the panel. Also check mark should appear on the selected menu
item. If more than one menu item is selected then the color of the panel
should be the combination of the selected items. */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class CMenu
{
public static void main(String[] args)
{
CFrame frame = new CFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class CFrame extends JFrame implements ActionListener


{
JCheckBoxMenuItem red,blue,green;
JMenu color;
JMenuBar mbar;
JPanel panel;

public CFrame()
{
setTitle("MenuTest");
setSize(400, 400);

panel = new JPanel();

mbar=new JMenuBar();
setJMenuBar(mbar);

color = new JMenu("Colour");

red = new JCheckBoxMenuItem("Red");


blue = new JCheckBoxMenuItem("Blue");
green = new JCheckBoxMenuItem("Green");

color.add(red);
red.addActionListener(this);
color.addSeparator();

color.add(blue);
blue.addActionListener(this);
color.addSeparator();

color.add(green);
green.addActionListener(this);

mbar.add(color);

getContentPane().add(panel,"Center");

}
public void actionPerformed(ActionEvent e)
{
int rmode,bmode,gmode;
rmode=(red.isSelected()?255:0);
bmode=(blue.isSelected()?255:0);
gmode=(green.isSelected()?255:0);
panel.setBackground(new Color(rmode,gmode,bmode));

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

You might also like