mport javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class DataBase extends JFrame implements ActionListener
{
JButton btnAdd,btnNew,btnFind,btnDelete,btnCancel,btnView;
JLabel lblHouseNo,lblName,lblDate,lblAmount,lblempty;
JTextField txtHouseNo,txtName,txtDate,txtAmount;
JPanel panel1,panel2,panel3;
ImageIcon im;
Container con=getContentPane();
Connection cont=null;
Statement st=null;
public DataBase()
{
super("House Rental Management");
setSize(600,500);
setLocation(70,30);
panel1=new JPanel();
panel1.setLayout(new GridLayout(5,2));
lblHouseNo=new JLabel("Enter House Number:");
lblName=new JLabel("Enter Name:");
lblDate=new JLabel("Enter Date:");
lblAmount=new JLabel("Enter Amount:");
//lblAdvance=new JLabel("Enter Advance:");
txtHouseNo=new JTextField(15);
txtName=new JTextField(15);
txtDate=new JTextField(15);
txtAmount=new JTextField(15);
//txtAdvance=new JTextField(15);
panel1.add(lblHouseNo);panel1.add(txtHouseNo);
panel1.add(lblName);panel1.add(txtName);
panel1.add(lblDate);panel1.add(txtDate);
panel1.add(lblAmount);panel1.add(txtAmount);
//panel1.add(lblAdvance);panel1.add(txtAdvance);
panel2=new JPanel();
panel2.setLayout(new FlowLayout());
btnAdd=new JButton("ADD");
btnAdd.addActionListener(this);
btnAdd.setActionCommand("ADD");
btnNew=new JButton("NEW");
btnNew.addActionListener(this);
btnNew.setActionCommand("NEW");
btnFind=new JButton("FIND");
btnFind.addActionListener(this);
btnFind.setActionCommand("FIND");
btnDelete=new JButton("DELETE");
btnDelete.addActionListener(this);
btnDelete.setActionCommand("DELETE");
btnCancel=new JButton("CANCEL");
btnCancel.addActionListener(this);
btnCancel.setActionCommand("CANCEL");
btnView=new JButton("VIEW");
btnView.addActionListener(this);
btnView.setActionCommand("VIEW");
im=new ImageIcon("house.jpg");
lblempty=new JLabel(im);
JLabel el=new JLabel("Developed by BALU");
el.setForeground(Color.red);
panel2.add(btnAdd);
panel2.add(btnNew);
panel2.add(btnFind);
panel2.add(btnDelete);
panel2.add(btnView);
panel2.add(btnCancel);
panel3=new JPanel();
panel3.add(lblempty);
panel3.add(el);
con.add(panel1,BorderLayout.NORTH);
con.add(panel3,BorderLayout.CENTER);
con.add(panel2,BorderLayout.SOUTH);
show();
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("ADD")&&txtHouseNo!=null)
{
try
{
initializeConnection();
int no = Integer.parseInt(txtHouseNo.getText());
String name= txtName.getText();
String date = txtDate.getText();
int amount = Integer.parseInt(txtAmount.getText());
insertRecord(no,name,date,amount);
closeConnection();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,new String("Please! Enter all the Details:"),"",JOptionPane.INFORMATION_MESSAGE);
}
}
else if(str.equals("NEW"))
{
txtHouseNo.setText("");
txtName.setText("");
txtDate.setText("");
txtAmount.setText("");
txtHouseNo.requestFocus();
}
else if(str.equals("FIND"))
{
try
{
int hNo =Integer.parseInt(JOptionPane.showInputDialog(this,new String("Enter House No :"),"Find House...",JOptionPane.QUESTION_MESSAGE));
initializeConnection();
try
{
ResultSet myRs = getRecords("Select * from House where HouseNo="+hNo);
String message = " House No : "+myRs.getInt(1);
message = message + "\n Name : " + myRs.getString(2);
message = message + "\n Date :" + myRs.getDate(3);
message = message + "\n Amount :" + myRs.getInt(4);
JOptionPane.showMessageDialog(this,message,"House....",JOptionPane.INFORMATION_MESSAGE);
}
catch(Exception e) { JOptionPane.showMessageDialog(this,new String("Enter! Valid HouseNo:"),"",JOptionPane.INFORMATION_MESSAGE);
}
closeConnection();
}
catch(NumberFormatException nfe)
{
JOptionPane.showMessageDialog(this,new String("Fool! Enter a Number:"),"",JOptionPane.INFORMATION_MESSAGE);
}
}
else if(str.equals("DELETE"))
{
try
{
int hoNo =Integer.parseInt(JOptionPane.showInputDialog(this,new String("Enter House No to delete :"),"delete House...",JOptionPane.QUESTION_MESSAGE));
initializeConnection();
try
{
st.executeUpdate("Delete from House where HouseNo="+hoNo);
}
catch(Exception e)
{
}
closeConnection();
}
catch(NumberFormatException nfe)
{
JOptionPane.showMessageDialog(this,new String("Record deleted:"),"",JOptionPane.INFORMATION_MESSAGE);
}
}
else if(str.equals("CANCEL"))
{
System.exit(0);
}
else if(str.equals("VIEW"))
{
try
{
new TableDeneme();
}
catch(Exception e)
{
}
}
}
private void initializeConnection()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cont = DriverManager.getConnection("jdbc:odbc:balu","","");
st = cont.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
}
catch(Exception e) { }
}
private ResultSet getRecords(String query) throws SQLException
{
ResultSet rs=st.executeQuery(query);
rs.first();
return rs;
}
private void insertRecord(int houseNo,String name,String d,int amt)
{
name = "'" + name +"'";
d = "'" + d +"'";
String query = "insert into House values (" + houseNo +","+name+","+d+","+amt+")";
try
{
st.executeQuery(query);
} catch (Exception e) { }
JOptionPane.showMessageDialog(this,new String(" Record Added..."),"House....",JOptionPane.INFORMATION_MESSAGE);
}
private void closeConnection()
{
try
{
if (cont!=null)
{
cont.close();
st.close();
}
}
catch(Exception e) { }
}
public static void main(String args[])
{
DataBase db=new DataBase();
}
}
Code for TableDeneme:
import java.awt.event.*;
import java.awt.Window;
import java.awt.*;
import java.sql.*;
import java.io.*;
import java.util.Vector;
import java.util.EventObject;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
class BasicWindowMonitor extends WindowAdapter{
public void windowClosing(WindowEvent e)
{
Window w=e.getWindow();
w.setVisible(false);
w.dispose();
System.exit(0);
}
}
class QueryTableModel extends AbstractTableModel{
Vector cache;
int colCount;
String[] headers;
Connection db;
Statement statement;
String currentURL;
String kolon;
public QueryTableModel()
{
cache=new Vector();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
}
catch(java.lang.Exception e)
{
System.err.println("Class not found exception : ");
System.err.println(e.getMessage());
}
}
public String getColumnName(int i)
{
return headers[i];
}
public int getColumnCount() {return colCount;}
public int getRowCount() {return cache.size();}
public Object getValueAt(int row,int col){
return ((String[])cache.elementAt(row))[col];
}
public boolean isCellEditable(int row, int col){ return true; }
public void setValueAt(Object value, int row, int col) {//are you editing?
/*prepare the query*/
/*you have to change the query to adapt it to your table*/
if(col==0) kolon="english";
if(col==1) kolon="turkish";
String s="update House set " + kolon + " = '" + (String)value + "' where " + kolon + " = '" + ((String[])cache.elementAt(row))[col] + "'";
System.out.println(s);
/*excecute the query*/
try{
statement.execute(s);
}catch(Exception e){System.out.println("Could not updated");}
((String[])cache.elementAt(row))[col] = (String)value;
fireTableCellUpdated(row, col);//also update the table
}
/*****end of abstracttablemodel methodlarý******/
public void setHostURL(String url){
if(url.equals(currentURL))
{return;}
closeDB();
initDB(url);
currentURL=url;
}
public void setQuery(String q){
cache= new Vector();
try{
ResultSet rs=statement.executeQuery(q);
ResultSetMetaData meta=rs.getMetaData();
colCount=meta.getColumnCount();
headers=new String[colCount];
for (int h=1;h<=colCount;h++) { headers[h-1]=meta.getColumnName(h); } while(rs.next()) { String[] record=new String[colCount]; for(int i=0;i
{record[i]=rs.getString(i+1);}
cache.addElement(record);
} //while sonu
fireTableChanged(null);
} //try sonu
catch(Exception e){
cache=new Vector();
e.printStackTrace();
}
} //setQuery sonu
public void initDB(String url){
try {
db=DriverManager.getConnection(url);
statement=db.createStatement();
}catch(Exception e){
System.out.println("Database could not started");
e.printStackTrace();
}
} //initDB sonu
public void closeDB(){
try {
if(statement!= null) {statement.close();}
if(db != null) {db.close();}
}catch(Exception e){
System.out.println("Database could not closed");
e.printStackTrace();
}
} //closeDB sonu
}
/* ***********************TableDeneme class********************* */
/* ***********************TableDeneme class********************* */
/* ***********************TableDeneme class********************* */
/* ***********************TableDeneme class********************* */
public class TableDeneme extends JFrame {
QueryTableModel qtm;
JTable table;
JScrollPane scrollpane;
JPanel p1,p2;
JButton jb,can;
ListSelectionModel rowSM;
public TableDeneme(){
super("Dictionary Window");
setSize(800,600);
setLocation(70,30);
setBackground(Color.blue);
qtm=new QueryTableModel();
table=new JTable(qtm);
scrollpane=new JScrollPane(table);
p1=new JPanel();
jb=new JButton("Click Here!");
can=new JButton("CANCEL");
can.setActionCommand("CANCEL");
p1.add(jb);
getContentPane().add(p1,BorderLayout.NORTH);
getContentPane().add(scrollpane,BorderLayout.CENTER);
getContentPane().add(can,BorderLayout.SOUTH);
addWindowListener(new BasicWindowMonitor());
setSize(500,500);
setVisible(true);
/*JOptionPane.showMessageDialog(new Frame(),"Press the button,\n"
+"It will fill the table with all records.\n"
+"Then you can edit the cells.\n"
+"When you select another cell, the previous one will updated.\n\n"
+"suhan@turkserve.net");*/
can.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String str=e.getActionCommand();
if(str.equals("CANCEL"))
{
System.exit(0);
}
}
});
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
qtm.setHostURL("jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);UID=admin;UserCommitSync=Yes;Threads=3;SafeTransactions=0;PageTimeout=5;MaxScanRows=8;MaxBufferSize=2048;FIL=MS Access;DriverId=281;DBQ=HouseDB.mdb");
qtm.setQuery("select * from House where HouseNo orderby ASC");
}
});
}
public static void main(String[] args){
TableDeneme td=new TableDeneme();
}
}