|
hi,,,
i have this application that has a tab ...
i also have an add button(to add the info of the user example:name,address,phone etc) to my database, when i click on the add button the info will be added but what happens that a new tab will be added to ,,i don't want this to happen.
can some one help me please?
this is my code:
[code]
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.io.*;
import javax.swing.JPanel;
import java.applet.*;
import sun.audio.*;
import java.net.*;
import java.text.*;
class UtilityMethods extends JFrame implements ActionListener
{
private File fileName;
private RandomAccessFile output;
AudioStream voice;
UtilityMethods utilities;
Connection conn;
Statement stat;
String dsnName, userStatus;
String appTable = "CUSTOMER";
Container c = getContentPane();
JTabbedPane tabs;
JTable dataTable, addataTable;//,vdataTable;
static String[][] tableData, adtableData;//,vtableData;
JScrollPane scrollpane, adscrollpane,vscrollpane;
JTextField id, name, address, phone, sex, dob, photo,audio,template;
JTextArea comments;
JButton search, update, clear, add, delete, close,audio1,faceBrowse,voiceBrowse;
JPanel customerPanel, adminPanel,voicePanel;
JPanel backPanel, inputPanel, middlePanel, buttonPanel1, buttonPanel2, photoHolder;
JPanel topPanel ;
JTextField adname, adusername, adpassword;
JPanel adbackPanel, adinputPanel, admiddlePanel, adbuttonPanel1, adbuttonPanel2, radioPanel;
JButton adsearch, adupdate, adclear, adadd, addelete, adclose;
JRadioButton userStat, adminStat, cleared;
ButtonGroup statusGroup;
/*JTextField vid,vname,vaddress,vphone,vsex,vdob,vtemplate,vvoice;
JButton vsearch,vupdate,vclear,vadd,vdelete,vclose,vplay,vstop;
JPanel vbackPanel, vinputPanel, vmiddlePanel, vbuttonPanel1, vbuttonPanel2;*/
/*public UtilityMethods()
{
makeGUI();
}*/
//===================================================================================================
//Create the GUI:
void makeGUI()
{
c.setLayout(new BorderLayout());
tabs = new JTabbedPane();
customerPanel = new JPanel(new BorderLayout());
adminPanel = new JPanel(new BorderLayout());
voicePanel= new JPanel(new BorderLayout());
//1. Construct customers tab:
//The data input section:
/* inputPanel = new JPanel(new GridLayout(4, 4));
id = new JTextField(20);
name = new JTextField(20);
address = new JTextField(20);
phone = new JTextField(20);
sex = new JTextField(20);
dob = new JTextField(20);
photo = new JTextField(20);
audio = new JTextField(20);
inputPanel.add(new JLabel("CPR", JLabel.CENTER));
inputPanel.add(id);
inputPanel.add(new JLabel("Name", JLabel.CENTER));
inputPanel.add(name);
inputPanel.add(new JLabel("Address", JLabel.CENTER));
inputPanel.add(address);
inputPanel.add(new JLabel("Phone", JLabel.CENTER));
inputPanel.add(phone);
inputPanel.add(new JLabel("Sex", JLabel.CENTER));
inputPanel.add(sex);
inputPanel.add(new JLabel("Date Of Birth", JLabel.CENTER));
inputPanel.add(dob);
inputPanel.add(new JLabel("Customer Photo ", JLabel.CENTER));
inputPanel.add(photo);
inputPanel.add(new JLabel("Voice ", JLabel.CENTER));
inputPanel.add(audio);
customerPanel.add(inputPanel, BorderLayout.NORTH);*/ JPanel labelPanel = new JPanel(new GridLayout(0, 1));
JPanel inputPanel = new JPanel(new GridLayout(0, 1));
JPanel buttonPanel = new JPanel(new GridLayout(0, 1));
id = new JTextField(20);
name = new JTextField(20);
address = new JTextField(20);
phone = new JTextField(20);
sex = new JTextField(20);
dob = new JTextField(20);
photo = new JTextField(20);
audio = new JTextField(20);
template = new JTextField(20);
faceBrowse = new JButton("...");
faceBrowse.setBounds(210, 150, 25, 25);
// faceBrowse.addActionListener(this);
voiceBrowse = new JButton("...");
voiceBrowse.setBounds(210, 150, 25, 25);
// voiceBrowse.addActionListener(this);
faceBrowse.setPreferredSize(new Dimension(26, 26));
voiceBrowse.setPreferredSize(new Dimension(26, 26));
labelPanel.add(new JLabel("CPR", JLabel.CENTER));
inputPanel.add(id);
buttonPanel.add(new JLabel(""));
labelPanel.add(new JLabel("Name", JLabel.CENTER));
inputPanel.add(name);
buttonPanel.add(new JLabel(""));
labelPanel.add(new JLabel("Address", JLabel.CENTER));
inputPanel.add(address);
buttonPanel.add(new JLabel(""));
labelPanel.add(new JLabel("Phone", JLabel.CENTER));
inputPanel.add(phone);
buttonPanel.add(new JLabel(""));
labelPanel.add(new JLabel("Sex", JLabel.CENTER));
inputPanel.add(sex);
buttonPanel.add(new JLabel(""));
labelPanel.add(new JLabel("Date Of Birth", JLabel.CENTER));
inputPanel.add(dob);
buttonPanel.add(new JLabel(""));
labelPanel.add(new JLabel("Customer Photo ", JLabel.CENTER));
inputPanel.add(photo);
buttonPanel.add(faceBrowse);
labelPanel.add(new JLabel("Voice ", JLabel.CENTER));
inputPanel.add(audio);
buttonPanel.add(voiceBrowse);
labelPanel.add(new JLabel("Template", JLabel.CENTER));
inputPanel.add(template);
buttonPanel.add(new JLabel(""));
JPanel topPanel = new JPanel(new GridLayout(1, 3));
topPanel.add(labelPanel);
topPanel.add(inputPanel);
topPanel.add(buttonPanel);
customerPanel.add(topPanel, BorderLayout.NORTH);
//The buttons section:
backPanel = new JPanel();
middlePanel = new JPanel(new BorderLayout());
buttonPanel1 = new JPanel();
buttonPanel2 = new JPanel();
search = new JButton("SEARCH");
update = new JButton("UPDATE");
clear = new JButton("CLEAR");
add = new JButton("ADD");
delete = new JButton("DELETE");
close = new JButton("EXIT");
audio1 =new JButton("Voice");
search.setPreferredSize(new Dimension(102, 26));
update.setPreferredSize(new Dimension(102, 26));
clear.setPreferredSize(new Dimension(102, 26));
add.setPreferredSize(new Dimension(102, 26));
delete.setPreferredSize(new Dimension(102, 26));
close.setPreferredSize(new Dimension(102, 26));
audio1.setPreferredSize(new Dimension(102, 26));
search.addActionListener(this);
update.addActionListener(this);
clear.addActionListener(this);
add.addActionListener(this);
delete.addActionListener(this);
close.addActionListener(this);
audio1.addActionListener(this);
buttonPanel1.add(search);
buttonPanel1.add(update);
buttonPanel1.add(clear);
buttonPanel2.add(add);
buttonPanel2.add(delete);
buttonPanel2.add(close);
buttonPanel2.add(audio1);
middlePanel.add(buttonPanel1, BorderLayout.NORTH);
middlePanel.add(buttonPanel2, BorderLayout.CENTER);
photoHolder = new JPanel();
Icon curPhoto = new ImageIcon("");
Icon[] custPhotos = {curPhoto};
JList photosList = new JList(custPhotos);
photosList.setFixedCellHeight(100);
photosList.setFixedCellWidth(80);
photoHolder.add(photosList);
makeComments();
backPanel.add(middlePanel);
backPanel.add(photoHolder);
backPanel.add(comments);
/*// Create vertical box for second tab
Box box = Box.createVerticalBox();
// Create component for top
box.add(inputPanel);
// Place glue between components
box.add(Box.createVerticalGlue());
// Create component for middle
box.add(middlePanel);
// Place glue between components
box.add(Box.createVerticalGlue());
// Create component for bottom
//box.add(new JButton("Bottom"));
// Add box to JTabbedPane
//tabs.add(box, "Box");*/
customerPanel.add(backPanel, BorderLayout.CENTER);
//2. Create the administration tab:
adinputPanel = new JPanel(new GridLayout(2, 4));
adname = new JTextField(20);
adusername = new JTextField(20);
adpassword = new JTextField(20);
radioPanel = new JPanel();
statusGroup = new ButtonGroup();
userStat = new JRadioButton("User");
adminStat = new JRadioButton("Admin");
cleared = new JRadioButton("");
statusGroup.add(userStat);
statusGroup.add(adminStat);
statusGroup.add(cleared);
JLabel filler = new JLabel();
filler.setPreferredSize(new Dimension(90, 0));
radioPanel.add(userStat);
radioPanel.add(adminStat);
radioPanel.add(filler);
adinputPanel.add(new JLabel("Name ", JLabel.RIGHT));
adinputPanel.add(adname);
adinputPanel.add(new JLabel("Status: ", JLabel.RIGHT));
adinputPanel.add(radioPanel);
adinputPanel.add(new JLabel("(Search by) UserName ", JLabel.RIGHT));
adinputPanel.add(adusername);
adinputPanel.add(new JLabel("Password ", JLabel.RIGHT));
adinputPanel.add(adpassword);
adminPanel.add(adinputPanel, BorderLayout.NORTH);
//The admin buttons section:
admiddlePanel = new JPanel(new BorderLayout());
adbuttonPanel1 = new JPanel();
adbuttonPanel2 = new JPanel();
adsearch = new JButton("SEARCH");
adupdate = new JButton("UPDATE");
adclear = new JButton("CLEAR");
adadd = new JButton("ADD");
addelete = new JButton("DELETE");
adclose = new JButton("EXIT");
adsearch.setPreferredSize(new Dimension(102, 26));
adupdate.setPreferredSize(new Dimension(102, 26));
adclear.setPreferredSize(new Dimension(102, 26));
adadd.setPreferredSize(new Dimension(102, 26));
addelete.setPreferredSize(new Dimension(102, 26));
adclose.setPreferredSize(new Dimension(102, 26));
adsearch.addActionListener(this);
adupdate.addActionListener(this);
adclear.addActionListener(this);
adadd.addActionListener(this);
addelete.addActionListener(this);
adclose.addActionListener(this);
adbuttonPanel1.add(adsearch);
adbuttonPanel1.add(adupdate);
adbuttonPanel1.add(adclear);
adbuttonPanel2.add(adadd);
adbuttonPanel2.add(addelete);
adbuttonPanel2.add(adclose);
admiddlePanel.add(adbuttonPanel1, BorderLayout.NORTH);
admiddlePanel.add(adbuttonPanel2, BorderLayout.CENTER);
adminPanel.add(adinputPanel, BorderLayout.NORTH);
adminPanel.add(admiddlePanel, BorderLayout.CENTER);
tabs.add(customerPanel, "Customers");
tabs.add(adminPanel, "Administration");
//if(userStatus.equals("user"))
//{
delete.setEnabled(false);
// vdelete.setEnabled(false);
tabs.setEnabledAt(1, false);
//}
pack();
setVisible(true);
} //makeGUI
//===================================================================================================
//===================================================================================================
//Update the customer table from the database:
void updateTable(String userStatus)
{
this.userStatus = userStatus;
updateTable();
}
void updateTable()
{
ResultSet results = null;
ResultSet results1 = null;
try
{
//Get the number of rows in the table so we know how big to make the data array..
int rowNumbers = 0;
int columnCount = 6;
results = stat.executeQuery("SELECT COUNT(*) FROM CUSTOMER ");
if(results.next())
{
rowNumbers = results.getInt(1);
} //if
if(rowNumbers == 0)
rowNumbers = 1;
tableData = new String[rowNumbers][columnCount];
//Initialize the data array with "" so we avoid possibly having nulls in it later..
for(int i =0;i<tableData.length;i++)
{
for(int j=0;j<tableData[0].length;j++)
tableData[j] = "";
}
//Populate the data array with results of the query on the database..
int currentRow = 0;
results1 = stat.executeQuery("SELECT * FROM CUSTOMER ORDER BY ID");
while (results1.next())
{
for(int i = 0; i < columnCount; i++)
tableData[currentRow] = results1.getString(i + 1);
currentRow++;
} //while
//-----------------------------------------------------------------------------------------------------
//Create the table model:
final String[] colName = { "CPR", "Name", "Address", "Phone", "Sex", "Date OF Birth" };
TableModel pageModel = new AbstractTableModel()
{
public int getColumnCount()
{
return tableData[0].length;
} //getColumnCount
public int getRowCount()
{
return tableData.length;
} //getRowCount
public Object getValueAt(int row, int col)
{
return tableData[row][col];
} //getValueAt
public String getColumnName(int column)
{
return colName[column];
} //getcolName
public Class getColumnClass(int col)
{
return getValueAt(0, col).getClass();
} //getColumnClass
public boolean isCellEditable(int row, int col)
{
return false;
} //isCellEditable
public void setValueAt(String aValue, int row, int column)
{
tableData[row][column] = aValue;
} //setValueAt
//dataTable.setValue( new JScrollBar(JScrollBar.HORIZONTAL), 2,1 );
}; //pageModel
//-----------------------------------------------------------------------------------------------------
//Create the JTable from the table model:
JTable dataTable = new JTable(pageModel);
//-----------------------------------------------------------------------------------------------------
/*if (scrollpane != null)
{
scrollpane.setVisible(false);
scrollpane = null;
} //if*/
//scrollpane = new JScrollPane(dataTable);
//scrollpane.setVisible(true);
if (inputPanel == null)
makeGUI();
JScrollPane scrollpane = new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// Create vertical box for second tab
Box box = Box.createVerticalBox();
// Create component for top
box.add(topPanel);
// Place glue between components
box.add(Box.createVerticalGlue());
// Create component for middle
box.add(middlePanel);
// Place glue between components
box.add(Box.createVerticalGlue());
// Create component for middle
box.add(backPanel);
// Place glue between components
box.add(Box.createVerticalGlue());
// Create component for bottom
box.add(scrollpane);
// Add box to JTabbedPane
tabs.add(box, "Box");
// customerPanel.add(scrollpane, BorderLayout.SOUTH);
c.add(tabs);
id.grabFocus();
pack();
repaint();
adupdateTable();
} //try
catch (Exception e)
{
System.out.println("Caught updateTable exception: " + e);
} //catch
} //updatetable
//===================================================================================================
//===================================================================================================
//Update the admin gui from the database:
void adupdateTable()
{
ResultSet results = null;
ResultSet results1 = null;
try
{
//Get the number of rows in the table so we know how big to make the data array..
int rowNumbers = 0;
int columnCount = 4;
results = stat.executeQuery("SELECT COUNT(*) FROM PASSWORD1");
if(results.next())
{
rowNumbers = results.getInt(1);
} //if
if(rowNumbers == 0)
rowNumbers = 1;
adtableData = new String[rowNumbers][columnCount];
//Initialize the data array with "" so we avoid possibly having nulls in it later..
for(int i =0;i< adtableData.length;i++)
{
for(int j=0;j< adtableData[0].length;j++)
adtableData[j] = "";
}
//Populate the data array with results of the query on the database..
int currentRow = 0;
results1 = stat.executeQuery("SELECT * FROM PASSWORD1 ");
while (results1.next())
{
for(int i = 0; i < columnCount; i++)
adtableData[currentRow] = results1.getString(i + 1);
currentRow++;
} //while
//-----------------------------------------------------------------------------------------------------
//Create the table model:
final String[] colName = { "Name", "Username", "Password", "Status"};
TableModel adpageModel = new AbstractTableModel()
{
public int getColumnCount()
{
return adtableData[0].length;
} //getColumnCount
public int getRowCount()
{
return adtableData.length;
} //getRowCount
public Object getValueAt(int row, int col)
{
return adtableData[row][col];
} //getValueAt
public String getColumnName(int column)
{
return colName[column];
} //getcolName
public Class getColumnClass(int col)
{
return getValueAt(0, col).getClass();
} //getColumnClass
public boolean isCellEditable(int row, int col)
{
return false;
} //isCellEditable
public void setValueAt(String aValue, int row, int column)
{
adtableData[row][column] = aValue;
} //setValueAt
}; //adpageModel
//-----------------------------------------------------------------------------------------------------
//Create the JTable from the table model:
addataTable = new JTable(adpageModel);
//-----------------------------------------------------------------------------------------------------
//if (adscrollpane != null)
//{
// adscrollpane.setVisible(false);
// adscrollpane = null;
//} //if
//adscrollpane = new JScrollPane(addataTable);
//adscrollpane.setVisible(true);
if (adminPanel == null)
makeGUI();
JScrollPane adscrollpane = new JScrollPane(addataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
addataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//customerPanel.add(scrollpane, BorderLayout.SOUTH);
adminPanel.add(adscrollpane, BorderLayout.SOUTH);
c.add(tabs);
id.grabFocus();
pack();
repaint();
// vupdateTable();
} //try
catch (Exception e)
{
System.out.println("Caught updateTable exception: " + e);
} //catch
} //updatetable
//===================================================================================================
//===================================================================================================
//===========================================================================================================================
//===========================================================================================================================
//The button actions:
public void actionPerformed(ActionEvent e)
{
FileInputStream fis = null;
if (e.getSource() == add) //The ADD button.
{
//User has not populated all the input fields.
if(name.getText().equals("")|| address.getText().equals("")|| phone.getText().equals("")|| sex.getText().equals("")|| dob.getText().equals("")|| photo.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Please fill in all the fields","Missing Fields",JOptionPane.INFORMATION_MESSAGE);
}
else
{
// save the new customer:
try
{
//1. take the customer's data and photo:
int userId = Integer.parseInt(id.getText());
String userName = name.getText();
String userAddress = address.getText();
String userPhone = phone.getText();
String userSex = sex.getText();
String userDateBirth = dob.getText();
String photoName = photo.getText();
String audioName= audio.getText();
File file = new File(photoName);
int fileLength = (int)file.length();
//2. Set the user's photo into the photoHolder:
photoHolder.setVisible(false);
photoHolder = null;
comments.setVisible(false);
comments = null;
Icon[] custPhotos = {new ImageIcon(photoName)};
JList photosList = new JList(custPhotos);
photosList.setFixedCellHeight(100);
photosList.setFixedCellWidth(80);
photoHolder = new JPanel();
photoHolder.add(photosList);
makeComments();
//3. Insert the data and photo into the database:
if(fileLength > 0)
{
fis = new FileInputStream(file);
String query = " INSERT INTO CUSTOMER VALUES('"+userId+"', '"+ userName+ "', '"+ userAddress+ "', " +" '"+ userPhone+ "', '"+ userSex+ "', '"+ userDateBirth+ "', ?,?,? ) ";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setBinaryStream(1, fis, fileLength);
pstmt.setString(2,photoName);
pstmt.setString(3,audioName);
pstmt.executeUpdate();
comments.setText(userName+", added.");
}
else
{
String query = " INSERT INTO CUSTOMER (id, name, address, phone, sex, dob) VALUES('"+userId+"', '"+userName+"', '"+userAddress+"', '"+userPhone+"', '"+userSex+"', '"+userDateBirth+"') ";
stat.executeUpdate(query);
comments.setText("Customer saved without a photo.");
}
backPanel.add(photoHolder);
backPanel.add(comments);
updateTable();
} //try
catch (Exception ee)
{
//The danger of putting creating the JOptionPane in here is that it will show the same message regardless of the error.
JOptionPane.showMessageDialog(null, "Customers CPR already exits!!Please enter another CPR","Invalid",JOptionPane.INFORMATION_MESSAGE);
System.out.println("Caught exception in add action: " + ee);
} //catch
} //if
}//add button
//-----------------------------------------------------------------------------------------------------
//===================================================================================================
//Handle the connections to the database:
void makeConnection(String dsnName)
{
try
{
this.dsnName = dsnName;
System.out.println("Connecting to database..");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:" + dsnName);
stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
}
catch (Exception e)
{
System.out.println("Caught exception in makeConnection: " + e);
}
} //makeConnection()
//-----------------------------------------------------------------------------------------------------
void closeConnection()
{
try
{
System.out.println("Closing database connections..");
conn.close();
conn = null;
stat = null;
}
catch (Exception e)
{
System.out.println("Caught closeConnection exception: " + e);
}
} //closeConnection()
public static void main(String args[]){
UtilityMethods application=new UtilityMethods();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//MAIN
}
[/code]
|
|
|
|
|
|
|
|