JTable &  AbstractTableModel(Delete row problem)

Hi!!
I have used AbstractTableModel in my JTable.In case of multiple rows, i want to delete rows from interface as well as from database. As removeRow method is absent in AbstractTableModel.so DefaultTableModel has been used by casting but CastClassException throws. Here is Partial code(tried in many ways).Plz help me to solve the problem.
void jButtonCancel_actionPerformed(ActionEvent e) {
try{
jTable1.setModel(myModel); //jtable is object of JTable and myModel is of Abstract TableModel           
DefaultTableModel model=((DefaultTableModel)jTable1.getModel());
int row=jTable1.getSelectedRow();
if(row>=0){
model.removeRow();
jTable1.revalidate();
model.fireTableDataChanged();
System.out.println("Rows Delete");
catch(Exception sq){
sq.printStackTrace();
sq.getMessage();

Hmm...
A bit of studying java awaits you.
Anyway.
Your class:
public class MyModel extends AbstractTableModel
  // Do various sorts of coding here
}Is not an instance of DefaultTableModel, so, if you try to cast your model to a DefaultTableModel it will throw an exception since the conversion is impossible.
Recomended solution:
Add a remove method for your class MyModel that does the following:
public void removeRow(int row)
  // data removed
  // fire removed data event
}Then instead of casting to DefaultTableModel, cast it to 'MyModel' and call the method 'removeRow'.
When it comes to inheritance and casting you can always cast an object to any of it's superclasses or any of the interfaces it supplies or it's superclasses suppplies. You can not cast an object to a instance of which it has no relation with.
In you example, your table model class extends the abstract table model but it does not extend the DefaultTableModel. An instance of your class can be casted to AbstractTableModel and so can an DefaultTableModel because they are both subclasses from AbstractTableModel. They can also be casted to TableModel since all of these implement the interface needed to fullfill TableModel's specification.
If you cast a DefaultTableModel instance to TableModel you can not try to cast it upwards to something the instance wasn't from the beginning.
Example:
DefaultTableModel dtm = new DefaultTableModel();
// When you do casting uppwards, there is no need for paranthesis
TableModel tm = dtm;
// You can easily later on cast this back to what is what or to any step
// in between
DefaultTableModel stillSameModel = (DefaultTableModel)tm;
// You can not however cast to something the instance never was
// Row below will cause an compile error:
JComboBox jb = (JComboBox)dtm;
// This since JComboBox can never be an superclass to the DefaultModel
// More dangerous errors that can't be catched until runtime is the
// one you made. Ie: I do what could be an valid cast
MyModel mm = (MyModel)tm;
// Since MyModel is an TableModel and tm refers to an TableModel,
// this casting is approved by the compiler.
// It will on the other hand throw an ClassCastException when run since
// the variable tm contains an instance of DefaultTableModel which
// is not an MyModel instance.Recomended that you read up on inheritance and basic OO.
Regards,
Peter Norell

Similar Messages

  • Add/Delete Rows problem

    I'm having a problem with the add row and delete row for my table.  I have a table set up with the add row button in the header, and the delete row button in the first cell of the row beneath the header.  I have it set so that the initial count of the row is 2.  My problem is if the user adds several rows with data, and save the form.  When that user goes back into the same form later, it keeps the several rows that the user entered, which is fine, but then it automatically adds 3 more blank rows to the table, which I don't want.  I don't understand why it is doing this.  Does anyone have a clue to why this is happening?
    Thanks
    Connie

    Hi Connie,
    Just make sure that you have checked the below thing.\
    File > Form Properties > Run tIme > Scripting > Automatically is checked.
    Thanks,
    Bibhu.

  • Problem deleting rows from a JTable

    I've got an editable JTable and a button outside that deletes rows selected by a user from the model. The problem is that if the user has clicked on an editable cell in the table, while rest of the information in that row is deleted, the entry in the editable cell remains. So even though the entry has been deleted from the model, the JTable does not update correctly. I am using a custom editor/renderer for the editable cells.
    So it appears that I need to get my custom editor to release, i.e., stop editing on demand, so I can reset the information on the entire row properly.
    Any ideas how I can do so ?
    Thanks, Bhishma

    Thanks that worked perfectly ! Full points assigned.
    In case the above link stops working the solution that worked for me was using a client property as below.
    jTable1.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    Ciao.
    Edited by: Bhishma on Dec 20, 2008 7:53 PM

  • Delete rows from table...Bizarre problem.

    Folks
    i HAVE this bizarre problem.
    I hava a Java class which displays data read into a table with a delete
    option by the side of each row.
    Now lets assume you have 3 rows in the Table.
    abc deleteButton
    efg deleteButton
    xyz deleteButton
    When I click the first delete,that row gets deleted from the table.(perfect...)
    Now I have 2 rows.
    When I click on the first row,I get the error
    'You clicked -1'
    java.lang.ArrayIndexOutofBoundsException: -1 < 0.
    Can anyone tell me why this is happening even though there are rows in the table.???
    ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println("You clicked row : " + table.getSelectedRow());
    javax.swing.table.TableModel model = table.getModel();
    Object o = model.getValueAt(table.getSelectedRow(),0);
    //System.out.print(model.getValueAt(table.getSelectedRow(), 0));
    //System.out.println();
    MyDeleteFunction(o.toString());
    // Delete row from window.
    ((DefaultTableModel)table.getModel()).removeRow(table.getSelectedRow());
    table.revalidate();
    table.repaint();

    Hi ritu,
    This class is called
    new DisplayCall_IDTodisconnect(hashTable);
    its a long file.
    its attached below.
    The rows are displayed by reading a hashtable into a vector
    and the vector is iterated and appended..
    public class DisplayCall_IDToDisconnect {
    public static JTable createTable(Vector data, String buttonLabel, ActionListener action){
    return createTable(data.iterator(), buttonLabel, action);
    public static JTable createTable(
    Iterator dataIterator,
    String buttonLabel,
    ActionListener action) {
    DefaultTableModel model = new DefaultTableModel() {
    public boolean isCellEditable(int row, int col) {
    return col == 1;
    model.setColumnCount(2);
    while (dataIterator.hasNext()) {
    Object[] row = { dataIterator.next().toString(), null };
    model.addRow(row);
    DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
    columnModel.addColumn(new TableColumn(0, 100));
    columnModel.addColumn(new TableColumn(1, 80,
    new TableButtonCellRenderer(buttonLabel),
    new TableButtonCellEditor(buttonLabel, action)
    JTable table = new JTable(model, columnModel) {
    public void valueChanged(ListSelectionEvent e) {
    super.valueChanged(e);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    return table;
    private static class TableButtonCellRenderer implements TableCellRenderer {
    final JButton button;
    TableButtonCellRenderer(String buttonLabel) {
    button = new JButton(buttonLabel);
    public Component getTableCellRendererComponent(
    JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus, int row, int column) {
    return button;
    private static class TableButtonCellEditor
    extends AbstractCellEditor
    implements TableCellEditor, ActionListener {
    final JButton button;
    final ActionListener callback;
    TableButtonCellEditor(String buttonLabel, ActionListener callback) {
    button = new JButton(buttonLabel);
    this.callback = callback;
    button.addActionListener(this);
    public Component getTableCellEditorComponent(
    JTable table,
    Object value,
    boolean isSelected,
    int row, int column) {
    return button;
    public Object getCellEditorValue() {
    return null;
    public void actionPerformed(ActionEvent e) {
    button.getParent().requestFocus();
    callback.actionPerformed(e);
    static JTable table;
    Vector items;
    final ClientManager clientMgr;
    // Constructor.
    public DisplayCall_IDToDisconnect(Hashtable callLegTable,ClientManager clientMgr){
    Vector vCSeqnos = displayCSeqNos(callLegTable);
    this.clientMgr = clientMgr;
    JFrame frame = new JFrame("Disconnect Options");
    /*Vector*/ items = new Vector();
    Enumeration vEnum = vCSeqnos.elements();
    while(vEnum.hasMoreElements()){
    items.add(vEnum.nextElement());
    ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    //System.out.println("You clicked row ,col: " + table.getSelectedRow()+
    // table.getSelectedColumn());
    javax.swing.table.TableModel model = table.getModel();
    Object o = model.getValueAt(table.getSelectedRow(),0);
    System.out.print(model.getValueAt(table.getSelectedRow(), 0));
    System.out.println();
    closeConnection(o.toString());
    // Delete row from window too.
    ((DefaultTableModel)table.getModel()).removeRow(table.getSelectedRow());
    table.revalidate();
    table = DisplayCSeqNos.createTable(items, "Disconnect", al);
    frame.getContentPane().add(new JScrollPane(table));
    frame.pack();
    frame.show();
    } // End Constructor.
    public void closeConnection(String s){
    /*1. Disconnect the current session*/
    this.clientMgr.disconnectCall(s);
    /*2. refresh the Disconnect window*/
    this.refreshWindow();
    public Vector displayCSeqNos(Hashtable callLegTable){
    Enumeration eNum;
    String str;
    Vector v = new Vector();
    eNum=callLegTable.keys();
    while(eNum.hasMoreElements()){
    str = (String) eNum.nextElement();
    //System.out.println("Key : " + str + " Value : " + callLegTable.get(str));
    v.addElement(str);
    return v;
    } // End of displayCSeqNos.

  • Add/delete row in JTable

    I went through the tutorial of JDK about how to programming JTable, i can NOT find a way to add/delete row into/from JTable.
    I immagine it would be a difficult task because the data set it takes 'Object data[][]' is NOT dynamically grow/shrinkble.
    Can we make it take ArrayList[] as input dataset so that the dataset can dynamically grow/shrink?
    Any other way around to add/delete row?
    THANKS for your consideration.

    You have to write your own TableModel like extending AbstractTableModel. In that class add custom methods to add and remove rows. From those methods call fireTableRowsDeleted(..) and fireTableRowsInserted(..) to update UI.

  • Delete  row  internal  bank  problem

    Hi,
    i  wasn't  able  to   delete   row  of   my  internal  bank,  despite  i   delete  this  bank   in  my   BP  account and   in  all  payment  method.
    Also   i   delete   all  the  information  in  internal  banck  account  (  branch,  count  number,  iban,etc)  but  when  i  delete  the  row  the  system  give  me  this  messagge  error
    bank account is currently in use and therefore can not be eliminated  705-20 
    i   currently  use   2007A   SP  01   patch  level  7
    how  can  i  resolve  this   problem?  thanks  a  lot

    Hi,
    thanks   a   lot,   but   this  bank   is  not   linked   to  any  one  field  in  Sap  B1
    1)  in  initial  details  there   isn't
    2)   in  payment   methods  there  isn't 
    3)  in  registry  BP  there   isn't
    where  can  i   has   to   find   it????
    By  copy  espress  i   had  copied  all  payment  methods  (  with  this  bank),  and  after   i   deleted   this   payment   methods  without   using  this  payment  method   in  anyone   Sap  b1  documents....and here the strange thing

  • Delete row in JTable

    Hello I am new To JAVA SWING
    I have 2 questions related to JTable
    1) How do i remove selected row in JTable ...for instance, I click on the row to delete (It is selected) , later I press the delete button, and then row is removed .... any hints ?
    2) If I would like to save the rows in a JTable into a database , .... How can iterate through the rows in the JTable..each row .... the rows are saved in a List object...and a List Object is what I pass as a parameter in a class method in order to be saved into Database.
    Thanks,
    deibys

    1) use the removeRow(...) method of the DefaultTableModel
    20 use table.getModel().getValueAt(...) to get the data from the model and create your list Object.

  • Deleting rows from a JTable

    Hello,
    I've got a JTable which is based on a 2-dimensional array, which contains my data. Now I want to delete several rows from the JTable. There's the possibility to modify my data-array by creating a new array which doesn't contain anymore the datasets I want to delete. Afterwards I can redraw the table and my rows are deleted. But I think that's a very complicated way to delete rows from a JTable. Can anybody tell me whether ther's an easier way to do so ? I'd really be pleased...
    Thanx,
    Findus

    When you create a TableModel using a two-dimensional array or a Vector of Vectors, a DefaultTableModel is created and it stores the data in its own Vector of Vectors. The DefaultTableModel supports methods for adding/removing rows of data. To remove the first row in the table you would do something like:
    DefaultTableModel model = (DefaultTableModel)table.getModel();
    model.removeRow( 0 );
    Note: once you create the TableModel you should set your array to null as it is not used anymore.

  • MySQL+JTable, AbstractTableModel - solution v.0.1 beta

    Hi everybody, My name is Sergey, I am a student from Russian Federation, Moscow.
    I spent days and nights trying to find how to connect JTable, DB tables.
    To tell you the truth, I visited many russian and english-lang forums. But I didn't get somewhere goog answer. that is terrible.
    Seems like nobody nows how to do simple things.
    So, I've started to do on my own. And I suggest you the first version.
    Ofcourse it is rather raw, but it works.
    Sometimes I was really angry when people suggested others untested and foolish code. With mistakes.
    what we need:
    JDBC adapter - mysql.com (you canget it)
    MySQL server (must be started)
    DB
    Tables in DB
    NetBeans 5.5 - netbeans.org
    NB MySQL server on localhost, thisway you will not need to dig mysql config files
    Create new project application
    Add mysql driver jar file to project library (it is in project window)
    create two classes and enjoy
    import java.sql.*;
    import java.util.Collections;
    import java.util.List;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.table.AbstractTableModel;
    import java.util.Collections;
    * @author SShpk
    //we are going to override methods of AbstracTableModel Class
    /**This class forms view of DB table which will be loaded into JTable swing component*/
    public class JTableAdapter extends AbstractTableModel{
            //my table name
            private String tableName ="Sheet";
         //frame for error exception output
            private JFrame jframeError = new JFrame("Connection error");
            //variables for transactions
            private Connection connection;
            private Statement  statement;
            private ResultSet  resultSet;
            private ResultSetMetaData metaData;
            //names of colums --- will get them from DB table
            public  String[]   columnNames;
            //this Vector will  keep rows of table
            private Vector     rows = new Vector();
            private int i;
            private String t="";
        /** Creates a new instance of JTableAdapter */
        public JTableAdapter(String url, String driverName, String user, String password) {
            jframeError.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//frame for showing errors
            //this String var I use to avoid problem with Date/Datestamps e.t.c. like �0000-00-00�
         //because java converts them to NULL. This is terrible fact. Do not lose this comment!
            String overrideBADDATE="zeroDateTimeBehavior=convertToNull&";
         //let�s put together all params
            //common view is: :jdbc:mysql://yourhost.com:port_num/NameofYourDB?<property&>
            t=url+overrideBADDATE+"user="+user+"&password="+password;
            try{     //trying to load driver
                Class.forName(driverName);
                connection=DriverManager.getConnection(t);
                statement = connection.createStatement();
                                    //this commented code will be useful for you in debug proccess.
                                    //it will give you list of all loaded drivers to driver managers
                                    //so you will be able to see is your jdbc driver loaded or not.
                                     try{
                                          List drivers = Collections.list(DriverManager.getDrivers());
                                          for(int i=0;i<drivers.size();i++){
                                              Driver driver = (Driver)drivers.get(i);
                                              String driverName1 = driver.getClass().getName();
                                              System.out.println("Driver "+i+":::"+driverName1);
                                     }catch(Exception e){
                                          System.out.println(e);
                                     }//catch in try
            }//try
            //let's catch exceptions.
            //see messages to get the meaning of exception
            catch(ClassNotFoundException ex){
                         JOptionPane.showMessageDialog(jframeError,
                                                        "Error occurred during driver load"+driverName,
                                                        "Driver load error:"+ex.getMessage(),
                                                        JOptionPane.ERROR_MESSAGE);
                                                        jframeError.setVisible(true);
            }//catch1
            catch(SQLException ex){
                         JOptionPane.showMessageDialog(jframeError,
                                                        "Error connecting DB"+url,
                                                        "DB Connection error:"+ex.getMessage(),
                                                        JOptionPane.ERROR_MESSAGE);
                                                        jframeError.setVisible(true);
            }//catch2
        //executing SELECT query to fill our table
         executeQuery("SELECT * FROM " + this.tableName);  
        }//constructor
        /**method sends SELECT query and parses result of this query*/
        public void executeQuery(String query){
            //testing for alive connection
            if(connection== null || statement == null){
                            JOptionPane.showMessageDialog(jframeError,
                                                        "Error occurred during query post",
                                                        "DB connection error",
                                                        JOptionPane.ERROR_MESSAGE);
                                                        jframeError.setVisible(true);
         //let�s parse result of query
            try{
                resultSet = statement.executeQuery(query);
                //get num of columns in table   /***/getColumnCount()
                //get names of columns          /***/getColumnLabel(i+1)
                metaData = resultSet.getMetaData();
                int numberOfColumns = metaData.getColumnCount();
               //getting names of DB table columns
                columnNames = new String[numberOfColumns];
                for(i=0;i<numberOfColumns;i++){
                        columnNames= metaData.getColumnLabel(i+1);
    }//for
    Object testnulledobj;
    rows = new Vector();
    //from the beginning of resultSet up to the END
    while (resultSet.next()){
    //each row of DB table is Vector
    Vector newRow = new Vector();
    for (i=1; i<= getColumnCount();i++){
    testnulledobj=resultSet.getObject(i);
         //this IF statement I will develop
    //to output NULL-object Date (like Date field = 0000-00-00)
    if(resultSet.wasNull()){
    testnulledobj=new String("");
    newRow.addElement(testnulledobj);
    }//for
              //row from DB is completed. Every row will be in Vector of Rows.
              //I hope you got my idea.
              //We collect row cells of DB table row in Vector
              //Then we put this Vector into another Vector, which consists of DB rows
    rows.addElement(newRow);
    }//while
    //table is changed
    fireTableChanged(null);
    }//try
    catch(SQLException ex){
    JOptionPane.showMessageDialog(jframeError,
    "Error occurred during query result parsing",
    "Data accept error",
    JOptionPane.ERROR_MESSAGE);
    jframeError.setVisible(true);
    }//executeQuery
    /**cell of table editable or not?*/
    public boolean isCellEditable(int row,int column){
    /*Testing field(aka column) property. We get it from DB.
    try{
    return metaData.isWritable(column+1);
    }//try
    catch(SQLException e){
    return false;
    }//catch
    /****LOCKING ID FIELD***/
    if(column>0) return true;
    else return false;
    }//isCellEditable
    //these three methods very simple. I think they do not need any explanations
    /**set column name in JTable*/
    public String getColumnName(int column){
    return this.columnNames[column];
    /**get quantity of rows in table*/
    public int getRowCount(){
    return this.rows.size();
    /**get quantity of columns in table*/
    public int getColumnCount(){
    return this.columnNames.length;
    /**get value from JTable cell*/
    public Object getValueAt(int aRow, int aColumn){
    Vector row = (Vector)rows.elementAt(aRow);
    return row.elementAt(aColumn);
    //if user edited cell (double-click on it and then went away)
    //we need to update DB table and JTable also.
    //this is not pretty good variant, because we will flood DB with plenty of small queries.
    //the best way is to save value of "double-clicked" cell. Then we have to compare its value before
    //focus and after. If values differ, then we update DB table, else � no update
    //unfortunately I do not know how to control focus method of JTable cell
    /**update DB table cell value*/
    public void setValueAt(Object value, int row, int column){
    //Before updating DB table cell we need to update JTable cell
    Object val;
    val = tbRepresentation(column, value);
    Vector dataRow = (Vector)rows.elementAt(row);
    dataRow.setElementAt(val,column);
    //Now it's time to update DB table
    try{
    //get name of column in DB table (our JTable has the same column names)
    //it's possible to give them normal names instead of user_id,user_name e.t.c.
    //I am sure, user of your app will prefer to see normal names of columns, not like listed before
    String columnName = getColumnName(column);
    //This is very bad example of update query.
    //You have to determine automatically key field. but still I didn't find how to do that
    //But it's possible to do through metadata. I am sure.
    //Just need some more time
    //When I am designing DB I prefer to name key field in each table as "ID"
    String query = "UPDATE "
    tableName
    " SET "+columnName+" = "+"'"+dbRepresentation(column,getValueAt(row, column))+"'"+
    " WHERE ID = "+dbRepresentation(0,getValueAt(row, 0));
    //extremely important string for debug
    System.out.println("UPDATE QUERY:::"+query);
    //executing update query
    PreparedStatement pstmt = connection.prepareStatement(query);
    pstmt.executeUpdate();
    }//try
    catch(Exception ex){
    JOptionPane.showMessageDialog(jframeError,
    "������ ��� ���������� ������ � ������� ��",
    "������ �������� ��� ���������� ������ � ��",
    JOptionPane.ERROR_MESSAGE);
    jframeError.setVisible(true);
    }//catch
    }//setValueAt
    //Next two methods are very neccessary. And they need accurate testing
    //they convert DB datatypes into java datatypes and backwards
    /**convert SQL (MySQL in this case) datatypes into datatypes which java accepts*/
    public Object tbRepresentation(int column, Object value) throws NumberFormatException{
    Object val;
    int type;
    if(value == null){
    return "null";
    }//if null
    try{
    type = metaData.getColumnType(column+1);
    }//try
    catch (SQLException e){
    JOptionPane.showMessageDialog(jframeError,
    "Error occured during Table update",
    "Error occured during DB table field type get",
    JOptionPane.ERROR_MESSAGE);
    jframeError.setVisible(true);
    return value.toString();
    }//catch
    switch(type){
    case Types.BIGINT:
    return val = new Long(value.toString());
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    return val = new Integer(value.toString());
    case Types.REAL:
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.DECIMAL:
    return val = new Double(value.toString());
    case Types.CHAR:
    case Types.BLOB:
    case Types.VARCHAR:
    case Types.LONGNVARCHAR:
    return val = new String(value.toString());
    case Types.DATE:
    return val = new String(value.toString());
    default: return val = new String(value.toString());
    }//switch
    }//tbRepresentation
    /**conver Java datatypes into SQL (MySQL) datatypes*/
    public Object dbRepresentation(int column, Object value){
    Object val;
    int type;
    if(value == null){
    return "null";
    }//if null
    //my preparations for accurate work with "nulled" dates/time/e.t.c
    //this IF statement doesn't play any important role
    String testbaddate="0000-00-00";
    if(value.toString().equals(testbaddate)){
    return value.toString();
    try{
    type = metaData.getColumnType(column+1);
    }//try
    catch (SQLException e){
    return value.toString();
    }//catch
    switch(type){
    case Types.BIGINT:
    return val = new Long(value.toString());
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    return val = new Integer(value.toString());
    case Types.DECIMAL:
    case Types.FLOAT:
    case Types.DOUBLE:
    return val = new Double(value.toString());
    case Types.VARCHAR:
    case Types.CHAR:
    return val = new String(value.toString());
    case Types.DATE:
    return val = new String(value.toString());
    default: return val = new String(value.toString());
    }//switch
    }//dbRepresentation
    //my preparations to read from SELECT query result
    //"nulled" dates/time/e.t.c.
    private Object testObject(Object obj){
    Object val= new String("");
    if(obj==null) return new String(val.toString());
    else return obj;
    }//class
    And other class. I will not comment it.
    It is very easy. Ask me if you want something
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class TableCreate extends JPanel{
        /** Creates a new instance of TableCreate */
        public TableCreate() {
            super(new GridLayout(1,0));
            JTable table = new JTable(new JTableAdapter("jdbc:mysql://localhost/Document?","com.mysql.jdbc.Driver","root",""));
            table.setPreferredScrollableViewportSize(new Dimension(500,210));
            JScrollPane scrollpane = new JScrollPane(table);
            add(scrollpane);
        public JPanel getJpanelTable(){
            return this;
        public static void main(String[] args){
            JFrame jframe = new JFrame("Test");
                TableCreate tcreate = new TableCreate();
                    jframe.add(tcreate.getJpanelTable());
                    jframe.pack();
                    jframe.setVisible(true);
    }//main

    So what we have:
    -DB table insert into JTable
    -Can edit values+update them in DB
    -override some common "critical points"
    What we need:
    -control row,col size in JTable
    -control column names in JTable
    -add combobox on fields which keep ID of other instance (I will give test example later)
    -add checkbox to boolean fields and to boolean fields which declared as int-family type, but use only "0" and "1" numbers
    -Add sort to JTable (to its header)
    -Add conrol buttons
    --new row
    --delete row
    --next record
    --previous record
    -Add user friendly GUI (highlight selected row e.t.c.)
    So as you can see, a lot of things to do
    I will be happy to answer all you questions
    But if you want to make me really happy- comment my post and suggest me how to refact code and approach this JTableAdapter class to reusable component (I want it to be useful in common cases when Java-specialist work with DB especially with MySQL)

  • Right way to delete row before insert

    I create a new row with method of ViewObject.
    Row row = viewObject.createRow();Then I want to delete this row. I found there are 4 methods. Which is the right answer?
    //1.
    row.remove();
    //2.
    row.refresh(Row.REFRESH_REMOVE_NEW_ROWS);
    //3.
    row.refresh(Row.REFRESH_FORGET_NEW_ROWS);
    //4.
    row.removeFromCollection();Thanks,

    Timo, we're having a problem when deleting as you describe, maybe you can offer some advice?
    We have a button to delete a row from an editable table, this is set to immediate=true (obviously the user should be able to skip validation when doing a delete). After deleting, if the user then clicks another button to add a new row, the values from the deleted row show in the new row :(
    If we set immediate=false this seems to fix the problem, but we then get the undesirable side effect that the user has to make sure all the values in the row are correct before it can be deleted (because the validation is firing). The user experience becomes a bit strange.

  • PL/SQL procedure for deleting rows

    We have to delete rows from a table by initiating parallel processes depending on no of connections, and also variable commit frequency. The procedure has to start by itself in case of failure of 1 or more parallel processes, by identifying the position where it stopped. Please some one help me what would be th elogic needed to write the [rocedure.
    Thanks in Advance
    Edited by: 864979 on Jun 9, 2011 10:02 PM

    Be careful of how this is designed and coded. It is very easy to do it horribly wrong, causing contention and problems.
    Have a look at DBMS_PARALLE_EXECUTE.
    If the package is not available on your Oracle version, then look at {message:id=1534900} for a manual approach.

  • Delete row in a table (not ALV)

    i have a table on my web-dynpro-view. I defined a delete-Button and a method with some coding.
    If the User marks a row and press the button, the row is deleted. Here's the code:
    METHOD onactioneintrag_loeschen .
      DATA:  wd_node TYPE REF TO if_wd_context_node,
             wa_temp  TYPE REF TO if_wd_context_element,
             lt_temp  TYPE wdr_context_element_set.
      wd_node = wd_context->get_child_node( name = 'LV' ).
      CALL METHOD wd_node->get_selected_elements
        RECEIVING
          set = lt_temp.
      LOOP AT lt_temp INTO wa_temp.
        wd_node->remove_element( EXPORTING element = wa_temp ).
      ENDLOOP.
    ENDMETHOD.
    My problem: in the context-change-log i can't identify the deleted rows. It's impossible to make a difference between a change of selection and a delete.

    Hi David,
    You can declare one attribute in the view of type ur row.
    and store the deleted row in this attribute in ur delete method.
    DATA: wd_node TYPE REF TO if_wd_context_node,
    wa_temp TYPE REF TO if_wd_context_element,
    lt_temp TYPE wdr_context_element_set.
    wd_node = wd_context->get_child_node( name = 'LV' ).
    CALL METHOD wd_node->get_selected_elements
    RECEIVING
    set = lt_temp.
    LOOP AT lt_temp INTO wa_temp.
    <Attribute_name> = wa_temp .
    wd_node->remove_element( EXPORTING element = wa_temp ).
    ENDLOOP.
    ENDMETHOD.
    Hope this will help you.
    Thanks & Regards,
    Arvind

  • How to delete rows in the target table using interface

    hi guys,
    I have an Interface with source as src and target as tgt both has company_code column.In the Interface i need like if a record with company_code already exists we need to delete it and insert the new one from the src and if it is not availble we need to insert it.
    plz tell me how to achieve this?
    Regards,
    sai.

    gatha wrote:
    For this do we need to apply CDC?
    I am not clear on how to delete rows under target, Can you please share the steps to be followed.If you are able to track the deletes in your source data then you dont need CDC. If however you cant - then it might be an option.
    I'll give you an example from what im working on currently.
    We have an ODS, some 400+ tables. Some are needed 'Real-Time' so we are using CDC. Some are OK to be batch loaded overnight.
    CDC captures the Deletes no problem so the standard knowledge modules with a little tweaking for performance are doing the job fine, it handles deletes.
    The overnight batch process however cannot track a delete as its phyiscally gone by the time we run the scenarios, so we load all the insert/updates using a last modified date before we pull all the PK's from the source and delete them using a NOT EXISTS looking back at the collection (staging) table. We had to write our own KM for that.
    All im saying to the OP is that whilst you have Insert / Update flags to set on the target datastore to influence the API code, there is nothing stopping you extending this logic with the UD flags if you wish and writing your own routines with what to do with the deletes - It all depends on how efficient you can identify rows that have been deleted.

  • Restore deleted rows in sql server 2008

    Hi,
    I have problem, I used import and export wizard in sql server 2008, and select wrong database in source data and wrong database in destination data (i Reflect databases) and  in editing mapping i make check for delete rows in destination table. 
    the step final complete and  i lost my data and i don't have backup
    how i can restore my data

    its not a straight forward activity if you don't have backups, first thing you need to do is to create proper maintenance plan for you databases. You can refer below links which could give some clue about your probles.
    http://social.msdn.microsoft.com/Forums/sqlserver/en-US/86befdbe-9806-4d96-9e9f-ead753d0fc20/recover-deleted-rows-from-sql-server-database?forum=transactsql
    http://sqlserver2000.databases.aspfaq.com/how-do-i-recover-data-from-sql-server-s-log-files.html
    Please mark solved if I've answered your question, vote for it as helpful to help other users find a solution quicker
    Praveen Dsa | MCITP - Database Administrator 2008 |
    My Blog | My Page

  • How to delete row by row comparing to first collumn?

    Hello!
    I have a problem - I need to delete row by row , but the problem is, that I know that first COLUMN of any table is a PK.
    To retrieve COLUMN NAME I use:
    SELECT column_name, table_name FROM USER_TAB_COLUMNS WHERE column_id = 1 and table_name = c1.tmp_table_name;
    But this somehow doesn't work.
    Below you can see my script (not worked for now):
    declare
    xxx varchar2(100);
    begin
    for c1 in (select table_name, tmp_table_name from tmp_tables) loop
    EXECUTE IMMEDIATE
    ' SELECT column_name into '|| xxx ||' FROM USER_TAB_COLUMNS WHERE column_id = 1 and table_name = ' ||''''||c1.tmp_table_name||'''';
    execute immediate
    'begin
    for c2 in (select * from '|| c1.tmp_table_name || ') loop begin
    insert into '|| c1.table_name || ' values c2; delete from '|| c1.tmp_table_name || ' where ' || xxx ||' = c2.'||xxx ||'; exception when others then null; end; end loop; end;';
    end loop;
    end;
    P.S. Inserts work perfect. I have a problem with delete rows that are in c1.table_name, from c1.tmp_table_name (this two tables have the same structure, PK, always), because I have different column names in another tables tables that are PK. (for example: K, ID, NS and so on) please help me to write correct script.
    For example for first fetched row it will be like:
    begin
    for c1 in (select table_name, tmp_table_name from tmp_tables) loop
    execute immediate
    'begin for c2 in (select * from '|| c1.tmp_table_name || ') loop begin
    insert into '|| c1.table_name || ' values c2; delete from '|| c1.tmp_table_name ||' where K = c2.K; exception when others then null; end; end loop; end;';
    end loop;
    end;
    That script works perfect. But I have many others tables with different PK - not K.

    Solution with error-logging table
    -- create the error-logging table
    CREATE TABLE tbl_MergeErrors (
        Stamp       TIMESTAMP(3),
        TableName   VARCHAR2(30),
        KeyColumn   VARCHAR2(30),
        KeyValue    VARCHAR2(4000),
        ErrorCode   NUMBER(5),
        ErrorMsg    VARCHAR2(4000),
      CONSTRAINT pk_MergeErrors
          PRIMARY KEY (TableName, Stamp)
          USING INDEX
    -- procedure to insert errors
    CREATE OR REPLACE
    PROCEDURE LogMergeError (pTableName  IN VARCHAR2,
                             pKeyColumn  IN VARCHAR2,
                             pKeyValue   IN VARCHAR2)
    IS PRAGMA AUTONOMOUS_TRANSACTION;
        -- you couldn't insert SQLCODE or SQLERRM directly into a table (ORA-00984)
        nSQLCODE   NUMBER(5)      := SQLCODE;
        vcSQLERRM  VARCHAR2(4000) := SQLERRM;
    BEGIN
      INSERT INTO tbl_MergeErrors
             (Stamp, TableName, KeyColumn, KeyValue, ErrorCode, ErrorMsg)
          VALUES (SYSTIMESTAMP, RTrim( SubStr( pTableName, 1, 30)),
                  RTrim( SubStr( pKeyColumn, 1, 30)), SubStr( pKeyValue, 1, 4000),
                  nSQLCODE, vcSQLERRM);
      COMMIT WORK;
    -- if an error occured here, then just roll back the autonomous transaction
    EXCEPTION
      WHEN OTHERS THEN   ROLLBACK WORK;
    END LogMergeError;
    -- create the tables and insert test-data
    CREATE TABLE TMP_TABLES (
        TABLE_NAME       VARCHAR2(200),
        TMP_TABLE_NAME   VARCHAR2(200),
      CONSTRAINT TMP_TABLES_X PRIMARY KEY (TABLE_NAME)
    CREATE TABLE TMP_KL002 (
        K   VARCHAR2(40),
        N   VARCHAR2(200)
    CREATE TABLE TMP_TABLE1 (
        NS   VARCHAR2(40),
        N    VARCHAR2(200)
    CREATE TABLE KL002 (
        K VARCHAR2(40),
        N VARCHAR2(200),
      CONSTRAINT PK_KL002 PRIMARY KEY (K)
    CREATE TABLE TABLE1 (
        NS   VARCHAR2(40),
        N    VARCHAR2(200),
      CONSTRAINT PK_TABLE1 PRIMARY KEY (NS)
    INSERT INTO TMP_TABLES (TABLE_NAME, TMP_TABLE_NAME) VALUES ('kl002','tmp_kl002');
    INSERT INTO TMP_TABLES (TABLE_NAME, TMP_TABLE_NAME) VALUES ('table1','tmp_table1');
    INSERT INTO tmp_KL002 (K, N) VALUES ('00', 'none');
    INSERT INTO tmp_KL002 (K, N) VALUES ('07', 'exists');
    INSERT INTO tmp_KL002 (K, N) VALUES ('08', 'not assigned');
    INSERT INTO tmp_table1 (NS, N) VALUES ('2000', 'basic');
    INSERT INTO tmp_table1 (NS, N) VALUES ('3000', 'advanced');
    INSERT INTO tmp_table1 (NS, N) VALUES ('4000', 'custom');
    COMMIT WORK;
    -- to test, if it works correct when primary key values exists before
    INSERT INTO KL002 VALUES ('07', 'exists before');
    COMMIT WORK;
    -- check the data before execution
    SELECT * FROM TMP_KL002 ORDER BY K;
    SELECT * FROM KL002 ORDER BY K;
    SELECT * FROM TMP_TABLE1 ORDER BY NS;
    SELECT * FROM TABLE1 ORDER BY NS;
    -- empty the error-logging table
    TRUNCATE TABLE tbl_MergeErrors DROP STORAGE;
    -- a solution
    DECLARE
        PLSQL_BLOCK  CONSTANT VARCHAR2(256) := '
    BEGIN
      FOR rec IN (SELECT * FROM <0>) LOOP
        BEGIN
          INSERT INTO <1> VALUES rec;
          DELETE FROM <0> t WHERE (t.<2> = rec.<2>);
        EXCEPTION
          WHEN OTHERS THEN
              LogMergeError( ''<1>'', ''<2>'', rec.<2>);
        END;
      END LOOP;
    END;';
    BEGIN
      FOR tabcol IN (SELECT t.Tmp_Table_Name, t.Table_Name, c.Column_Name
                     FROM Tmp_Tables t,
                          User_Tab_Columns c
                     WHERE     (c.Table_Name = Upper( t.Tmp_Table_Name))
                           AND (c.Column_ID = 1)
                ) LOOP
        EXECUTE IMMEDIATE Replace( Replace( Replace( PLSQL_BLOCK,
                                   '<0>', tabcol.Tmp_Table_Name),
                                   '<1>', tabcol.Table_Name),
                                   '<2>', tabcol.Column_Name);
      END LOOP;
    END;
    -- check the data after execution ...
    SELECT * FROM TMP_KL002 ORDER BY K;
    SELECT * FROM KL002 ORDER BY K;
    SELECT * FROM TMP_TABLE1 ORDER BY NS;
    SELECT * FROM TABLE1 ORDER BY NS;
    -- ... and also the error-logging table
    SELECT * FROM tbl_MergeErrors ORDER BY Stamp, TableName;
    -- of couse you must issue an COMMIT (the ROLLBACK is only for testing
    ROLLBACK WORK;
    -- drop the test-tables
    DROP TABLE TABLE1 PURGE;
    DROP TABLE KL002 PURGE;
    DROP TABLE TMP_TABLE1 PURGE;
    DROP TABLE TMP_KL002 PURGE;
    DROP TABLE TMP_TABLES PURGE;
    -- you shouldn't drop the error-logging table, but I use it to free up my db
    DROP TABLE tbl_MergeErrors PURGE;Greetings, Niels

Maybe you are looking for

  • Collections in Adobe Bridge

    I have 2 questions with regards to Collections in Adobe Bridge. I'm busy with a Photoshop basic course. 1. You'll be continually downloading images to your computer and want to keep them organized automatically according to their metadata.  What's th

  • Cant uninstall Itunes 7.7.1.11

    So I turn Itunes on and it asks if I want to upgrade to 8.0 and I click yes so i downloads everything and installs everything nothing looks like it went wrong but then when I turn it on i get an error box that says Warning! The registry settings used

  • HT1937 Can I get my secondhand iPhone 4 reset to factory setting?

    Can I get my secondhand iPhone 4 reset to factory setting? It is on uk carrier 3 and I would like to use it on the Tmobile or Virgin carriers and give it to my daughter for her birthday on 16-02-

  • How to copy HDD (MP3)Folders directly into specific iTunes Folders ?

    I want to import specific music folders from my HDD into specified iTunes folder but I only can import the content of specified folders into the iTunes music library, then I have to manually copy them into the specified iTunesFolders or Playlists. An

  • In what cases does Apple usually choose to just replace an iPhone instead of repairing it?

    From your guys' experiences, what qualifies for a free iPhone replacement by Apple? I'm taking my iPhone 4 in tomorrow for a stuck sleep/wake button. I've tried blowing any debris out of the button's surrounding area and even shook the phone upside d