Problem about jtable and database

The problem is that when i clicked the button to save the values of textfields and text area, although the table is supposed to show the new list of datas from the db, it adds the new data list to the end of the first list. I have to list one old and one new in jtable.
* To change this template, choose Tools | Templates
* and open the template in the editor.
* DatabaseConnection.java
* Created on 28.Aðu.2008, 11:24:52
package databaseconnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
* @author ARAGORN
public class DatabaseConnection extends javax.swing.JFrame {
    /** Creates new form DatabaseConnection */
    public DatabaseConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Students", "admin", "1837837");
            st = con.createStatement();
        } catch (Exception e) {
            System.out.println("Database Connection Error!");
        try {
            ResultSet rs = st.executeQuery("SELECT*FROM studentdata");
            while (rs.next()) {
                Object[] rowValues = {rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getString(5),rs.getString(6),rs.getInt(7)};
                row.addElement(rowValues);
            data = new Object[row.size()][7];
            for(int i=0;i<row.size();i++){
                data=(Object[]) row.get(i);
} catch (Exception e) {
System.out.println("reading error!");
initComponents();
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jSeparator1 = new javax.swing.JSeparator();
jLabel2 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jTextField5 = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jTextField6 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
jTable1.setModel(new javax.swing.table.DefaultTableModel(data,heading)
jScrollPane1.setViewportView(jTable1);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Öðrenci Bilgileri", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jLabel1.setText("Öðrenci No : ");
jLabel2.setText("Adý : ");
jLabel3.setText("Sýnýf : ");
jLabel4.setText("Soyad : ");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane2.setViewportView(jTextArea1);
jLabel5.setText("Adress : ");
jLabel6.setText("Tel : ");
jLabel7.setText("Þube : ");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(364, Short.MAX_VALUE))
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 581, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel6)
.addComponent(jLabel2)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField4)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE))
.addGap(28, 28, 28)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
.addComponent(jTextField6, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)))
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(49, 49, 49))
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel7)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
jButton1.setText("Kaydet");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
jButton2.setText("Temizle");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
jButton3.setText("Çýk");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 597, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3)))
.addContainerGap())
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addGap(38, 38, 38))
pack();
}// </editor-fold>
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
System.exit(0);
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jTextField6.setText("");
jTextArea1.setText("");
private void formWindowOpened(java.awt.event.WindowEvent evt) {                                 
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
try {
st.executeUpdate("INSERT studentdata(Ogrenci_no,Ad,Soyad,Sinif,Sube,Adres,Tel) VALUES(" +
Integer.parseInt(jTextField1.getText()) + ", '" +
jTextField2.getText() + "', '" +
jTextField4.getText() + "', " +
Integer.parseInt(jTextField3.getText()) + ", '" +
jTextField6.getText() + "', '" +
jTextArea1.getText() + "', " +
Integer.parseInt(jTextField5.getText()) +
} catch (SQLException e) {
System.out.println("Writing data Error!");
try {
ResultSet rs = st.executeQuery("SELECT * FROM studentdata");
while (rs.next()) {
Object[] rowValues = {rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getString(5),rs.getString(6),rs.getInt(7)};
row.addElement(rowValues);
data = new Object[row.size()][7];
for(int i=0;i<row.size();i++){
data[i]=(Object[]) row.get(i);
} catch (Exception e) {
System.out.println("reading error!");
jTable1.setModel(new MyTableModel());
jTable1.setVisible(true);
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DatabaseConnection().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTable jTable1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
private javax.swing.JTextField jTextField6;
// End of variables declaration
Connection con;
Statement st;
Vector row = new Vector();
Object[][] data;
Object[] heading = {"Öðrenci_No","Ad","Soyad","Sýnýf","Sube","Adres","Tel"};
class MyTableModel extends AbstractTableModel{
public int getColumnCount(){
return heading.length;
public int getRowCount(){
return data.length;
@Override
public String getColumnName(int column){
return heading[column].toString();
public Object getValueAt(int row, int column){
return data[row][column];
public boolean isCellEditable(){
return false;
@Override
public void setValueAt(Object value, int row, int column){
data[row][column] = value;
fireTableCellUpdated(row, column);
}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

any one to help ?

Similar Messages

  • Hello apple I have the problem with my iPhone and my friends have this problem too. My iPhone have the problem about calling and answer the call. When I use my iPhone to call I can't hear anything from my iPhone but the person that I call can answer it bu

    Hello apple
    I have the problem with my iPhone and my friends have this problem too.
    My iPhone have the problem about calling and answer the call. When I use my iPhone to call I can't hear anything from my iPhone but the person that I call can answer it but when answer both of us can't hear anything and when I put my iPhone to my face the screen is still on and when I quit the phone application and open it again it will automatic call my recent call. And when my friends call me my iPhone didn't show anything even the missed call I'm only know that I missed the call from messages from carrier. Please check these problem I restored my iPhone for 4 time now in this week. I lived in Hatyai, Songkhla,Thailand and many people in my city have this problem.
    Who have this problem??

    Apple isnt here. this is a user based forum for technical questions. The solution is to restart, reset, and restore as new which is in the manual after that get it replaced for hard ware failure. if your within your one year warranty its replaced if it is out of the warranty then it is 199$

  • A very surprise problem about JDBC and connection pool

    I occur a very problem about JDBC and connection pool on Weblogic Platform
    8.1.
    There is a table in Oracle
    Table
    Name: t1
    id varchar2(5);
    content clob;
    id is primary key.
    If I use a connection pool to connect to Oracle,like following program:
    InitialContext ic = new InitialContext();
    DataSource ds = (DataSource) ic.lookup("cgOracleDataSource");
    con = ds.getConnection();
    then following program will throw a ClassCastException
    String sql = "select content from t1 where id = ?";
    PreparedStatement pst = con.prepareStatement(sql);
    pst.setString(1,"001");
    oracle.sql.CLOB clob = (oralce.sql.CLOB)rs.getClob("content") //this
    statement will throw ClassCastException
    but if I use JNDI to connect to Oracle,like following program, then those
    program above is ok
    private String dbdriver="oracle.jdbc.driver.OracleDriver";
    private String dburl="jdbc:oracle:thin:@192.168.7.148:1521:ep";
    private String username="ep";
    private String password="epuser";
    Class.forName(dbdriver);
    conn = DriverManager.getConnection(dburl, username, password);
    conn.setAutoCommit(false);
    On the contrary, if I use JNDI to connect to Oracle, following program will
    throw ClassCastException
    weblogic.jdbc.vendor.oracle.OracleThinClob clob =
    (weblogic.jdbc.vendor.oracle.OracleThinClob)rs.getClob("content");
    but it is fine if I use connection pool to connect to Oracle.
    I am confused this problem, who can tell me why?
    Daniel

    When you are getting connection using datasource lookup from weblogic
    connection pool, this connection is internally wrapped and hence you have to
    cast it to weblogic.jdbc.vendor.oracle.OracleThinClob which you do and so it
    works.
    But when you get connection by loading driver straight, you are getting naked
    oracle connection. In this case when you cast it to oracle.sql.Clob it works,
    as you have seen in your test case.
    I hope this explains what is going on with your code.
    Thanks,
    Mitesh
    Daniel wrote:
    I occur a very problem about JDBC and connection pool on Weblogic Platform
    8.1.
    There is a table in Oracle
    Table
    Name: t1
    id varchar2(5);
    content clob;
    id is primary key.
    If I use a connection pool to connect to Oracle,like following program:
    InitialContext ic = new InitialContext();
    DataSource ds = (DataSource) ic.lookup("cgOracleDataSource");
    con = ds.getConnection();
    then following program will throw a ClassCastException
    String sql = "select content from t1 where id = ?";
    PreparedStatement pst = con.prepareStatement(sql);
    pst.setString(1,"001");
    oracle.sql.CLOB clob = (oralce.sql.CLOB)rs.getClob("content") //this
    statement will throw ClassCastException
    but if I use JNDI to connect to Oracle,like following program, then those
    program above is ok
    private String dbdriver="oracle.jdbc.driver.OracleDriver";
    private String dburl="jdbc:oracle:thin:@192.168.7.148:1521:ep";
    private String username="ep";
    private String password="epuser";
    Class.forName(dbdriver);
    conn = DriverManager.getConnection(dburl, username, password);
    conn.setAutoCommit(false);
    On the contrary, if I use JNDI to connect to Oracle, following program will
    throw ClassCastException
    weblogic.jdbc.vendor.oracle.OracleThinClob clob =
    (weblogic.jdbc.vendor.oracle.OracleThinClob)rs.getClob("content");
    but it is fine if I use connection pool to connect to Oracle.
    I am confused this problem, who can tell me why?
    Daniel

  • EAI is just about  WS and database interaction or WS and What

    Salut,
    I want a straightforward answer for this question
    EAI: is it about WS and legacy database interaction or what ?

    Hello,
    Have you take a look to BPEL (Business Process Execution Language) that is a language that use Web Services to define your business process.
    Take a look to the BPEL page on OTN and you will learn about what can WS give you in term of EAI. For example Oracle Application server with its adaptor based on JCA allow you to publish this JCA information as Web Service so you can leverage any legacy system...
    - BPEL Page
    Regards
    Tugdual Grall

  • Jtable and database

    hi,
    i am using jdevlopper 10g and oracle 10g express.
    i create a database and a new connection to it.
    in the first frame, i created a new jtable and i want that it containts data from the database.
    is any one can help me.
    thanks

    Hi,
    you have two options:
    - Use ADF and ADF Swing, in which cae the database connect is through a business service (e.g. ADF Business Components or EJB)
    - Create a JDBC connection to the database and populate the JTable model with the data (which is cumbersome). You find tutorials on the web of how to do this.
    Frank

  • Strange Problem about KeyListener, and FocusListener

    Hi,Please help me with this problem.
    I create a JTable and setCellEditor by using my customerized TextField
    The problem is: when I edit JTable Cell, the value can not be changed and I can not get Key Event and Focus Event.
    here is my source:
    //create normal JTable instance,and then initlize it
    private void initTable(Vector folders)
    TableColumn tempcol = getColumnModel().getColumn(0);
    tempcol.setCellEditor(new DefaultCellEditor(new MyTextField()));
    for(int i=0;i<folders.size();i++)
    mddDataSource ds=(mddDataSource) folders.get(i);
    String name = ds.getDataSourceName();
    layers.add(name);
    for(int i=0;i<layers.size();i++){
    Vector temp = new Vector();
    temp.add(layers.get(i));
    temp.add(layers.get(i));
    dtm.addRow(temp);
    // My Text Field cell
    class MyTextField extends JTextField implements FocusListener, KeyListener
    MyTextField()
    setOpaque (false);
    addKeyListener(this);
    addFocusListener(this);
    MyTextField(String text)
    setOpaque (false);
    addKeyListener(this);
    addFocusListener(this);
    public void focusGained(FocusEvent e) {
    System.out.println("get Focus");
    public void focusLost(FocusEvent e) {
    instance.setValue(getText());
    public void keyTyped(KeyEvent e){
    instance.setValue(getText());
    public void keyPressed(KeyEvent e){
    System.out.println("get Key ");
    public void keyReleased(KeyEvent e){
    instance.setValue(getText());
    If there are some good sample, please tell me the link or give me some suggestion.
    Thanks in advanced

    Thanks for your help.
    The problem still exist. It does not commit the value that I input.
    Maybe I should say it clearly.
    I have create JPanel include three JPanel:
    Left Panel and right upper-panel and right borrom panel.
    The JTable instance is on right-upper Panel.
    If I edit one of row at JTable and then click JTable other row,the value can be commited. if I edit one of row and then push one Button on
    the right-bottom button to see the editting cell value.It does not commit value.
    when I use debug style, and set breakpoint the
    foucsGained or KeyTyped,
    It never stopes at there,So I assume that the Editing cell never get focus.
    Is there a bug at Java if we move focus on other Panel, that JTable can not detect the Focus lost or focus gained event?
    Thanks

  • Problem about ZHT32EUC encoding database and JDBC clients

    We have encountered a problem with the following configuration:
    Oracle Database Server
    AIX
    Oracle 8.1.7 - ZHT32EUC character encoding
    Clients are Java Applet/Servlet/JSP/EJB, as well as an other
    ZHT32EUC database for some data import/export (abbr as OLD).
    the problem we have is, no matter what we had set (the NLS_LANG
    environment variable) on the Java clients, we cannot read the
    ResultSet.getString() with the DB link and imported data from
    the OLD correctly. However, with the data we inserted with our
    own Java clients, it can be read flawlessly with JDBC calls.
    Any suggestions will be appreciated.
    Cheng Chun Kit
    Software Specialist
    Automated Systems (HK) Ltd

    Hard to tell, as you are not providing a lot of details. What is
    the OS that your other database is on. What are you actually
    setting NLS_LANG to? Are you using Oracle's JDBC driver or
    someone elses? Please describe? Which driver, OCI or thin
    driver? I would advise you to use the dump command to look at
    the data. I suspect you have not loaded the data properly to the
    database.

  • Problem about JTable's DataVector probelm

    I'm writing a database program with JTable, I want to make a copy of the data content of the jtable before editing the values.
    I first get the TableModel of the table then get the DataVector out to clone a copy to a new Vector, but when I change the values in the table, the values in both Vector also changed.
    Can anyone tell me why this happen? I really need your help. Thanks!
    Code:
    originalTable = (DefaultTableModel)jTablePO.getModel();
    originalVector = (Vector) (orgtable.getDataVector().clone());

    You don't actually want to copy the contents of that Vector to another Vector. That's because the contents of the Vector consists of references to a bunch of objects. Copies of those references are actually references to the same objects. That's what you're seeing there.
    So you don't want just copies of the references in the Vector. You want the new Vector to contain references to copies of whatever the original Vector contained references to. And since in a JTable, those things you're cloning are themselves Vectors, you have the same problem again at this level.
    You need a deep copy of the Vector, is what it boils down to. You should be able to google for that phrase or for deep clone.
    Edit: Good, while I was typing all that in a form that I hoped wasn't too confusing, you were already taking my advice.
    Message was edited by:
    DrClap

  • How to use JTable and database

    how i want to know how to store data into Jtable from the database for the end users.
    any tutorial or example will be helpfull.
    thank you

    my problem is i want to store data that i will get from the database into a JTableThen you problem is with Swing in which case you should be searching the Swing forum for answers. This question has been asked and answered several times. I know I've posted solutions before.

  • A problem about Proc and oci

    I got a new task (coding in c language with oci or proc to operate remote oracle. the develope environment is linux server is windows OS ) ,but I have nothing experice about it previously. in the process of using oci and proc, amount of problems appeared.
    the first question i want to make explicit is , can I testing and running the program with out the client of oracle. in a other word ,only use the .so files to compiling and testing .in linux environment .
    If the answer is that we can . how can i program with oci or proc?
    as I know in the samples of oracle ,every demo is only link to the local database.
    and the resource about this field is so limit. I can not find any usable material with google.
    in my familar condition ,if we need connect to remote database ,we should provide the hostname or ip address and the prot num of oracle service . but in OCI library ,there are two functions olog and ocilogon can use to log to service .how can i use it?
    eg. if the server hostname is dbserver/192.168.1.2 and port is 1521,the dbname is iv. how can i use olog or ocilogon to log on the server? thanks very much !!!
    btw: if we using proc to connect server. how can i connect to server?
    waiting on line...
    Thanks.

    You must install an Oracle Client in order to proceed. The client installation is included in the Oracle Database installation disc.
    Afterwards, use "netca" to configure the connection to your remote DB. Alternatively, you could edit the tnsnames.ora file manually if so you wish.
    For reading material, type "Pro*C/C++ Precompiler Programmer's Guide" in google.
    Message was edited by:
    jonjac

  • JTable and Databases

    Hi all,
    I have two files excerpts from my Java application. I feel that in order for me to get understood so well, with regards to a problem that challenged me, I had to post these two files as you can see below. They are called ResultSetTableModel.java and DisplayQueryResults.java [which gets displayed in an internal frame].
    I have this code from ResultSetTableModel
    // ResultSetTableModel.java
    // A TableModel that supplies ResultSet data to a JTable.
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import javax.swing.table.AbstractTableModel;
    // ResultSet rows and columns are counted from 1 and JTable
    // rows and columns are counted from 0. When processing
    // ResultSet rows or columns for use in a JTable, it is
    // necessary to add 1 to the row or column number to manipulate
    // the appropriate ResultSet column (i.e., JTable column 0 is
    // ResultSet column 1 and JTable row 0 is ResultSet row 1).
    public class ResultSetTableModel extends AbstractTableModel
       private Connection connection;
       private Statement statement;
       private ResultSet resultSet;
       private ResultSetMetaData metaData;
       private int numberOfRows;
       // keep track of database connection status
       private boolean connectedToDatabase = false;
       // constructor initializes resultSet and obtains its meta data object;
       // determines number of rows
       public ResultSetTableModel(String driver, String url,
          String username, String password, String query)
          throws SQLException, ClassNotFoundException {        
          // load database driver class
          Class.forName(driver);
          // connect to database
          connection = DriverManager.getConnection(url, username, password);
          // create Statement to query database
          statement = connection.createStatement(
             ResultSet.TYPE_SCROLL_INSENSITIVE,
             ResultSet.CONCUR_READ_ONLY);
          // update database connection status
          connectedToDatabase = true;
          // set query and execute it
          setQuery(query);
       } // end constructor ResultSetTableModel
       // get class that represents column type
       public Class getColumnClass(int column) throws IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine Java class of column
          try {
             String className = metaData.getColumnClassName(column + 1);
             // return Class object that represents className
             return Class.forName(className);
          } // end try
          catch (Exception exception) {
             exception.printStackTrace();
          } // end catch
          //return Object.class; // if problems occur above, assume type Object
          return getValueAt(0, column).getClass(); // added January 25, 2008 in stead of the one above
       } // end method getColumnClass
       // get number of columns in ResultSet
       public int getColumnCount() throws IllegalStateException {  
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine number of columns
          try  {
             return metaData.getColumnCount();
          } // end try
          catch (SQLException sqlException) {
             sqlException.printStackTrace();
          } // end catch
          return 0; // if problems occur above, return 0 for number of columns
       } // end method getColumnCount
       // get name of a particular column in ResultSet
       public String getColumnName(int column) throws IllegalStateException {   
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine column name
          try {
             return metaData.getColumnName(column + 1); 
          } // end try
          catch (SQLException sqlException) {
             sqlException.printStackTrace();
          } // end catch
          return ""; // if problems, return empty string for column name
       } // end method getColumnName
       // return number of rows in ResultSet
       public int getRowCount() throws IllegalStateException {     
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          return numberOfRows;
       } // end method getRowCount
       // obtain value in particular row and column
       public Object getValueAt(int row, int column)
          throws IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // obtain a value at specified ResultSet row and column
          try {
             resultSet.absolute(row + 1);
             return resultSet.getObject(column + 1);
          } // end try
          catch ( SQLException sqlException ) {
             sqlException.printStackTrace();
          } // end catch
          return ""; // if problems, return empty string object
       } // end method getValueAt
        * Don't need to implement this method unless your table's
        * editable.
      public boolean isCellEditable(int row, int column) { // Added on January 25, 2008 6:51 A.M.
         //Note that the data/cell address is constant,
         //no matter where the cell appears onscreen.
         if (column < 2) {
            return false;
         } else {
            return true;
       // set new database query string
       public void setQuery(String query)
          throws SQLException, IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // specify query and execute it
          resultSet = statement.executeQuery(query);
          // obtain meta data for ResultSet
          metaData = resultSet.getMetaData();
          // determine number of rows in ResultSet
          resultSet.last();                   // move to last row
          numberOfRows = resultSet.getRow();  // get row number    
          // notify JTable that model has changed
          fireTableStructureChanged();
       } // end method setQuery
       // close Statement and Connection              
       public void disconnectFromDatabase() {             
          if (!connectedToDatabase)                 
             return;
          // close Statement and Connection           
          try {                                           
             statement.close();                       
             connection.close();                      
          } // end try                                
          catch (SQLException sqlException) {                                           
             sqlException.printStackTrace();          
          } // end catch                              
          finally { // update database connection status                                          
             connectedToDatabase = false;             
          } // end finally                            
       } // end method disconnectFromDatabase         
    }  // end class ResultSetTableModelThe DisplayQueryResults code follows:
    // DisplayQueryResults.java
    // Display the contents of the Authors table in the
    // Books database.
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import javax.swing.JInternalFrame;
    import java.util.*; // for the Bundle
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    import javax.swing.event.InternalFrameAdapter;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.*; // step 1
    import javax.swing.table.TableModel; // step 1
    public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
       // JDBC driver, database URL, username and password
       ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
       String JDBC_DRIVER = bundle.getString("Driver");
       String DATABASE_URL = bundle.getString("URL");
       String USERNAME = bundle.getString("User");
       String PASSWORD = bundle.getString("Password");
       String DEFAULT_QUERY = bundle.getString("Query");
       private ResultSetTableModel tableModel;
       private JTextArea queryArea;
       static final int xOffset = 0, yOffset = 200;
       // create ResultSetTableModel and GUI
       public DisplayQueryResults() {  
          super("Sales of the Day",
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  false);//iconifiable
          //...Create the GUI and put it in the window...
          //Set the window's location.
          setLocation(xOffset, yOffset);
          // create ResultSetTableModel and display database table
          try {
             // create TableModel for results of query SELECT * FROM authors
             tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
                USERNAME, PASSWORD, DEFAULT_QUERY);
             // set up JTextArea in which user types queries
             queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
             queryArea.setWrapStyleWord(true);
             queryArea.setLineWrap(true);
             JScrollPane scrollPane = new JScrollPane(queryArea,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
             // set up JButton for submitting queries
             JButton submitButton = new JButton("Submit Query");
             // create Box to manage placement of queryArea and
             // submitButton in GUI
             Box box = Box.createHorizontalBox();
             box.add(scrollPane);
             box.add(submitButton);
             // create JTable delegate for tableModel
             final JTable resultTable = new JTable(tableModel);
             resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
             resultTable.setRowSelectionAllowed(true);
             resultTable.getModel().addTableModelListener(this); // step 3
             // place GUI components on content pane
             add(box, BorderLayout.NORTH);
             add(new JScrollPane(resultTable), BorderLayout.CENTER);
             // create event listener for submitButton
             submitButton.addActionListener(
                new ActionListener()
                   // pass query to table model
                   public void actionPerformed(ActionEvent event)
                      // perform a new query
                      try
                         tableModel.setQuery(queryArea.getText());
                      } // end try
                      catch ( SQLException sqlException)
                         JOptionPane.showMessageDialog(null,
                            sqlException.getMessage(), "Database error",
                            JOptionPane.ERROR_MESSAGE);
                         // try to recover from invalid user query
                         // by executing default query
                         try {
                            tableModel.setQuery(DEFAULT_QUERY);
                            queryArea.setText(DEFAULT_QUERY);
                         } // end try
                         catch (SQLException sqlException2) {
                            JOptionPane.showMessageDialog(null,
                               sqlException2.getMessage(), "Database error",
                               JOptionPane.ERROR_MESSAGE);
                            // ensure database connection is closed
                            tableModel.disconnectFromDatabase();
                            System.exit(1); // terminate application
                         } // end inner catch                  
                      } // end outer catch
                   } // end actionPerformed
                }  // end ActionListener inner class         
             ); // end call to addActionListener
             //...Then set the window size or call pack...
                setSize(750,300);
             setVisible(true); // display window 
          } // end try
          catch (ClassNotFoundException classNotFound) {
             JOptionPane.showMessageDialog(null,
                "MySQL driver not found", "Driver not found",
                JOptionPane.ERROR_MESSAGE);
             System.exit(1); // terminate application
          } // end catch
          catch (SQLException sqlException) {
             JOptionPane.showMessageDialog(null, sqlException.getMessage(),
                "Database error", JOptionPane.ERROR_MESSAGE);
             // ensure database connection is closed
             tableModel.disconnectFromDatabase();
             System.exit(1);   // terminate application
          } // end catch
          // dispose of window when user quits application (this overrides
          // the default of HIDE_ON_CLOSE)
          setDefaultCloseOperation(DISPOSE_ON_CLOSE);
          // ensure database connection is closed when user quits application
          addInternalFrameListener(
             new InternalFrameAdapter() {
                // disconnect from database and exit when window has closed
                public void windowClosed(WindowEvent event) {
                   tableModel.disconnectFromDatabase();
                   System.exit(0);
                } // end method windowClosed
             } // end WindowAdapter inner class
          ); // end call to addWindowListener
       } // end DisplayQueryResults constructor
       public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data");
       // execute application
       public static void main(String args[]) {
          new DisplayQueryResults();    
       } // end main
    } // end class DisplayQueryResultsMy problem:
    is in these lines:
    public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data"); // should output in the console
        }How do we notify java that a cell on a row has changed so that we can reflect the changes to the database. The current application shows that the data in cells are editable, but when we edit a cell and hit enter, data changes back to the previous data in that particular cell. And the data as well does not change its state: for example, if a data in the table has a value of boolean value false [checkbox unchecked], I can not modify the checkbox state to checked state. The tableChanged method does not get executed, and therefore, this is a serious error that I cant figure out.
    My question:
    What code should I write so that I will be able to notify java of the changed cell and how do we write the code that will reflect the changed values in a cell into the database?
    Edited by: Oliverbob on Jan 26, 2008 8:40 PM

    This maybe what you're looking for??
    http://developer.java.sun.com/developer/Books/swing2/chapter18-09.html

  • JTable and Database communication

    Hi all,
    I have two files excerpts from my Java application. I feel that in order for me to get understood so well, with regards to a problem that challenged me, I had to post these two files as you can see below. They are called ResultSetTableModel.java and DisplayQueryResults.java [which gets displayed in an internal frame].
    I have this code from ResultSetTableModel
    // ResultSetTableModel.java
    // A TableModel that supplies ResultSet data to a JTable.
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import javax.swing.table.AbstractTableModel;
    // ResultSet rows and columns are counted from 1 and JTable
    // rows and columns are counted from 0. When processing
    // ResultSet rows or columns for use in a JTable, it is
    // necessary to add 1 to the row or column number to manipulate
    // the appropriate ResultSet column (i.e., JTable column 0 is
    // ResultSet column 1 and JTable row 0 is ResultSet row 1).
    public class ResultSetTableModel extends AbstractTableModel
       private Connection connection;
       private Statement statement;
       private ResultSet resultSet;
       private ResultSetMetaData metaData;
       private int numberOfRows;
       // keep track of database connection status
       private boolean connectedToDatabase = false;
       // constructor initializes resultSet and obtains its meta data object;
       // determines number of rows
       public ResultSetTableModel(String driver, String url,
          String username, String password, String query)
          throws SQLException, ClassNotFoundException {        
          // load database driver class
          Class.forName(driver);
          // connect to database
          connection = DriverManager.getConnection(url, username, password);
          // create Statement to query database
          statement = connection.createStatement(
             ResultSet.TYPE_SCROLL_INSENSITIVE,
             ResultSet.CONCUR_READ_ONLY);
          // update database connection status
          connectedToDatabase = true;
          // set query and execute it
          setQuery(query);
       } // end constructor ResultSetTableModel
       // get class that represents column type
       public Class getColumnClass(int column) throws IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine Java class of column
          try {
             String className = metaData.getColumnClassName(column + 1);
             // return Class object that represents className
             return Class.forName(className);
          } // end try
          catch (Exception exception) {
             exception.printStackTrace();
          } // end catch
          //return Object.class; // if problems occur above, assume type Object
          return getValueAt(0, column).getClass(); // added January 25, 2008 in stead of the one above
       } // end method getColumnClass
       // get number of columns in ResultSet
       public int getColumnCount() throws IllegalStateException {  
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine number of columns
          try  {
             return metaData.getColumnCount();
          } // end try
          catch (SQLException sqlException) {
             sqlException.printStackTrace();
          } // end catch
          return 0; // if problems occur above, return 0 for number of columns
       } // end method getColumnCount
       // get name of a particular column in ResultSet
       public String getColumnName(int column) throws IllegalStateException {   
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine column name
          try {
             return metaData.getColumnName(column + 1); 
          } // end try
          catch (SQLException sqlException) {
             sqlException.printStackTrace();
          } // end catch
          return ""; // if problems, return empty string for column name
       } // end method getColumnName
       // return number of rows in ResultSet
       public int getRowCount() throws IllegalStateException {     
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          return numberOfRows;
       } // end method getRowCount
       // obtain value in particular row and column
       public Object getValueAt(int row, int column)
          throws IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // obtain a value at specified ResultSet row and column
          try {
             resultSet.absolute(row + 1);
             return resultSet.getObject(column + 1);
          } // end try
          catch ( SQLException sqlException ) {
             sqlException.printStackTrace();
          } // end catch
          return ""; // if problems, return empty string object
       } // end method getValueAt
        * Don't need to implement this method unless your table's
        * editable.
      public boolean isCellEditable(int row, int column) { // Added on January 25, 2008 6:51 A.M.
         //Note that the data/cell address is constant,
         //no matter where the cell appears onscreen.
         if (column < 2) {
            return false;
         } else {
            return true;
       // set new database query string
       public void setQuery(String query)
          throws SQLException, IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // specify query and execute it
          resultSet = statement.executeQuery(query);
          // obtain meta data for ResultSet
          metaData = resultSet.getMetaData();
          // determine number of rows in ResultSet
          resultSet.last();                   // move to last row
          numberOfRows = resultSet.getRow();  // get row number    
          // notify JTable that model has changed
          fireTableStructureChanged();
       } // end method setQuery
       // close Statement and Connection              
       public void disconnectFromDatabase() {             
          if (!connectedToDatabase)                 
             return;
          // close Statement and Connection           
          try {                                           
             statement.close();                       
             connection.close();                      
          } // end try                                
          catch (SQLException sqlException) {                                           
             sqlException.printStackTrace();          
          } // end catch                              
          finally { // update database connection status                                          
             connectedToDatabase = false;             
          } // end finally                            
       } // end method disconnectFromDatabase         
    }  // end class ResultSetTableModelThe DisplayQueryResults code follows:
    // DisplayQueryResults.java
    // Display the contents of the Authors table in the
    // Books database.
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import javax.swing.JInternalFrame;
    import java.util.*; // for the Bundle
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    import javax.swing.event.InternalFrameAdapter;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.*; // step 1
    import javax.swing.table.TableModel; // step 1
    public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
       // JDBC driver, database URL, username and password
       ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
       String JDBC_DRIVER = bundle.getString("Driver");
       String DATABASE_URL = bundle.getString("URL");
       String USERNAME = bundle.getString("User");
       String PASSWORD = bundle.getString("Password");
       String DEFAULT_QUERY = bundle.getString("Query");
       private ResultSetTableModel tableModel;
       private JTextArea queryArea;
       static final int xOffset = 0, yOffset = 200;
       // create ResultSetTableModel and GUI
       public DisplayQueryResults() {  
          super("Sales of the Day",
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  false);//iconifiable
          //...Create the GUI and put it in the window...
          //Set the window's location.
          setLocation(xOffset, yOffset);
          // create ResultSetTableModel and display database table
          try {
             // create TableModel for results of query SELECT * FROM authors
             tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
                USERNAME, PASSWORD, DEFAULT_QUERY);
             // set up JTextArea in which user types queries
             queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
             queryArea.setWrapStyleWord(true);
             queryArea.setLineWrap(true);
             JScrollPane scrollPane = new JScrollPane(queryArea,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
             // set up JButton for submitting queries
             JButton submitButton = new JButton("Submit Query");
             // create Box to manage placement of queryArea and
             // submitButton in GUI
             Box box = Box.createHorizontalBox();
             box.add(scrollPane);
             box.add(submitButton);
             // create JTable delegate for tableModel
             final JTable resultTable = new JTable(tableModel);
             resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
             resultTable.setRowSelectionAllowed(true);
             resultTable.getModel().addTableModelListener(this); // step 3
             // place GUI components on content pane
             add(box, BorderLayout.NORTH);
             add(new JScrollPane(resultTable), BorderLayout.CENTER);
             // create event listener for submitButton
             submitButton.addActionListener(
                new ActionListener()
                   // pass query to table model
                   public void actionPerformed(ActionEvent event)
                      // perform a new query
                      try
                         tableModel.setQuery(queryArea.getText());
                      } // end try
                      catch ( SQLException sqlException)
                         JOptionPane.showMessageDialog(null,
                            sqlException.getMessage(), "Database error",
                            JOptionPane.ERROR_MESSAGE);
                         // try to recover from invalid user query
                         // by executing default query
                         try {
                            tableModel.setQuery(DEFAULT_QUERY);
                            queryArea.setText(DEFAULT_QUERY);
                         } // end try
                         catch (SQLException sqlException2) {
                            JOptionPane.showMessageDialog(null,
                               sqlException2.getMessage(), "Database error",
                               JOptionPane.ERROR_MESSAGE);
                            // ensure database connection is closed
                            tableModel.disconnectFromDatabase();
                            System.exit(1); // terminate application
                         } // end inner catch                  
                      } // end outer catch
                   } // end actionPerformed
                }  // end ActionListener inner class         
             ); // end call to addActionListener
             //...Then set the window size or call pack...
                setSize(750,300);
             setVisible(true); // display window 
          } // end try
          catch (ClassNotFoundException classNotFound) {
             JOptionPane.showMessageDialog(null,
                "MySQL driver not found", "Driver not found",
                JOptionPane.ERROR_MESSAGE);
             System.exit(1); // terminate application
          } // end catch
          catch (SQLException sqlException) {
             JOptionPane.showMessageDialog(null, sqlException.getMessage(),
                "Database error", JOptionPane.ERROR_MESSAGE);
             // ensure database connection is closed
             tableModel.disconnectFromDatabase();
             System.exit(1);   // terminate application
          } // end catch
          // dispose of window when user quits application (this overrides
          // the default of HIDE_ON_CLOSE)
          setDefaultCloseOperation(DISPOSE_ON_CLOSE);
          // ensure database connection is closed when user quits application
          addInternalFrameListener(
             new InternalFrameAdapter() {
                // disconnect from database and exit when window has closed
                public void windowClosed(WindowEvent event) {
                   tableModel.disconnectFromDatabase();
                   System.exit(0);
                } // end method windowClosed
             } // end WindowAdapter inner class
          ); // end call to addWindowListener
       } // end DisplayQueryResults constructor
       public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data");
       // execute application
       public static void main(String args[]) {
          new DisplayQueryResults();    
       } // end main
    } // end class DisplayQueryResultsMy problem:
    is in these lines:
    public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data"); // should output in the console
        }How do we notify java that a cell on a row has changed so that we can reflect the changes to the database. The current application shows that the data in cells are editable, but when we edit a cell and hit enter, data changes back to the previous data in that particular cell. And the data as well does not change its state: for example, if a data in the table has a value of boolean value false [checkbox unchecked], I can not modify the checkbox state to checked state. The tableChanged method does not get executed, and therefore, this is a serious error that I cant figure out.
    My question:
    What code should I write so that I will be able to notify java of the changed cell and how do we write the code that will reflect the changed values in a cell into the database?
    Edited by: Oliverbob on Jan 26, 2008 9:54 PM

    Why don't you check out the link shown below:
    http://www.aokabc.com
    and just follow the white rabbit!
    ;o)
    V.V.

  • Problem with JTable and JPanel

    Hi,
    I'm having problems with a JTable in a JPanel. The code is basicly as follows:
    public class mainFrame extends JFrame
            public mainFrame()
                    //A menu is implemeted giving rise to the following actions:
                    public void actionPerformed(ActionEvent evt)
                            String arg = evt.getActionCommand();
                            if(arg.equals("Sit1"))
                            //cells, columnNames are initiated correctly
                            JTable table = new JTable(cells,columnNames);
                            JPanel holdingPanel = new JPanel();
                            holdingPanel.setLayout( new BorderLayout() );
                            JScrollPane scrollPane = new JScrollPane(holdingPanel);
                            holdingPanel.setBackground(Color.white);
                            holdingPanel.add(table,BorderLayout.CENTER);
                            add(scrollPane, "Center");
                            if(arg.equals("Sit2"))
                                    if(scrollPane !=null)
                                            remove(scrollPane);validate();System.out.println("ScrollPane");
                                    if(holdingPanel !=null)
                                            remove(holdingPanel);
                                    if(table !=null)
                                            remove(table);table.setVisible(false);System.out.println("table");
                            //Put other things on the holdingPanel....
            private JScrollPane scrollPane;
            private JPanel holdingPanel;
            private JTable table;
    }The problem is that the table isn't removed. When you choose another situation ( say Sit2), at first the table apparently is gone, but when you press with the mouse in the area it appeared earlier, it appears again. How do I succesfully remove the table from the panel? Removing the panel doesn't seem to be enough. Help is much appreciated...
    Best regards
    Schwartz

    If you reuse the panel and scroll pane throughout the application,
    instantiate them in the constructor, not in an often-called event
    handler. In the event handler, you only do add/remove of the table
    on to the panel. You can't remove the table from the container
    which does not directly contain it.
    if (arg.equals("Sit2")){
      holdingPanel.remove(table);
      holdingPanel.revalidate();
      holdingPanel.repaint(); //sometimes necessary
    }

  • Problem about put and get

    hi there,
    I met a problem, when i put the data, and get it.
    key data
    aaa aaaaaa
    bbb bbbbbb
    ccc cccccc
    I have put "aaa", "bbb" and "ccc" into db, but when I try to get the key for "aaa" , "bbb", it return the data "cccccc", how can I solve it?
    after that, when i get the key "ddd", "eee" , and all strings are length 3, the key does not in the DB, it also return the data "cccccc". Did I do something wrong on my code?
    void Set1(CString sKey)
    int ret;
    std::string sdb = "test.db";
    Db db(NULL, 0);
    ret = db.open(NULL,
         sdb.c_str(),
         NULL,
         DB_BTREE,
    DB_CREATE,
         0);
    std::string skey, sdata;
    skey = sKey;
    sdata.append(skey);
    sdata.append(skey);
    Dbt key(&skey, skey.length());
    Dbt data(&sdata, sdata.length());
    ret = db.put(NULL, &key, &data, 0);
    if(ret==0){
    TRACE("success\n");
    ret = db.close(0);
    void Get1(CString sKey)
    int ret;
    std::string sdb = "test.db";
    ret = db.open(NULL,
    sdb.c_str(),
         NULL,
         DB_BTREE,
         DB_CREATE,
         0);
    Dbc *cur;
    ret = db.cursor(NULL, &cur, 0);
    std::string skey, s2, a2;
    skey = sKey;
    Dbt key(&skey, skey.length());
    Dbt data;
    memset(&data, 0, sizeof(data));
    ret = cur->get(&key, &data, DB_SET);
    if(ret!=DB_NOTFOUND){
    a2 = (std::string*) data.get_data();
    s2 = (std::string*) key.get_data();
    TRACE("FOUND %s %s\n", s2->c_str(), a2->c_str());
    ret = cur->close();
    ret = db.close(0);
    }

    Hi,
    The problem seems to be with these lines:
    std::string skey, sdata;
    Dbt key(&skey, skey.length());
    Dbt data(&sdata, sdata.length());You are constructing a Dbt with data that is actually a pointer to a C++ std::string object. You want the value to be an actual c style string.
    An alternative would be to construct the Dbts like:
    Dbt key(skey.c_str(), skey.length());
    Dbt data(sdata.c_str(), sdata.length());You will need to create a new std::string out of any data retrieved from the database as well. Since it will now be just a C-style char * string.
    I hope this helps.
    Regards,
    Alex Gorrod, Oracle

  • Problem about rmic and rmiregistry

    I am new to java!
    My OS is Win2000 and the java compiler I installed is Sun One Studio 4 CE. The teaching book I used is teh JAVA2 unleash.
    I try to copy some example in the book and run it! The problem I have the book didn't quite tell me how to compile it!
    The chapter is about the RMI and the step describe in the book are followed:
    1) Move to the directory containing all your classes and compile them. (Which I did)
    2) Move to the root directory
    c:\>rmic unleashed.ch2.GreeterImpl (problem)
    3) Open one command window and type
    c:\> rmiregistry (problem)
    4) Open another command window and type
    c:\> java unleashed.ch2.GreeterServer
    5) open the thrid window and type
    c:\> java unleashed.ch2.GreetingClient
    Problem part:
    I try to follow the step and open a DOS Prompt and type step two and three!! It seems that the window don't understand the command rmic and rmiregistry! What should I do??
    Thank you very much for helping! Thanks!!
    Ferdinand

    you need to add the java bin directory to your 'path' system environment variable

Maybe you are looking for

  • I was able to use one of my itunes songs for my ringtone but can I use one for my text tone?

    I was able to use one of my itune songs for a ringtone but I'd like to use one of my own songs for a text tone.  Is that possible?

  • Newb question: page size and bindings

    Hi all, I'm having trouble with two things (probably many more to come). 1) In the "discover berkeley" presentation, it said I could change the page size in my database. Where is that configurable? 2) I've read in the manuals that to store values in

  • Internal ITS, ITS_ERRMSG_EXCEPTION SAPMSYST

    Dear Sirs, I am currently facing an issue with an IAC based on the standard WSTA (some modification to the IAC) program by SAP. It runs quite well, but it looks like out of a 500 user sessions I have got three similar short dumps. The error message i

  • Problem with SAP Directory

    Hi, I have to transfer some records from internal table field (type string) to SAP Directory(AL11) Directory:  /sapmnt/CRD/qoutsap, some of the records are very large (around 800 characters). for larger record it is not displaying the complete string

  • Accessing SQL Server from ORACLE using Transparent Gateway

    So I had downloaded the gateway installer and was following the guide here to set up the Transparent Gateway for SQL Server: http://www.orafusion.com/art_orahs.htm After I had created the database link, I was prompted the following error when trying