" + insert successfully + "
");Wednesday, December 30, 2009
Hibernate Web Application in NetBeans
Monday, June 29, 2009
AbstractDemo
abstract void search();
//no body of statements in abstract method
void print(){
System.out.println("Non Abstract Method");
}
}
class B3 extends A3{
void search(){
System.out.println("Binary Search");
System.out.println("Linear Search");
}
}
class AbstractDemo{
public static void main(String[] a){
B3 b2=new B3();
b2.search();
b2.print();
A3 a2;
B3 b3=new B3();
a2=b3;
a2.print();
}
}
SimpleAboutDialog
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SimpleAboutDialog extends JDialog {
public SimpleAboutDialog(JFrame parent) {
super(parent, "About Dialog", true);
Box b = Box.createVerticalBox();
b.add(Box.createGlue());
b.add(new JLabel("Java source code, product and article"));
b.add(new JLabel("By Java source and support"));
b.add(new JLabel("At www.java2s.com"));
b.add(Box.createGlue());
getContentPane().add(b, "Center");
JPanel p2 = new JPanel();
JButton ok = new JButton("Ok");
p2.add(ok);
getContentPane().add(p2, "South");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setVisible(false);
}
});
setSize(250, 150);
}
public static void main(String[] args) {
JDialog f = new SimpleAboutDialog(new JFrame());
f.show();
}
}
FramewithComponents
import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class FramewithComponents extends JFrame {
public FramewithComponents() {
super("JLayeredPane Demo");
setSize(256, 256);
JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.setOpaque(false);
JLabel label1 = new JLabel("Username:");
label1.setForeground(Color.white);
content.add(label1);
JTextField field = new JTextField(15);
content.add(field);
JLabel label2 = new JLabel("Password:");
label2.setForeground(Color.white);
content.add(label2);
JPasswordField fieldPass = new JPasswordField(15);
content.add(fieldPass);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(content);
((JPanel) getContentPane()).setOpaque(false);
ImageIcon earth = new ImageIcon("1.jpg");
JLabel backlabel = new JLabel(earth);
getLayeredPane().add(backlabel, new Integer(Integer.MIN_VALUE));
backlabel.setBounds(0, 0, earth.getIconWidth(), earth.getIconHeight());
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(l);
setVisible(true);
}
public static void main(String[] args) {
new FramewithComponents();
}
}
CenteredFrame
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class CenteredFrame extends JFrame {
public CenteredFrame() {
setTitle("CenteredFrame");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
setSize(screenWidth / 2, screenHeight / 2);
setLocation(screenWidth / 4, screenHeight / 4);
}
public static void main(String[] args) {
JFrame frame = new CenteredFrame();
frame.show();
}
}
Errordialogs
import javax.swing.JPanel;
public class Errordialogs extends JPanel {
public static void main(String[] a) {
JOptionPane jop = new JOptionPane();
JOptionPane.showMessageDialog(jop, "Press Ok to exit our " +
"from the error diaolag box");
JOptionPane.showConfirmDialog(null, "Click one",
"Click one", JOptionPane.YES_NO_OPTION);
}
}
SimpleScreenManager
import javax.swing.JFrame;
/**
The SimpleScreenManager class manages initializing and
displaying full screen graphics modes.
*/
public class SimpleScreenManager {
private GraphicsDevice device;
/**
Creates a new SimpleScreenManager object.
*/
public SimpleScreenManager() {
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
device = environment.getDefaultScreenDevice();
}
/**
Enters full screen mode and changes the display mode.
*/
public void setFullScreen(DisplayMode displayMode,
JFrame window)
{
window.setUndecorated(true);
window.setResizable(false);
device.setFullScreenWindow(window);
if (displayMode != null &&
device.isDisplayChangeSupported())
{
try {
device.setDisplayMode(displayMode);
}
catch (IllegalArgumentException ex) {
// ignore - illegal mode for this device
}
}
}
/**
Returns the window currently used in full screen mode.
*/
public Window getFullScreenWindow() {
return device.getFullScreenWindow();
}
/**
Restores the screen's display mode.
*/
public void restoreScreen() {
Window window = device.getFullScreenWindow();
if (window != null) {
window.dispose();
}
device.setFullScreenWindow(null);
}
}
FullScreenTest
import javax.swing.JFrame;
public class FullScreenTest extends JFrame {
public static void main(String[] args) {
DisplayMode displayMode;
if (args.length == 3) {
displayMode = new DisplayMode(
Integer.parseInt(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2]),
DisplayMode.REFRESH_RATE_UNKNOWN);
}
else {
displayMode = new DisplayMode(800, 600, 16,
DisplayMode.REFRESH_RATE_UNKNOWN);
}
FullScreenTest test = new FullScreenTest();
test.run(displayMode);
}
private static final long DEMO_TIME = 5000;
public void run(DisplayMode displayMode) {
setBackground(Color.blue);
setForeground(Color.white);
setFont(new Font("Dialog", Font.PLAIN, 24));
SimpleScreenManager screen = new SimpleScreenManager();
try {
screen.setFullScreen(displayMode, this);
try {
Thread.sleep(DEMO_TIME);
}
catch (InterruptedException ex) { }
}
finally {
screen.restoreScreen();
}
}
public void paint(Graphics g) {
g.drawString("Hello World!", 20, 50);
}
}
java FullScreenTest 400 500 100
ImagePanel
private Image img;
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null),
img.getHeight(null));
setSize(size);
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setLayout(null);
}
}
Tuesday, June 9, 2009
Sample Login And Validation
import java.awt.event.*;
import javax.swing.*;
public class Login extends JFrame implements ActionListener
{
public JTextField t1;
public TextField t2;
public JLabel l1,l2,l3;
public JButton b1,b2;
public JPanel panel;
public Font g;
public Login()
{
g=new Font("",Font.BOLD,18);
getContentPane().setBackground(Color.magenta);
panel=(JPanel)getContentPane();
panel.setLayout(null);
l1=new JLabel("LOGIN FORM");
l2=new JLabel("LOGIN");
l3=new JLabel("PASSWORD");
t1=new JTextField(20);
t2=new TextField(20);
t2.setEchoChar('*');
b1=new JButton("OK");
b2=new JButton("EXIT");
panel.add(l1);
l1.setFont(g);
panel.add(l2);
panel.add(l3);
panel.add(t1);
panel.add(t2);
panel.add(b1);
panel.add(b2);
l1.setBounds(100,5,150,40);
l2.setBounds(30,60,100,30);
l3.setBounds(30,110,100,30);
t1.setBounds(140,60,150,30);
t2.setBounds(140,110,150,30);
b1.setBounds(140,180,60,30);
b2.setBounds(220,180,65,30);
t1.addActionListener(this);
t2.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
String s1="mrp";
String s2="pandey";
String s3="OK";
String s4="EXIT";
String str=a.getActionCommand();
if(s3.equals(str))
{
if(s1.equals(t1.getText()) && s2.equals(t2.getText()))
{
this.dispose();
menu p=new menu();
p.setVisible(true);
p.setSize(800,700);
p.show();
this.dispose();
}
else
{
if(s3.equals(str))
{
t1.setText("");
t2.setText("");
JOptionPane.showMessageDialog(null,"Please varify the correct Login and Password","Warning",JOptionPane.OK_CANCEL_OPTION);
}
}
}
if( str=="EXIT")
{
JOptionPane.showMessageDialog(null,"The project is still in progress,do u want to quit now","Warning",JOptionPane.OK_CANCEL_OPTION);
if(s4.equals(str))
{
System.exit(0);
}
repaint();
}
}
public static void main(String args[])
{
Login f=new Login();
f.setVisible(true);
f.setSize(800,600);
f.show();
}
}
Multiple Interface
}
interface B {
}
class X implements A, B {
}
class Y implements A {
B makeB() {
// Anonymous inner class:
return new B() {
};
}
}
public class MultiInterfaces {
static void takesA(A a) {
}
static void takesB(B b) {
}
public static void main(String[] args) {
X x = new X();
Y y = new Y();
takesA(x);
takesA(y);
takesB(x);
takesB(y.makeB());
}
} ///:~
Interface Inherit
* Start with Thread which implements Runnable.
*/
public class InterfaceInherit extends Thread {
public static void main(String[] a) {
new InterfaceInherit().start();
}
public void run() {
if (this instanceof InterfaceInherit)
System.out.println("This is InterfaceInherit");
if (this instanceof Thread)
System.out.println("This is Thread");
if (this instanceof Runnable)
System.out.println("This is Thread -- Interfaces ARE inherited!");
}
}
Interface
void methodI1(); // public static by default
}
interface I2 extends I1 {
void methodI2(); // public static by default
}
class A1 {
public String methodA1() {
String strA1 = "I am in methodC1 of class A1";
return strA1;
}
public String toString() {
return "toString() method of class A1";
}
}
class B1 extends A1 implements I2 {
public void methodI1() {
System.out.println("I am in methodI1 of class B1");
}
public void methodI2() {
System.out.println("I am in methodI2 of class B1");
}
}
class C1 implements I2 {
public void methodI1() {
System.out.println("I am in methodI1 of class C1");
}
public void methodI2() {
System.out.println("I am in methodI2 of class C1");
}
}
abstract class D1 implements I2 {
public void methodI1() {
}
}
public class InterFaceEx {
public static void main(String[] args) {
I1 i1 = new B1();
i1.methodI1();
((I2) i1).methodI2();
I2 i2 = new B1();
i2.methodI1();
i2.methodI2();
String var2 = ((A1) i1).methodA1();
System.out.println("var2 : " + var2);
String var3 = ((B1) i1).methodA1();
System.out.println("var3 : " + var3);
String var4 = i1.toString();
System.out.println("var4 : " + var4);
String var5 = i2.toString();
System.out.println("var5 : " + var5);
I1 i3 = new C1();
String var6 = i3.toString();
System.out.println("var6 : " + var6);
Object o1 = new B1();
((I1) o1).methodI1();
((I2) o1).methodI1();
((B1) o1).methodI1();
}
}
Thread Pool
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Tests the ThreadPool task.");
System.out.println(
"Usage: java ThreadPoolTest numTasks numThreads");
System.out.println( " numTasks - integer: number of task to run.");
System.out.println( " numThreads - integer: number of threads " +
"in the thread pool.");
return;
}
int numTasks = Integer.parseInt(args[0]);
int numThreads = Integer.parseInt(args[1]);
// create the thread pool
ThreadPool threadPool = new ThreadPool(numThreads);
// run example tasks
for (int i=0; i<numTasks; i++) {
threadPool.runTask(createTask(i));
}
// close the pool and wait for all tasks to finish.
threadPool.join();
}
/**
Creates a simple Runnable that prints an ID, waits 500
milliseconds, then prints the ID again.
*/
private static Runnable createTask(final int taskID) {
return new Runnable() {
public void run() {
System.out.println("Task " + taskID + ": start");
// simulate a long-running task
try {
Thread.sleep(500);
}
catch (InterruptedException ex) { }
System.out.println("Task " + taskID + ": end");
}
};
}
}
import java.util.LinkedList;
/**
A thread pool is a group of a limited number of threads that
are used to execute tasks.
*/
public class ThreadPool extends ThreadGroup {
private boolean isAlive;
private LinkedList taskQueue;
private int threadID;
private static int threadPoolID;
/**
Creates a new ThreadPool.
@param numThreads The number of threads in the pool.
*/
public ThreadPool(int numThreads) {
super("ThreadPool-" + (threadPoolID++));
setDaemon(true);
isAlive = true;
taskQueue = new LinkedList();
for (int i=0; i<numThreads; i++) {
new PooledThread().start();
}
}
/**
Requests a new task to run. This method returns
immediately, and the task executes on the next available
idle thread in this ThreadPool.
Tasks start execution in the order they are received.
@param task The task to run. If null, no action is taken.
@throws IllegalStateException if this ThreadPool is
already closed.
*/
public synchronized void runTask(Runnable task) {
if (!isAlive) {
throw new IllegalStateException();
}
if (task != null) {
taskQueue.add(task);
notify();
}
}
protected synchronized Runnable getTask()
throws InterruptedException
{
while (taskQueue.size() == 0) {
if (!isAlive) {
return null;
}
wait();
}
return (Runnable)taskQueue.removeFirst();
}
/**
Closes this ThreadPool and returns immediately. All
threads are stopped, and any waiting tasks are not
executed. Once a ThreadPool is closed, no more tasks can
be run on this ThreadPool.
*/
public synchronized void close() {
if (isAlive) {
isAlive = false;
taskQueue.clear();
interrupt();
}
}
/**
Closes this ThreadPool and waits for all running threads
to finish. Any waiting tasks are executed.
*/
public void join() {
// notify all waiting threads that this ThreadPool is no
// longer alive
synchronized (this) {
isAlive = false;
notifyAll();
}
// wait for all threads to finish
Thread[] threads = new Thread[activeCount()];
int count = enumerate(threads);
for (int i=0; i<count; i++) {
try {
threads[i].join();
}
catch (InterruptedException ex) { }
}
}
/**
A PooledThread is a Thread in a ThreadPool group,
designed to run tasks (Runnables).
*/
private class PooledThread extends Thread {
public PooledThread() {
super(ThreadPool.this,
"PooledThread-" + (threadID++));
}
public void run() {
while (!isInterrupted()) {
// get a task to run
Runnable task = null;
try {
task = getTask();
}
catch (InterruptedException ex) { }
// if getTask() returned null or was interrupted,
// close this thread by returning.
if (task == null) {
return;
}
// run the task, and eat any exceptions it throws
try {
task.run();
}
catch (Throwable t) {
uncaughtException(this, t);
}
}
}
}
}
Run As : java ThreadPoolTest 5 2
Thread State
Thread obj;
public static void main(String a[]){
new ThreadStateDemo();
}
ThreadStateDemo(){
obj=new Thread(this);
System.out.println("Thread obj is born");
System.out.println("Thread obj is ready");
obj.start();
}
public void run(){
System.out.println("THread obj is running");
}
}
Thread All Methods
boolean available;
ChopStick(){
available=true;
}
public synchronized void takeup(){
while(!available){
try
{
System.out.println("Hello is waiting for the other chopStick");
wait();
}
catch(InterruptedException e){}
}
available=false;
}
public synchronized void putdown(){
available=true;
notify();
}
}
class Hello extends Thread{
ChopStick left,right;
int hello_num;
Hello(int num,ChopStick chop1,ChopStick chop2){
hello_num=num;
left=chop1;
right=chop2;
}
public void eat(){
left.takeup();
right.takeup();
System.out.println("Hello "+(hello_num+1)+" is eating");
}
public void think(){
left.putdown();
right.putdown();
System.out.println("Hello "+(hello_num+1)+" is THinking");
}
public void run(){
while(true){
eat();
try
{
sleep(1000);
}
catch(InterruptedException ex){}
think();
try
{
sleep(1000);
}
catch(InterruptedException ex){}
}
}
}
class ThreadAllDemo{
static ChopStick[] chopsticks=new ChopStick[5];
static Hello[] hellos=new Hello[5];
public static void main(String a[]){
for(int count=0;count<=4;count++){
chopsticks[count]=new ChopStick();
}
for(int count=0;count<=4;count++){
hellos[count]=new Hello(count,chopsticks[count],chopsticks[(count+1)%5]);
}
for(int count=0;count<=4;count++){
hellos[count].start();
}
}
}
Thread Synchronization Methods
synchronized void display(int num){
System.out.println(""+num);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){
System.out.println("Error : "+e);
}
System.out.println("Done");
}
}
class Two implements Runnable{
int number;
One objo;
Thread objo1;
public Two(One one_num,int num){
objo=one_num;
number=num;
objo1=new Thread(this);
objo1.start();
}
public void run(){
objo.display(number);
}
}
class SynchMethod{
public static void main(String a[]){
One objo=new One();
int digit=10;
Two objSynch1=new Two(objo,digit++);
Two objSynch2=new Two(objo,digit++);
Two objSynch3=new Two(objo,digit++);
//wait for THreads to end
try
{
objSynch1.objo1.join();
objSynch2.objo1.join();
objSynch3.objo1.join();
}
catch(InterruptedException ex){
System.out.println("Error : "+ex);
}
}
}
Thread Synchronization
void display(int num){
System.out.println(""+num);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){
System.out.println("Interrupted");
}
System.out.println("Done");
}
}
class DemoTwo implements Runnable{
int number;
DemoOne objone;
Thread objTh;
public DemoTwo(DemoOne one_num,int num){
objone=one_num;
number=num;
objTh=new Thread(this);
objTh.start();
}
public void run(){
synchronized(objone){
objone.display(number);
}
}
}
class SynchBlock{
public static void main(String a[]){
DemoOne objone=new DemoOne();
int digit=10;
DemoTwo objSynch1=new DemoTwo(objone,digit++);
DemoTwo objSynch2=new DemoTwo(objone,digit++);
DemoTwo objSynch3=new DemoTwo(objone,digit++);
try
{//wait for Threads to end
objSynch1.objTh.join();
objSynch2.objTh.join();
objSynch3.objTh.join();
}
catch(InterruptedException ex){
System.out.println("Error : "+ex);
}
}
}
Thread Priority
int num;
public Priority(int num){
this.num=num;
}
public void run(){
for(int count=0;count<=num;count++){
System.out.println("Count is "+count);
}
System.out.println(Thread.currentThread().getName());
System.out.println("Its Priority was : "+Thread.currentThread().getPriority());
Thread.currentThread().setPriority(MAX_PRIORITY);
System.out.println("Its Priority now is : "+Thread.currentThread().getPriority());
}
public static void main(String a[]){
for(int ctr=0;ctr<2;ctr++){
Priority obj=new Priority(5);
obj.start();
obj.setName("Thread "+(ctr+1));
}
}
}
Thread
public static void main(String ar[]){
MyThread obj=new MyThread();
obj.create();
System.out.println("This is the main Thread");
}
public void create(){
Thread obj1=new Thread(this);
obj1.start();
}
public void run(){
while(true){
try{
System.out.println("This is the child Thread ");
Thread.sleep(500);
}
catch(InterruptedException ex)
{
System.out.println("Error : "+ex);
}
}
}
}
Thread
public static void main(String ar[]){
Thread current=Thread.currentThread();
//displays information
System.out.println("Current Thread Details : "+current);
current.setName("Demo Thread");
System.out.println("After changing the names : "+current);
}
}
Tuesday, April 14, 2009
ODBC-JDBC
import java.awt.event.*;
import javax.swing.*;
import java.lang.StringBuffer;
import java.io.IOException;
import java.io.*;
//******************
import java.sql.*; //allows sql calls to the database
public class AddressBookDataBase extends JFrame
{
private DataPanel myDataPanel;
private Connection dbconn;
private static int numPeople=0;
private static String info;
private static JTextArea txtInfo=new JTextArea( 8, 40 ); //needs to be here to speak
//across classes
public AddressBookDataBase()
{
super("This is my Student Records which calls a database, Student");
GridLayout myGridLayout= new GridLayout(3,1); //allows 3 panels
Container p = getContentPane();
myDataPanel=new DataPanel();
p.add(myDataPanel);
myDataPanel.setLayout(myGridLayout);
//*********************************
try
{
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
dbconn = DriverManager.getConnection("jdbc:odbc:databaseName",
"servernameForOracle","password");
info="Connection successful\n";
}
catch ( ClassNotFoundException cnfex )
{
cnfex.printStackTrace();
info=info+"Connection unsuccessful\n" + cnfex.toString();
}
catch ( SQLException sqlex )
{
sqlex.printStackTrace();
info=info+"Connection unsuccessful\n" +sqlex.toString();
}
catch ( Exception excp )
{
excp.printStackTrace();
info=info+excp.toString();
}
//**********************************
txtInfo.setText(info); //sets connection information
setSize(500,290);
setVisible(true);
}
public static void main(String args[])
{
AddressBookDataBase myAddressBookDataBase= new AddressBookDataBase();
myAddressBookDataBase.addWindowListener
(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
//*******************************
class DataPanel extends JPanel implements ActionListener
{
JLabel lblIDCap= new JLabel("Record Number");
JLabel lblLast=new JLabel("ROLL NO");
JLabel lblFirst=new JLabel("First Name");
JLabel lblPhone=new JLabel("AGE");
//JTextArea txtInfo=new JTextArea();
JLabel lblID=new JLabel(" "); //10 spaces
JTextField txtLast=new JTextField(10);
JTextField txtFirst=new JTextField(10);
JTextField txtPhone=new JTextField(10);
JButton btnAdd=new JButton("Add Record");
JButton btnFind=new JButton("Find Record");
JButton btnDelete=new JButton("Delete Record");
JButton btnUpdate=new JButton("Update Record"); //**
JButton btnClear=new JButton("Clear");
JButton btnExit=new JButton("Exit");
public DataPanel()
{
JPanel myPanel = new JPanel();
JPanel myPanel2 = new JPanel();
JPanel myPanel3 =new JPanel(); //**
myPanel.setLayout(new GridLayout (4,2));
myPanel2.setLayout(new GridLayout (2,3));
myPanel3.setLayout(new GridLayout(1,1));
add(myPanel);
add(myPanel2);
add(myPanel3); //**
myPanel.add(lblIDCap);
myPanel.add(lblID);
myPanel.add(lblLast);
myPanel.add(txtLast);
myPanel.add(lblFirst);
myPanel.add(txtFirst);
myPanel.add(lblPhone);
myPanel.add(txtPhone);
myPanel2.add(btnAdd);
myPanel2.add(btnFind);
myPanel2.add(btnDelete);
myPanel2.add(btnUpdate);
myPanel2.add(btnClear);
myPanel2.add(btnExit);
myPanel3.add( new JScrollPane(txtInfo)); //**
//puts txtInfo on application and allows it to scroll
btnAdd.addActionListener(this);
btnFind.addActionListener(this);
btnUpdate.addActionListener(this);
btnClear.addActionListener(this);
btnExit.addActionListener(this);
btnDelete.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
String ID=""; //must initialize to ""
String Last="";
String First="";
String Phone="";
Object source=event.getSource();
ID=lblID.getText().trim();
lblID.setText(ID);
Last=txtLast.getText().trim();
txtLast.setText(Last);
First=txtFirst.getText().trim();
txtFirst.setText(First);
Phone=txtPhone.getText().trim();
txtPhone.setText(Phone);
if (source.equals(btnAdd))
{
//********************************
try {
Statement statement = dbconn.createStatement();
if ( !Last.equals( "" ) &&
!First.equals( "" ) &&
!Phone.equals("") )
{
String temp = "INSERT INTO stu (" +
"Rollno, name, " +
"age" +
") VALUES (" +
Last + ", '" +
First + "', '" +
Phone + "')";
txtInfo.append( "\nInserting: " +
dbconn.nativeSQL( temp ) + "\n" );
int result = statement.executeUpdate( temp );
if ( result == 1 )
{ //does a query to see if insertion successful
txtInfo.append("\nInsertion successful\n");
String query="";
try
{
query = "SELECT * FROM stu WHERE name='" +
First + "' " ;
ResultSet rs = statement.executeQuery( query );
rs.next();
lblID.setText(String.valueOf(rs.getInt(1)));
}
catch ( SQLException sqlex )
{
txtInfo.append("error :-"+ sqlex.toString() );
}
}
else
{
txtInfo.append( "\nInsertion failed\n" );
txtFirst.setText( "" );
txtLast.setText( "" );
txtPhone.setText( "" );
}
}
else
txtInfo.append( "\nEnter Rollno, first, and " +
"Age, then press Add\n" );
statement.close();
}
catch ( SQLException sqlex )
{
txtInfo.append( sqlex.toString() );
txtFirst.setText("Entry already exists -- reenter");
}
}
//****************************
if (source.equals(btnFind))
{
try
{
if ( !Last.equals(""))
{
Statement statement =dbconn.createStatement();
String query = "SELECT * FROM stu " +
"WHERE rollno = " +
Last + " ";
txtInfo.append( "\nSending query: " +
dbconn.nativeSQL( query ) + "\n" );
ResultSet rs = statement.executeQuery( query );
display( rs );
statement.close();
}
else
txtLast.setText("Enter Roll No"+
" then press Find" );
}
catch ( SQLException sqlex )
{
txtInfo.append( sqlex.toString() + sqlex.getMessage() );
}
}
//******************************************
if (source.equals(btnUpdate))
{
try
{
Statement statement = dbconn.createStatement();
if ( ! lblID.getText().equals(""))
{
String temp = "UPDATE stu SET " +
"name='" + txtFirst.getText() +
"', age=" + txtPhone.getText() +
" WHERE rollno=" + lblID.getText();
txtInfo.append( "\nSending update: " +
dbconn.nativeSQL( temp ) + "\n" );
int result = statement.executeUpdate( temp );
if ( result == 1 )
txtInfo.append( "\nUpdate successful\n" );
else {
txtInfo.append( "\nUpdate failed\n" );
txtFirst.setText( "" );
txtLast.setText( "" );
txtPhone.setText( "" );
}
statement.close();
}
else
txtInfo.append( "\nYou may only update an " +
"existing record. Use Find to " +
"\nlocate the record, then " +
"modify the information and " +
"\npress Update.\n" );
}
catch ( SQLException sqlex ) {
txtInfo.append( sqlex.toString() );
}
}
//********************************************
if (source.equals(btnDelete))
{
try
{
Statement statement = dbconn.createStatement();
if ( ! lblID.getText().equals(""))
{
System.out.print(lblID.getText());
String temp = "DELETE from stu " +
" WHERE rollno=" + lblID.getText();
txtInfo.append( "\nDeleting Record: " +
dbconn.nativeSQL( temp ) + "\n" );
int result = statement.executeUpdate( temp );
if ( result == 1 )
{
txtInfo.append( "\nDeletion successful\n" );
}
else
{
txtInfo.append( "\nDeletion failed\n" );
txtFirst.setText( "" );
txtLast.setText( "" );
txtPhone.setText( "" );
}
statement.close();
}
else
txtInfo.append( "\nYou may only delete an " +
"existing record. Use Find to " +
"\nlocate the record, then " +
"press delete.\n" );
}
catch ( SQLException sqlex )
{
txtInfo.append( sqlex.toString() );
}
}
//********************************************
if (source.equals(btnClear))
{
txtLast.setText("");
txtFirst.setText("");
txtPhone.setText("");
lblID.setText("");
}
//********************************************
if (source.equals(btnExit))
{
System.exit(0);
}
}
//********************************************
public void display( ResultSet rs )
{
try
{
rs.next();
txtLast.setText("");
txtFirst.setText("");
txtPhone.setText("");
lblID.setText("");
int recordNumber = rs.getInt( 1 );
if ( recordNumber != 0 )
{
lblID.setText( String.valueOf(recordNumber) );
txtFirst.setText( rs.getString( 2 ) );
txtPhone.setText( rs.getString( 3 ) );
txtLast.setText( rs.getString( 1 ) );
}
else
{
txtInfo.append( "\nNo record found\n" );
}
}
catch ( SQLException sqlex )
{
txtInfo.append( "\n*** Student Details Not In Database ***\n" );
}
} }
}