Want to add rows from database in custom table model

Hello all,
I have written custom table model which has single blank row intially.
Once user clicks on button, i want to add more rows in custom table model and display them in JTable.
I have created JTable object as shown below.
Jtable patientTable = new JTable( new DiagnosticTableModel());
My custom tabel model is as shown below.
import javax.swing.table.AbstractTableModel;
public class DiagnosticTableModel extends AbstractTableModel
     private String[] columnNames = {
                     "Date",
                                          "Diagnosis",
                                          "Severity",
                                          "Medications"};
     private String[][] data = {
      public int getColumnCount()
         return columnNames.length;
      public int getRowCount()
           return data.length;
      public String getColumnName(int col)
         return columnNames[col];
      public Class getColumnClass(int col)
         return getValueAt(0, col).getClass();
      public Object getValueAt(int row, int col)
         return data[row][col];
      public boolean isCellEditable(int row, int col)
      return true;
      public void setValueAt(Object value, int row, int col)
         data[row][col] = value.toString();
         fireTableCellUpdated(row, col);
}Thanx a lot in advance.

I have written custom table model which has single blank row intially.Why did you write a custom TableModel? The DefaultTableModel will work fine and it has methods that allow you to dynamically add rows to the table.

Similar Messages

  • How to select rows from database like 10 to 20 etc

    Hi Experts,
    I want to select rows from database like row number 10 to row number 20.How could it be done?

    HI,
       First get the data into the INTERNAL TABLE from the FLAT FILE and read the internal table using the index.
        ex: 1) Read table ITAB index 10.
              2) Read table ITAB index 20.
    or use as said by  Srinivas Gurram, to get the range of records using where condition to the loop.
    <REMOVED BY MODERATOR>
    Edited by: Ravi Kumar on Jun 9, 2008 4:01 PM
    Edited by: Alvaro Tejada Galindo on Jun 9, 2008 3:16 PM

  • How do i add data from database to JTable ! Urgent

    How do i add data from database to the columns of JTable?.

    hi,
    Thanks for ur link. but this is just a part of my application which i am developing user interface in swing package for which i want to know how to show data to user in the table format where by table input data will be from the database. say something like todays activity is shown to the user in table format... So u have any idea of how to do this...

  • HOW TO DELETE THE ROW FROM DATABASE

    hI,
    Iam pasting my code below.My problem isi retrieve rows from database and display them in jsp page in rows.For each row there is delete hyperlink.Now when i click that link i should only delete the row corresponding to that delete link temporarily but it should not delete the row from database now.It should only delete the row from database when i click the save button.How can i do this can any one give some code.
    thanks
    naveen
    [email protected]
    <%@ page language="java" import="Utils.*,java.sql.*,SQLCon.ConnectionPool,java.util.Vector,java.util.StringTokenizer" %>
    <html>
    <head>
    <meta http-equiv="Content-Language" content="en-us">
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
    <meta name="ProgId" content="FrontPage.Editor.Document">
    <title>Item Details</title>
    <script>
    function submitPage()
    document.details.action = "itemdetails.jsp" ;
    document.details.submit();
    </script>
    </head>
    <body>
    <form name="details" action="itemdetails.jsp" method="post">
    <%
    ConnectionPool pool;
    Connection con = null;
    Statement st;
    ResultSet rs =null;
    %>
    <table border="0" cellpadding="0" cellspacing="0" width="328">
    <tr>
    <td width="323" colspan="4"><b>Reference No :</b> <input type="text" name="txt_refno" size="14">
    <input type="submit" value="search" name="search" ></td>
    </tr>
    <tr>
    <td width="81" bgcolor="#000099"><font color="#FFFFFF"><b>Item Code</b></font></td>
    <td width="81" bgcolor="#000099"><font color="#FFFFFF"><b>Item No</b></font></td>
    <td width="81" bgcolor="#000099"><font color="#FFFFFF"><b>Amount </b></font></td>
    <td width="80" bgcolor="#000099"> </td>
    </tr>
    <%
    pool= new ConnectionPool();
    Utils utils = new Utils();
    double total =0.00;
    String search =utils.returnString(request.getParameter("search"));
    if(search.equals("search"))
    try
    String ref_no =utils.returnString(request.getParameter("txt_refno"));
    String strSQL="select * from ref_table where refno='" + ref_no + "' ";
    con = pool.getConnection();
    st=con.createStatement();
    rs = st.executeQuery(strSQL);
    while(rs.next())
    String itemcode=rs.getString(2);
    int item_no=rs.getInt(3);
    double amount= rs.getDouble(4);
    total= total + amount;
    %>
    <tr>
    <td width="81"><input type=hidden name=hitem value=<%=itemcode%>><%=itemcode%></td>
    <td width="81"><input type=hidden name=hitemno value=<%=item_no%>><%=item_no%></td>
    <td width="81"><input type=hidden name=hamount value=<%=amount%>><%=amount%></td>
    <td width="80"><a href="delete</td>
    </tr>
    <%
    }catch(Exception e){}
    finally {
    if (con != null) pool.returnConnection(con);
    %>
    <tr>
    <td width="323" colspan="4">
    <p align="right"><b>Total:</b><input type="text" name="txt_total" size="10" value="<%=total%>"></td>
    </tr>
    <tr>
    <td width="323" colspan="4">                   
    <input type="button" value="save" name="save"></td>
    </tr>
    </table>
    </form>
    </body>
    </html>

    You mean when you click on the hyperlink you want that row to disappear from the page, but not delete the row from the database until a commit/submit button is pressed?
    Personally, I think I'd prefer that you have a delete checkbox next to every row and NOT remove them from the display if I was a user. You give your users a chance to change their mind about their choice, and when they're done they can see exactly which rows will be deleted before they commit.
    You know your problem, of course, so you might have a good reason for designing it this way. But I'd prefer not removing them from the display. JMO - MOD

  • Use Preparedstatement to delete several rows from database

    Hello everyone,
    I am trying to delete multiple rows from database at one time using Preparedstatement.
    It works well when I tried in SQL directly,the sql query is as follows:
    delete from planners_offices where planner ='somename' and office in ( 'officeone', 'officetwo', 'officethree')
    I want to delete those 3 rows at one time.
    But when I am using preparedstatement to implement this function, it does not work. It did not throw any exception, but just does not work for me, the updated rows value always returns "0".
    Here is my simplified code:
    PreparedStatement ps = null;
    sqlStr = " delete from PLANNERS_OFFICES where planner = ? and office in (?) "
    Connection con = this.getConnection(dbname);
    try
    //set the sql statement into the preparedstatement
    ps = con.prepareStatement(sqlStr);
    ps.setString(1,"somename");
    ps.setString(2,"'officeone','officetwo','officethree'");
    int rowsUpdated =ps.executeUpdate();
    System.out.println(rowsUpdated);
    //catch exception
    catch (SQLException e)
    System.out.println("SQL Error: " + sqlStr);
    e.printStackTrace();
    catch (Exception e) {
    e.printStackTrace();
    } finally {
    this.releaseConnection(dbname, con);
    try{
    ps.close();
    }catch (SQLException e){
    e.printStackTrace();
    rowsUpdated always give me "0".
    I tried only delete one record at one time, "ps.setString(2, "officeone");", it works fine.
    I am guessing the second value I want to bind to the preparedstatement is not right, I tried several formats of that string, it does not work either.
    Can anyone give me a clue?
    Thanks in advance !
    Rachel

    the setString function in a preparedStatement doesn't just do a replace with the question mark. It is doing some internal mumbojumbo(technical term) to assign your variable to the ?.
    If you are looking to do your statement, then you will need to put in the correct of # of question marks as you need for the in clause.
    delete from PLANNERS_OFFICES WHERE PLANNER = ? and office in (?,?,?)
    If you need to allow for one or more parameters in your in clause, then you will need to build your SQL dynamically before creating your prepared statement.
    ArrayList listOfOfficesToDelete ;
    StringBuffer buffer = new StringBuffer("DELETE FROM PLANNERS_OFFICES WHERE PLANNER = ? AND OFFICE IN (");
    for(int i = 0; i < listOfOfficesToDelete.size(); i++ )
       if( i != 0 )
           buffer.append(",");
       buffer.append("?");
    buffer.append(")");
    cursor = conn.prepareStatement( buffer.toString() );
    cursor.setString(1, plannerObj);
    for(int i = 0; i < listOfOfficesToDelete().size(); i++ )
        cursor.setString(i+1, listOfOfficesToDelete.get(i) );
    cursor.executeUpdate() ;

  • Add rows from another table

    Hi ,
    I have a table with 20 records and 10 columns.I want to add columns from another table with out cross join.

    As others have said, you need to have some sort of join condition otherwise it is a cross join.
    SQL> ed
    Wrote file afiedt.buf
      1  with T1 as (select 'e' as c1, 2 as c2 from dual union all
      2              select 'd', 3 from dual)
      3      ,T2 as (select 'x' as c3, 5 as c4 from dual union all
      4              select 'y', 6 from dual union all
      5              select 'z', 2 from dual)
      6  --
      7  select T2.c3, T2.c4, T1.c1, T1.c2
      8  FROM (select c1, c2, row_number() over (order by c1) as rn from T1) T1
      9       FULL OUTER JOIN
    10       (select c3, c4, row_number() over (order by c3) as rn from T2) T2
    11*      ON (T1.rn = T2.rn)
    SQL> /
    C         C4 C         C2
    x          5 d          3
    y          6 e          2
    z          2
    SQL>This example assigns a row number to each row within each table and then joins using that row number.
    (I've assumed the row number should be generated based on the order of the first column of each table, but you can change that as required).
    What is the point of your requirement?

  • Problem in deleting row from database in table component

    Hi,
    I have a table component that its content change by diffrent links.
    in this table i have a hyperlink in each row to deleting that row from dataBase.
    so i must get the current row .
    i do it like this:
    define a rowset in the page that have a delete query :
    delete from response where responseID=?
    in action of delete hyperlink ,i have:
    Integer responseId=(Integer)responseDataProvider.
    getValue("#{currentRow.value['responseID']}") ;
    getSessionBean1().getResponseRowSet().setObject(1,responseId);
    getSessionBean1().getResponseRowSet().execute();
    but in first line occure a exception:
    illigalArgument #{currentRow.value['responseID']}
    thanks.

    by using data table
    first you should get current record (row that recived action)
    then delete it by using data provider.
    I do not think that you could execute delete statement using rowSets because they just can provide Select statements.
    btw , following code will retrive clicked row from data table and
    delete that row
    try {
    RowKey rk = getTableRowGroup1().getRowKey();
    if (rk != null) {
    testDataProvider.removeRow(rk);
    testDataProvider.commitChanges();
    } catch (Exception ex) {
    log("ErrorDescription", ex);
    error(ex.getMessage());
    hth
    masoud

  • Want to add song from iphone to itunes

    want to add song from iphone to itunes

    If it is Not a song your Purchased in iTunes... Then how did it get on your phone...
    https://discussions.apple.com/message/19252407#19252407

  • ORA-22905: cannot access rows from a non-nested table item in Table func

    I am using a table function in Oracle 8.1.7.4.0. I did declare an object type and a collection type like this:
    CREATE TYPE t_obj AS OBJECT ...
    CREATE TYPE t_tab AS TABLE OF t_obj;
    My table function returns t_tab and is called like this:
    SELECT ... FROM TABLE (CAST (my_pkg.table_fnc AS t_tab)) ...
    This works pretty well as long as I run it in the same schema that owns the function and the 2 types. As soon as I run this query from another schema, I get an ORA-22905: cannot access rows from a non-nested table item error, even though I granted execute on both the types and the function to the other user and I created public synonyms for all 3 objects.
    As soon as I specify the schema name of t_tab in the cast, the query runs fine:
    SELECT ... FROM TABLE (CAST (my_pkg.table_fnc AS owner.t_tab)) ...
    I don't like to have a schema hard coded in a query, therefore I'd like to do this without the schema. Any ideas of how to get around this error?

    Richard,
    your 3 statements are correct. I'll go ahead and log a TAR.
    Both DESCs return the same output when run as the other user. And, running the table function directly in SQL*Plus (SELECT my_pkg.table_fnc FROM dual;) also returns a result and no errors. The problem has to be in the CAST function.
    Thanks for your help.

  • ORA-22905: cannot access rows from a non-nested table item

    Hi All,
    This is the overview of the query used in the package.
    select ename,empno,sal,deptno from
    (select deptno from dept) a,
    (select ename,empno,sal from emp1) b
    where empno in (select * from table (pkg1.fun1('empno')))
    and a.deptno=b.deptno
    union
    select ename,empno,sal,deptno from
    (select deptno from dept) c,
    (select ename,empno,sal from emp2) d
    where empno in (select * from table (pkg1.fun1('empno')))
    and c.deptno=d.deptno
    Here the pkg1.fun1 will convert the string ('empno') into table form. ('empno') is the input parameter to the package and is a string of emp numbers.
    compilation is successful. when this is executed the below error pops up
    "ORA-22905: cannot access rows from a non-nested table item"
    Is there any problem with the table function which i am using in this query
    could anyone guide me to the solution.
    Thanks All

    I have used
    CREATE OR REPLACE
    type tab_num as table of number;
    select * from table (cast(pkg1.fun1('empno')) as tab_num))
    This throws an error during compilation itself
    "PL/SQL: ORA-00932: inconsistent datatypes:expected number got varchar2

  • Oracle error ORA-22905: cannot access rows from a non-nested table item

    Oracle error ORA-22905: cannot access rows from a non-nested table item
    Creating a report using oracle plsql code .
    Getting error ;
    Oracle error ORA-22905: cannot access rows from a non-nested table item
    when I am trying to pass data in clause in pl sql proc
    basically I have a proc which takes 2 parameters(a and b)
    proc (
    P_a varchar2,
    p_b varchar2,
    OUT SYS_REFCURSOR
    culprit code which is giving me  the error and on google they say cast it but I dont know how to do it in my context
    --where  id in (
    --        SELECT * FROM THE (SELECT p_cd_common.get_table_from_string(P_a) FROM dual)
    --        union
    --        SELECT * FROM THE (SELECT p_cd_common.get_table_from_string(P_b) FROM dual)
    data sample returned from this :SELECT * FROM THE (SELECT p_cd_common.get_table_from_string(P_a) FROM dual)
    'Abc','def',
    data sample returned from this;SELECT * FROM THE (SELECT p_cd_common.get_table_from_string(P_b) FROM dual)
    'fgd','fth',
    Any answers ?
    How to pass data in clause in a better way

    Why are you creating a duplicate post? I already asked you to post p_cd_common.get_table_from_string. In particular what is function return type and where it is declared. As I already mentioned, most likely function return type is declared in the package and therefore is PL/SQL type. And TABLE operator can only work with SQL types.
    SY.

  • SP which returns error cannot access rows from a non-nested table item.

    Dear Experts
    I have an SP which gives error " cannot access rows from a non-nested table item ". But here the strange thing is, it works fine with one query. But I write union query with another table, only then it gives error.
    CREATE OR REPLACE PROCEDURE SP_MONTHLYSALESUMMARY (
    P_TRANSACTIONMONTH VARCHAR2,
    P_LEDGERID VARCHAR2,
    O_RESULTSET OUT TYPES.CURSORTYPE)
    AS
    BEGIN
    OPEN O_RESULTSET FOR
    -- POINT OF SALE
    SELECT
    L.DESCRIPTION LEDGERNAME,
    LS.DESCRIPTION LEDGERSUBGROUPNAME,
    C.CORPORATENO
    || E.EMPLOYEENO
    || AF.AFFILIATEMEMBERNO
    || M.MEMBERNO
    AS ID,
    C.NAME || E.NAME || AF.NAME || M.NAME AS NAME,
    SUM(CASE
    WHEN PB.EMPLOYEE_ID IS NOT NULL
    AND T.ISCREDITTRANSACTIONMODE = 2
    THEN
    PB.TAXAMOUNT
    ELSE
    0
    END)
    EMPLOYEEDEBITCARDTAXAMOUNT,
    L.PRINTNO
    FROM POINTOFSALEBILL PB
    INNER JOIN POINTOFSALEBILLDETAIL PD
    ON PB.POINTOFSALEBILL_ID = PD.POINTOFSALEBILL_ID
    INNER JOIN TRANSACTIONTYPE TY
    ON TY.TRANSACTIONTYPE_ID = PB.TRANSACTIONTYPE_ID
    INNER JOIN TRANSACTIONMODE T
    ON T.TRANSACTIONMODE_ID = PB.TRANSACTIONMODE_ID
    INNER JOIN LEDGER L
    ON L.LEDGER_ID = PD.LEDGER_ID
    INNER JOIN LEDGERSUBGROUP LS
    ON LS.LEDGERSUBGROUP_ID = L.LEDGERSUBGROUP_ID
    LEFT JOIN CORPORATE C
    ON C.CORPORATE_ID = PB.CORPORATE_ID
    LEFT JOIN EMPLOYEE E
    ON E.EMPLOYEE_ID = PB.EMPLOYEE_ID
    LEFT JOIN AFFILIATEMEMBER AF
    ON AF.AFFILIATEMEMBER_ID = PB.AFFILIATEMEMBER_ID
    LEFT JOIN MEMBER M
    ON M.MEMBER_ID = PB.MEMBER_ID
    WHERE TY.ISDEBIT = 1 AND PB.FLAG = 0 AND T.ISROOMNO = 2
    AND (P_TRANSACTIONMONTH IS NULL
    OR P_TRANSACTIONMONTH =
    TO_CHAR (PB.BILLDATE, 'fmMONTH-YYYY'))
    AND (P_LEDGERID IS NULL
    OR L.LEDGER_ID IN
    ( (SELECT COLUMN_VALUE
    FROM TABLE(GET_ROWS_FROM_LIST1 (
    P_LEDGERID,
    GROUP BY L.DESCRIPTION,
    LS.DESCRIPTION,
    C.CORPORATENO
    || E.EMPLOYEENO
    || AF.AFFILIATEMEMBERNO
    || M.MEMBERNO,
    C.NAME || E.NAME || AF.NAME || M.NAME,
    L.PRINTNO;
    END SP_MONTHLYSALESUMMARY;
    GET_ROWS_FROM_LIST1 is a function, which i am using to pass " IN " to oracle. There is no problem with this, since it works fine with one query
    REATE OR REPLACE FUNCTION BCLUB1868.GET_ROWS_FROM_LIST1
    (L IN LONG DEFAULT NULL, SEP IN VARCHAR2 DEFAULT ',')
    RETURN MYVARCHARTABLE1 PIPELINED
    AS
    L_POS INT := 1;
    L_NEXT INT;
    L_PART VARCHAR(500);
    BEGIN
    SELECT INSTR( L, SEP, L_POS) INTO L_NEXT FROM DUAL;
    WHILE (L_NEXT>0)
    LOOP
    SELECT SUBSTR(L, L_POS, L_NEXT - L_POS) INTO L_PART FROM DUAL;
    PIPE ROW(L_PART);
    SELECT L_NEXT + 1, INSTR( L, SEP, L_POS)
    INTO L_POS, L_NEXT FROM DUAL;
    END LOOP;
    SELECT SUBSTR(L, L_POS) INTO L_PART FROM DUAL;
    PIPE ROW(L_PART);
    RETURN;
    END;
    Request help from you all experts in the forum

    Here it is
    CREATE OR REPLACE PROCEDURE SP_GRCS (
    P_TRANSACTIONMONTH VARCHAR2,
    P_LEDGERID VARCHAR2,
    O_RESULTSET OUT TYPES.CURSORTYPE)
    AS
    BEGIN
    OPEN O_RESULTSET FOR
    -- Point of sale
    SELECT *
    FROM ( SELECT L.DESCRIPTION LEDGERNAME,
    LS.DESCRIPTION LEDGERSUBGROUPNAME,
    C.CORPORATENO
    || E.EMPLOYEENO
    || AF.AFFILIATEMEMBERNO
    || M.MEMBERNO
    AS ID,
    C.NAME || E.NAME || AF.NAME || M.NAME AS NAME,
    SUM(CASE
    WHEN PB.EMPLOYEE_ID IS NULL
    AND T.ISCREDITTRANSACTIONMODE = 1
    THEN
    PB.BILLAMOUNT
    ELSE
    0
    END)
    MEMBERDEBITAMOUNT,
    L.PRINTNO
    FROM POINTOFSALEBILL PB
    INNER JOIN POINTOFSALEBILLDETAIL PD
    ON PB.POINTOFSALEBILL_ID = PD.POINTOFSALEBILL_ID
    INNER JOIN TRANSACTIONTYPE TY
    ON TY.TRANSACTIONTYPE_ID = PB.TRANSACTIONTYPE_ID
    INNER JOIN TRANSACTIONMODE T
    ON T.TRANSACTIONMODE_ID = PB.TRANSACTIONMODE_ID
    INNER JOIN LEDGER L
    ON L.LEDGER_ID = PD.LEDGER_ID
    INNER JOIN LEDGERSUBGROUP LS
    ON LS.LEDGERSUBGROUP_ID = L.LEDGERSUBGROUP_ID
    LEFT JOIN CORPORATE C
    ON C.CORPORATE_ID = PB.CORPORATE_ID
    LEFT JOIN EMPLOYEE E
    ON E.EMPLOYEE_ID = PB.EMPLOYEE_ID
    LEFT JOIN AFFILIATEMEMBER AF
    ON AF.AFFILIATEMEMBER_ID = PB.AFFILIATEMEMBER_ID
    LEFT JOIN MEMBER M
    ON M.MEMBER_ID = PB.MEMBER_ID
    WHERE TY.ISDEBIT = 1 AND PB.FLAG = 0 AND T.ISROOMNO = 2
    AND (P_TRANSACTIONMONTH IS NULL
    OR P_TRANSACTIONMONTH =
    TO_CHAR (PB.BILLDATE, 'fmMONTH-YYYY'))
    AND (P_LEDGERID IS NULL
    OR L.LEDGER_ID IN
    ( (SELECT COLUMN_VALUE
    FROM TABLE(GET_ROWS_FROM_LIST1 (
    P_LEDGERID,
    GROUP BY L.DESCRIPTION,
    LS.DESCRIPTION,
    C.CORPORATENO
    || E.EMPLOYEENO
    || AF.AFFILIATEMEMBERNO
    || M.MEMBERNO,
    C.NAME || E.NAME || AF.NAME || M.NAME,
    L.PRINTNO
    UNION ALL
    -- Guest Registration
    SELECT L.DESCRIPTION LEDGERNAME,
    LS.DESCRIPTION LEDGERSUBGROUPNAME,
    C.CORPORATENO
    || E.EMPLOYEENO
    || AF.AFFILIATEMEMBERNO
    || M.MEMBERNO
    AS ID,
    C.NAME || E.NAME || AF.NAME || M.NAME AS NAME,
    SUM(CASE
    WHEN PB.EMPLOYEE_ID IS NULL
    AND T.ISCREDITTRANSACTIONMODE = 1
    THEN
    PB.BILLAMOUNT
    ELSE
    0
    END)
    MEMBERDEBITAMOUNT,
    L.PRINTNO
    FROM GUESTREGISTRATION PB
    INNER JOIN GUESTREGISTRATIONDETAIL PD
    ON PB.GUESTREGISTRATION_ID = PD.GUESTREGISTRATION_ID
    INNER JOIN TRANSACTIONTYPE TY
    ON TY.TRANSACTIONTYPE_ID = PB.TRANSACTIONTYPE_ID
    INNER JOIN TRANSACTIONMODE T
    ON T.TRANSACTIONMODE_ID = PB.TRANSACTIONMODE_ID
    INNER JOIN LEDGER L
    ON L.LEDGER_ID = PD.LEDGER_ID
    INNER JOIN LEDGERSUBGROUP LS
    ON LS.LEDGERSUBGROUP_ID = L.LEDGERSUBGROUP_ID
    LEFT JOIN CORPORATE C
    ON C.CORPORATE_ID = PB.CORPORATE_ID
    LEFT JOIN EMPLOYEE E
    ON E.EMPLOYEE_ID = PB.EMPLOYEE_ID
    LEFT JOIN AFFILIATEMEMBER AF
    ON AF.AFFILIATEMEMBER_ID = PB.AFFILIATEMEMBER_ID
    LEFT JOIN MEMBER M
    ON M.MEMBER_ID = PB.MEMBER_ID
    WHERE TY.ISDEBIT = 1 AND PB.FLAG = 0 AND T.ISROOMNO = 2
    AND (P_TRANSACTIONMONTH IS NULL
    OR P_TRANSACTIONMONTH =
    TO_CHAR (PB.BILLDATE, 'fmMONTH-YYYY'))
    AND (P_LEDGERID IS NULL
    OR L.LEDGER_ID IN
    ( (SELECT COLUMN_VALUE
    FROM TABLE(GET_ROWS_FROM_LIST1 (
    P_LEDGERID,
    GROUP BY L.DESCRIPTION,
    LS.DESCRIPTION,
    C.CORPORATENO
    || E.EMPLOYEENO
    || AF.AFFILIATEMEMBERNO
    || M.MEMBERNO,
    C.NAME || E.NAME || AF.NAME || M.NAME,
    L.PRINTNO)
    ORDER BY PRINTNO;
    END SP_GRCS;
    I have even tried adding L.Ledger_ID in select statement.

  • JButton in JTable with custom table model

    Hi!
    I want to include a JButton into a field of a JTable. I do not know why Java does not provide a standard renderer for JButton like it does for JCheckBox, JComboBox and JTextField. I found some previous postings on how to implement custom CellRenderer and CellEditor in order to be able to integrate a button into the table. In my case I am also using a custom table model and I was not able to create a clickable button with any of the resources that I have found. The most comprehensive resource that I have found is this one: http://www.java2s.com/Code/Java/Swing-Components/ButtonTableExample.htm.
    It works fine (rendering and clicking) when I start it. However, as soon as I incorporate it into my code, the clicking does not work anymore (but the buttons are displayed). If I then use a DefaultTableModel instead of my custom one, rendering and clicking works again. Does anyone know how to deal with this issue? Or does anyone have a good pointer to a resource for including buttons into tables? Or does anyone have a pointer to a resource that explains how CellRenderer and CellEditor work and which methods have to be overwritten in order to trigger certain actions (like a button click)?
    thanks

    Yes, you were right, the TableModel was causing the trouble, everything else worked fine. Somehow I had this code (probably copy and pasted from a tutorial - damn copy and pasting) in my TableModel:
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 3) {
                    return false;
                } else {
                    return true;
    }A pretty stupid thing when you want to edit the 3rd column...

  • Custom table model, table sorter, and cell renderer to use hidden columns

    Hello,
    I'm having a hard time figuring out the best way to go about this. I currently have a JTable with an custom table model to make the cells immutable. Furthermore, I have a "hidden" column in the table model so that I can access the items selected from a database by their recid, and then another hidden column that keeps track of the appropriate color for a custom cell renderer.
    Subject -- Sender -- Date hidden rec id color
    Hello Pete Jan 15, 2003 2900 blue
    Basically, when a row is selected, it grabs the record id from the hidden column. This essentially allows me to have a data[][] object independent of the one that is used to display the JTable. Instinctively, this does not seem right, but I don't know how else to do it. I know that the DefaultTableModel uses a Vector even when it's constructed with an array and I've read elsewhere that it's not a good idea to do what I'm trying to do.
    The other complication is that I have a table sorter as well. So, when it sorts the objects in the table, I have it recreate the data array and then set the data array of the ImmutableTableModel when it has rearranged all of the items in the array.
    On top of this, I have a custom cell renderer as well. This checks yet another hidden field and displays the row accordingly. So, not only does the table sort need to inform the table model of a change in the data structure, but also the cell renderer.
    Is there a better way to keep the data in sync between all of these?

    To the OP, having hidden columns is just fine, I do that all the time.. Nothing says you have to display ALL the info you have..
    Now, the column appears to be sorting properly
    whenever a new row is added. However, when I attempt
    to remove the selected row, it now removes a seemingly
    random row and I am left with an unselectable blank
    line in my JTable.I have a class that uses an int[] to index the data.. The table model displays rows in order of the index, not the actual order of the data (in my case a Vector of Object[]'s).. Saves a lotta work when sorting..
    If you're using a similar indexing scheme: If you're deleting a row, you have to delete the data in the vector at the INDEX table.getSelectedRow(), not the actual data contained at
    vector.elementAt(table.getSelectedRow()). This would account for a seemingly 'random' row getting deleted, instead of the row you intend.
    Because the row is unselectable, it sounds like you have a null in your model where you should have a row of data.. When you do
    vector.removeElementAt(int), the Vector class packs itself. An array does not. If you have an array, when you delete the row you must make sure you dont have that gap.. Make a new array of
    (old array length-1), populate it, and give it back to your model.. Using Vectors makes this automatic.
    Also, you must make sure your model knows the data changed:
    model.fireTableDataChanged(); otherwise it has no idea anything happened..
    IDK if that's how you're doing it, but it sounds remarkably similar to what I went thru when I put all this together..

  • JTable: Custom Table Model (pII)

    As was explained in pI, I'm creating a custom table model to overcome a few pitfalls I came across using the DefaultTableModel class, such as aligning cells, and getting certain columns to return only numeric type data. However, I've come upon a few roadblocks myself.
    How do I create each of the following methods:
    insertRow(int ow, int column)
    remove row(int row)
    addRow(Object[] rowData)Assuming that I decide to allow the user to add a column to the table, how would I create the methodaddColumn(Object columnName, Object[] columnData)And also, as I'm creating a custom table model, would I need to replicate DefaultTableModel's methods that inform the listeners that a change has been made to the table?
    Thanks!

    Thanks!
    I just got this response. Anyways, I found another solution that was, interestingly, from one of your threads written in 2005.
    This is what I did:
    // Letting the JTable know what each column stores and should return by
       // overloading the getColumnClass() method
       public Class getColumnClass(int column)
            if(recordsTable.getColumnName(column) == "Ranking")
              return Integer.class;
         /* Why do I keep ketting an IllegalArgumentException here? *
           * It keeps saying it cannot format given object as a Number */            
            else if(recordsTable.getColumnName(column) == "Price (�) ")
              return Float.class;
         else
           return getValueAt(0, column).getClass();         
       }However, another problem has arisen.
    The if method for the int column (Ranking column) works okay, and is even right-aligned. The else if arguments for the Price (�) column however is returning an IllegalArgumentException. This I just cannot figure out.
    Here's the code:package Practice;
      import java.awt.BorderLayout;
      import java.awt.Frame;
      import java.awt.Menu;
      import java.awt.MenuBar;
      import java.awt.MenuItem;
      import java.awt.MenuShortcut;
      import java.awt.event.ActionEvent;
      import java.awt.event.ActionListener;
      import java.awt.event.KeyEvent; // for MenuItem shortcuts
      import java.awt.event.WindowAdapter;
      import java.awt.event.WindowEvent;
      import java.awt.event.WindowListener;
      import javax.swing.JOptionPane;
      import javax.swing.JScrollPane; // JTable added to it, aiding flexibility
      import javax.swing.JTable; // The personally preferred GUI for this purpose
            // Provides a basic implementation of TableModel
      import javax.swing.table.DefaultTableModel;
              // This class uses Vector to store the rows and columns of data, though
              // programmer will be using LinkedLists
      import java.util.LinkedList;
      // User-defined classes
      import Practice.MusicDatabase;
      public class MusicBank extends Frame implements ActionListener
         MusicDatabase mDBase;
         Frame frame;
         String title = "",      // Frame's title
                file = "";           // pathname of the file to be opened
          // Declaring Menu and MenuItem variables
         Menu recordM; // ...
         // recordM
         MenuItem newRecordR_MI, deleteRecordR_MI;
         // Other irrelevant menus and sub items
        DefaultTableModel recordDetails;
        JTable recordsTable;
        LinkedList musicList;
        public MusicBank()
            musicList = new LinkedList();
            frame = new Frame(title);
            frame.setMenuBar(menuSystem());
            // Should user seek to close window externally
            frame.addWindowListener(new WindowAdapter()
                 public void windowClosing(WindowEvent we)
                     frame.dispose();
                     System.exit(0);
         recordDetails = new DefaultTableModel();
         // Creating the relevant columns
         recordDetails.addColumn("Title");
         recordDetails.addColumn("Identity");
         recordDetails.addColumn("Music Company");
         recordDetails.addColumn("Ranking");
         recordDetails.addColumn("Price (�) ");
         // Ensuring the table has at least one visible record (empty)
         recordDetails.addRow(populateRow("", "", "", 0, 0.00f));
         // Creating the table to display the data files (music record details)
         recordsTable = new JTable(recordDetails)
             // Letting the JTable know what each column stores and should return by
             // overloading the getColumnClass() method
            public Class getColumnClass(int column)
               if(recordsTable.getColumnName(column) == "Ranking")
                   return Integer.class;
                /* Why do I keep ketting an IllegalArgumentException here? *
                 * It keeps saying it cannot format given object as a Number */            
                else if(recordsTable.getColumnName(column) == "Price (�) ")
                    return Float.class;
                else
                    return getValueAt(0, column).getClass();         
      // Creating the menus
      public MenuBar menuSystem()
          MenuBar bar = new MenuBar();
          // Record menu and related items
          recordM = new Menu("Record");
          recordM.setShortcut(new MenuShortcut(KeyEvent.VK_R, false));        
          newRecordR_MI = new MenuItem("New record");
          newRecordR_MI.setShortcut(new MenuShortcut(KeyEvent.VK_N, false));
          deleteRecordR_MI = new MenuItem("Delete record");
          deleteRecordR_MI.setShortcut(new MenuShortcut(KeyEvent.VK_D, false));
           recordM.add(newRecordR_MI);
           recordM.addSeparator();
           recordM.add(deleteRecordR_MI);
            // Enabling menus with functionality
           newRecordR_MI.addActionListener(this);
           deleteRecordR_MI.addActionListener(this);
           // Adding menus and items to menu bar
           bar.add(recordM);
           return bar;        
      public void actionPerformed(ActionEvent ae)
          if(ae.getSource() == newRecordR_MI)
             newRecord();
          else if(ae.getSource() == deleteRecordR_MI)
             deleteRecord();       
      // Object that will be used, in conjunction with MusicDatabase's, to 
      // populate the JTable
      // A record in a JTable is equivalent to an element in a LinkedList
      public Object[] populateRow(String title, String name, String comp, int rank, float price)
          // First, update the LinkedList
          mDBase = new MusicDatabase(title, name, comp, rank, price);
          musicList.add(mDBase);
           // Then, update the table
           // As the parameters of Object tableDetails can only take a String or
           // object, rank and price will have to be cast as a String and later
           // parsed to their original form before use.
           String rankPT = ""+rank, pricePT = ""+price;        
           Object rowDetails[] = {title, name, comp, rankPT, pricePT};
           return rowDetails;
      public static void main(String args[])
          MusicBank app = new MusicBank();
           // Using the platform's L&F (if Win32,  Windows L&F; Mac OS, Mac OS L&F,
           // Sun, CDE/Motif L&F)
           // For more on this, refer to the WinHelp Java tutorial by F. Allimont
           try
               UIManager.getSystemLookAndFeelClassName();
           catch(Exception e)
               JOptionPane.showMessageDialog(app,
                    "Failed to create the Windows Look and Feel for this program",
                    "Look and Feel (L&F) error",
                    JOptionPane.ERROR_MESSAGE);
           app.frame.setSize(500, 500);
           app.frame.setVisible(true);
            // Placing frame in the centre of the screen on-loading
           app.frame.setLocationRelativeTo(null);
      // action methods per menu items
      // Also, why do I keep getting an ArrayIndexOutOfBoundsException
      // here? I do know what this exception is, and how it works, but just cannot
      // understand what is causing it
      public void newRecord()
          // Before adding a new record, check if previous record has complete
          // entries. If not, either display a message (JOptionPane) or disallow
          // request (simply do nothing)        
          // Proceed based on assesment
          if(queryState() == true)
              // Inform user that all entries need to be filled in before a new
              // record can be created
              JOptionPane.showMessageDialog(this, // current frame
                       "There are incomplete cells in the table."+
                       "\nPlease fill these in before proceeding",       // Message to user
                       "Incomplete entries",                                // Title
                       JOptionPane.ERROR_MESSAGE);                           // Relevant icon
          else
               // To ensure that both the linked list & the table are simultaneously
               // updated, JOptionPane's input dialogs are used to temporarily store
               // the data which is then inputted into both (linked list and JTable)
              String titleN, identityN, companyN; int rankN; float priceN;
              titleN = JOptionPane.showInputDialog(this, "Enter song title");
              identityN = JOptionPane.showInputDialog(this,                                      "Enter name of singer/band");
             companyN = JOptionPane.showInputDialog(this,                                 "Enter signed/unsigned company");
             rankN = Integer.parseInt( JOptionPane.showInputDialog(this,
                             "Enter rank (a number)") );
            System.out.println("\n JTable rows = "+recordDetails.getRowCount());
             // Ensuring that the chosen rank is not already entered
             /* Problem lies here */
             for(int row = 1; row <= recordDetails.getRowCount(); ++row)
                 if((recordDetails.getValueAt(row, 4)).equals(""+rankN))
                     rankN = Integer.parseInt( JOptionPane.showInputDialog(this,
                             "That number's already chosen.\nPlease enter a rank ") );
             priceN = Float.parseFloat( JOptionPane.showInputDialog(this,                                 "Finally, enter price �") );
             mDBase = new MusicDatabase(titleN, identityN, companyN, rankN, priceN);
             musicList.add(mDBase);
             recordDetails.addRow(populateRow(titleN, identityN, companyN, rankN,
         priceN));
             System.out.println("JTable rows after creation = "+
                   recordDetails.getRowCount());
         // Enabling the delete record menu item (as necessary)
         if((recordsTable.getRowCount()) > 0)
              deleteRecordR_MI.setEnabled(true);
      } // newRecord()
      public void deleteRecord()
         int selectedRow = recordsTable.getSelectedRow();
         recordDetails.removeRow(selectedRow);
          // Removing the element from the LinkedList's corresponding index
          musicList.remove(selectedRow);
          System.out.println("Existing rows = "+recordsTable.getRowCount());
           // If there are no more rows, disallow user from trying to delete rows
           if(selectedRow <= 0)
              deleteRecordR_MI.setEnabled(false);
      } // deleteRecord()
      // Method to query if all cells have changed their states (empty or not)
      public boolean queryState()
          // Obtaining number of rows
          int rows = recordDetails.getRowCount();
          int columns = recordDetails.getColumnCount();
          boolean isEmpty = false; // cell
          System.out.println("Rows = "+rows);
          System.out.println("Columns = "+columns);
          try{
              // Assessing all cells for complete entries
              // This approach is flexible, rather than hardcoding the rows available,
              // making it more reusable (assuming it will always be 5 columns)
              for (int rowIndex = 0; rowIndex<=rows; ++rowIndex)
                  if((recordDetails.getValueAt(rowIndex, 1)).equals(""))
                 isEmpty = true;
                  else if((recordDetails.getValueAt(rowIndex, 2)).equals(""))
               isEmpty = true;
                  else if((recordDetails.getValueAt(rowIndex, 3)).equals(""))
               isEmpty = true;                
                  else if((recordDetails.getValueAt(rowIndex, 4)).equals("0"))
               isEmpty = true;
                  else if((recordDetails.getValueAt(rowIndex, 5)).equals("0.00"))
               isEmpty = true;
          catch(Exception e)
             System.out.println(e.getMessage());
          return isEmpty;
      Now here is the code for the MusicDatabase class
    package Practice;
    class MusicDatabase
        private String songTitle, identity, musicCompany;
        private int rank;
        private float priceF;
        // Defining the constructor
        public MusicDatabase(String title, String name, String company,                                int rankingInt, float price)
           songTitle = title;
           identity = name;
           musicCompany = company;
           rank = rankingInt;
           priceF = price;
        } // constructor
       // Other methods
    } // class MusicDatabaseSorry, but am not sure if these codes are executable, as where I am (a general library), JVM is not on the machine I am using. (Remember, i don't have ready acess to the Internet, so I could not use my machine, nor the facilities that had the JVM - unavailable to me at the time).
    Thanks!
    Reformer...
    PS I do hope the code pasted was not too much. Kind regards....

Maybe you are looking for

  • Registration key

    I received Oracle Database 10g disk set few months back. I did not get around to install soon enough and started installation today. I t asked to get registratin key from http://www.oracle.com/go/?&Svc=2758738&Act=56. I get error on this page and can

  • Recovering lost data

    This is likely a long shot, but please help if you can: I experienced problems where the lcd screen on my powerbook g4 turned into a photo negative looking image. I had the problem repaired through the Apple Store in my neighborhood. I just got it ba

  • SDM password error and go.bat error.

    Hi SAP EP gurus..       I installed SAP Netwevaer Enterprise portal(2004s) in my desktop PC. Its installed successfully. Then i started the server also, its also started successfully. Then i installed SAP Netweaver Developer studio in my PC..Its also

  • Premier 9.0  Update failed.  Could not apply the updates

    I just did a reinstallation of Premier and made an update via Adobe update. I get this error.  Update failed. Could not apply the updates. The error log can contain informtion to help you identify the problem. Then try to update again. Contact Custom

  • I am a newbie. got my ipod 80gb but don't know how to upload video

    i am a newbie. got my ipod 80gb but don't know how to upload video.I tried to add video to my itunes, but it does not recognize it. I kinda of wonder if that's because itunes does not recongnize avi format video. if that is the case, can anyone recom