Simple requirement about JTABLE

hello friends,
Learning JTable...
Somewhere while searching i found a java file named QueryTableModel.java
which has extended the AbstractTableModel. I used it but was unable to format
Double (for amount etc) and Date. It alway returns String class and not Date, Double
etc. I dont know why .....
can somebody help me, guide me so that using cell renderers i can format the
data being populated in the JTable, as per my need?
thanks in advance
anandaScreen

The TableBasic class is about as simple as it gets for displaying a table. You add whatever objects you want to the TableModel and then override the getColumnClass() method to tell the table what type of data is in each column. The table will choose the appropriate renderer for the data type:
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class TableBasic extends JFrame
     public TableBasic()
          String[] columnNames = {"Date", "String", "Integer", "Boolean"};
          Object[][] data =
               {new Date(), "A", new Integer(1), Boolean.TRUE },
               {new Date(), "B", new Integer(2), Boolean.FALSE},
               {new Date(), "C", new Integer(9), Boolean.TRUE },
               {new Date(), "D", new Integer(4), Boolean.FALSE}
          JTable table = new JTable(data, columnNames)
               //  Returning the Class of each column will allow different
               //  renderers to be used based on Class
               public Class getColumnClass(int column)
                    return getValueAt(0, column).getClass();
          table.setPreferredScrollableViewportSize(table.getPreferredSize());
          JScrollPane scrollPane = new JScrollPane( table );
          getContentPane().add( scrollPane );
     public static void main(String[] args)
          TableBasic frame = new TableBasic();
          frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
          frame.pack();
          frame.setLocationRelativeTo( null );
          frame.setVisible(true);
}

Similar Messages

  • Simple question about mount and delay script

    Hello, I have a simple question about mounting volumes on start up.
    My computer wakes up auto - and then auto there are serveral applescript tasks (mount and start up programs)
    I use this script (daily) for serveral connections with external volumes I always need the connect to. ( In the script I use this code 3 times for other locations) I do this on start up.
    set Uname to "XXX"
    set Pword to "XXX"
    set someVolume to "afp://XXX.XXX.XXX.XXX/XXX/XXX
    mount volume someVolume as user name Uname with password Pword
    (same code for 2 other locations)
    When i do this on start up sometimes the script says there is no connection possible. I guess it's because on start up the connection isn't there. And 1 minute later when computer is total ready the connection is ok. When I run the script then It works. Just sometimes ( In the morning) 'It' want to connect but the script stops. When i do it manually(I run the script again) it works just fine.
    Is it possible that I need a delay? Can someone explain this?
    How would I make a delay handler for this script? Is that the best solution?
    Thanks in advance. This is something small i'm wondering about.
    Colin

    BTW, If you saved the script as an application +(and not as an application bundle)+ you could drop the script on to *Drop Script Backgrounder* (freeware).
    Then the script would run in the background, so, you wouldn't see it running in the Finder.
    <http://www.macupdate.com/info.php/id/7922/drop-script-backgrounder-x>
    Tom

  • Best practices about JTables.

    Hi,
    I'm programming in Java since 5 months ago. Now I'm developing an application that uses tables to present information from a database. This is my first time handling tables in Java. I've read Sun's Swing tutorial about JTable, and several information on other websites, but they limit to table's syntax and not in best practices.
    So I decided what I think is a proper way to handle data from a table, but I'm not sure that is the best way.Let me tell you the general steps I'm going through:
    1) I query employee data from Java DB (using EclipseLink JPA), and load it in an ArrayList.
    2) I use this list to create the JTable, prior transformation to an Object[][] and feeding this into a custom TableModel.
    3) From now on, if I need to search an object on the table, I search it on the list and then with the resulting index, I get it from the table. This is possible because I keep the same row order on the table and on the list.
    4) If I need to insert an item on the table, I do it also on the list, and so forth if I'd need to remove or modify an element.
    Is the technique I'm using a best practice? I'm not sure that having to keep synchronized the table with the list is the better way to handle this, but I don't know how I'd deal just with the table, for instance to efficiently search an item or to sort the table, without doing that first on a list.
    Are there any best practices in dealing with tables?
    Thank you!
    Francisco.

    Hi Joachim,
    What I'm doing now is extending DefaultTableModel instead of implementing AbstractTableModel. This is to save implementing methods I don't need and because I inherit methods like addRow from DefaultTableModel. Let me paste the private class:
    protected class MyTableModel extends DefaultTableModel {
            private Object[][] datos;
            public MyTableModel(Object[][] datos, Object[] nombreColumnas) {
                super(datos, nombreColumnas);
                this.datos = datos;
            @Override
            public boolean isCellEditable(int fila, int columna) {
                return false;
            @Override
            public Class getColumnClass(int col) {
                return getValueAt(0, col).getClass();
        }What you are suggesting me, if I well understood, is to register MyTableModel as a ListSelectionListener, so changes on the List will be observed by the table? In that case, if I add, change or remove an element from the list, I could add, change or remove that element from the table.
    Another question: is it possible to only use the list to create the table, but then managing everything just with the table, without using a list?
    Thanks.
    Francisco.

  • A simple question about combo box

    Dear All,
    Just got a simple question about combo box: I have one of these selectors with labels based on filtered rows from a table.
    Is it possible to have one more label that would select all options?
    Like:
    Product A
    Product B
    Product C
    All Product
    Many thanks for your help!
    Gilles

    Hi Gilles,
    The purpose of ComboBox itself to select single option out of many.
    For your purpose, you may have to use "List Builder" which can accomodate 1 or more  to select.
    Please revert for more clarification if you need.
    With best wishes
    BaaRaa.

  • Urgent support by two simple requirements

    Hello,
    i need support by two simple requirements.
    Can someone tell me, whether it is possible to realize these in context of SAP XI /SAP Web AS
    Graph showing relationships between Tables, DB Spaces & OS File system?
    (Yes/No)
    Can all jobs and/or scripts be re-run after failure without risk to production data (i.e. stepwise recovery)?
    (Yes/No)
    Thank you very much!
    Regards
    A. Henke

    Hi Axel,
    As far as your first requirement is concerned we can do that in SAP WAS very well with the help of WebDynpro. You need to use Business Graphics for that purpose, see the following link for details,
    /people/sap.user72/blog/2005/03/23/business-graphics-in-webdynpro
    Well for the other one you need to use job scheduling in JAVA with the help of say Quartz or something like that so that you can run timely jobs.
    I hope it helps you.
    Best regards,
    Guru.

  • A simple question about performance!

    Hi! I have a simple question about performance. Suppouse that you have a servlet or a class with DB access, and you need to use a value several times in that page. What is best, to assign the value from say, a resultset or a request.getParameter() to a variable or to call the resultset or the request every time you need to retrieve that value? Which option uses less memory, which is faster, etc.?
    Hoping the best fou u
    Raul

    If you need more values from a db, the best is to open some connections (connection pool) and use the for accessing the db.
    To get the data only once, open the connection, get the data, store the data whereever you want: variable (class), hidden control (if you want to send from one page to another by request) and close the connection as quicky as possible.
    The advantage of the first method is that the most time consuming activity (connections opening) is done only once.

  • Does anybody can give me a simple example about the labview programme calling dll ?

      Does anybody can give me a simple example about the labview programme calling dll ?And the dll is also writed  by using labview .I just want to study  the process of the labview programme calling dll file.Thank you!

    Hi,
    Please click on "Find Examples" in the "Getting Started Window"
     A window named "NI Example Finder" will pop up.
     In this go to "Search" tab
    Type "DLLs"
    You will see a lot of examples. 
    If you're online, you'll see user examples too...

  • Requirement about transport tracking

    Hi,
    I have this small requirement about transport tracking.
    A transport might have lot of tables referenced. I need to find out, what is the difference, between the tables in one system, and the tables in another system, say between development system, and production system. Any leads on this would be helpful. Thanks for the help in advance.
    Regards,
    Vijay

    Hai Srikanth,
    These links may be helpful to you..just check them out.
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/7ce5c590-0201-0010-388e-cc28510abb89
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/a9039a90-0201-0010-c39d-c7173438ea0d
    Regards,
    Srikanth.

  • Simple question about af:panelTabbed and required="true"

    Hello,
    I have a component af:panelTabbed with four tabs:
    In the fourth tab i have an af:inputText with the tag required="true"
    The problem is: The required is only applied if i am at the fourth tab (where the inputText is on).
    If i am at first tab, the form is commited and the required is not applied.
    Any help, please ?
    Victor Jabur

    To complement, here is my jspx and my Managed Bean:
    When i click at cb1 button, the focus would have to go for tab4, but the partial refresh doesn't work. If i use the refreshPage() method posted above, the focus works, but as mentioned, it's not web 2.0 common use.
    JSPX:
    <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
    <jsp:directive.page contentType="text/html;charset=UTF-8"/>
    <f:view>
    <af:document id="d1" title="Test Tab Component">
    <af:form id="fm1">
    <af:commandButton id="cb1" text="Execution Action" action="#{myBean.executeAction}" partialSubmit="true"/>
    <af:panelTabbed id="ptab" styleClass="AFStretchWidth">
    <af:showDetailItem id="tab1" text="Tab 1"/>
    <af:showDetailItem id="tab2" text="Tab 2"/>
    <af:showDetailItem id="tab3" text="Tab 3"/>
    <af:showDetailItem id="tab4" text="Tab 4" binding="#{myBean.tab4}" clientComponent="true">
    <af:inputText id="it1" label="Input Text" binding="#{myBean.inputText}" clientComponent="true"/>
    </af:showDetailItem>
    </af:panelTabbed>
    </af:form>
    </af:document>
    </f:view>
    </jsp:root>
    Managed Bean:
    package com.test;
    import javax.faces.application.FacesMessage;
    import javax.faces.context.FacesContext;
    import oracle.adf.view.rich.component.rich.input.RichInputText;
    import oracle.adf.view.rich.component.rich.layout.RichShowDetailItem;
    import oracle.adf.view.rich.context.AdfFacesContext;
    public class MyBean {
    private RichInputText inputText = new RichInputText();
    private RichShowDetailItem tab4 = new RichShowDetailItem();
    public void executeAction(){
    if(this.inputText != null){
    if (this.tab4 != null) {
    FacesContext context = FacesContext.getCurrentInstance();
    FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Enter a value", "");
    context.addMessage(this.inputText.getClientId(context), facesMsg);
    this.inputText.setValid(false);
    this.tab4.setDisclosed(true);
    AdfFacesContext.getCurrentInstance().addPartialTarget(this.inputText);
    AdfFacesContext.getCurrentInstance().addPartialTarget(this.tab4);
    //AdfFacesContext.getCurrentInstance().partialUpdateNotify(this.inputText);
    //AdfFacesContext.getCurrentInstance().partialUpdateNotify(this.tab4);
    public void setInputText(RichInputText inputText) {
    this.inputText = inputText;
    public RichInputText getInputText() {
    return inputText;
    public void setTab4(RichShowDetailItem tab4) {
    this.tab4 = tab4;
    public RichShowDetailItem getTab4() {
    return tab4;
    }

  • A simple question about Drag and Relate navigation

    Dear experts
    I have found SAP help or related manuals only good at talking difficult things such as how to customise the drag and relate targets, etc.  However, after I followed exactly and then how to test.
    Then I just see pieces of information, very unstructured.  Spending me a whole day, even I can't get a good simple example on how to really perform a drag and relate at least for the proof of concept at EP 6.0.   It spent a lot of time in describing what the navgiation panels about, what drag and relate targets.  Then how to do it in once transversal.  That is, with all customisation, how to drag and relate an object.
    My step is with iview A, shows a purchase order details showing a drag and relate enabled object like vendor no.
    Then I try to drag this vendor no. to a display vendor iview, iview B.
    I have known I have to put iview A and iview B to a Drag-and-relate targets.  I am sure I have done this.  Does it mean opening the portal, I will see both iview A and iview B appearing at the same time in the drag-and-relate target area?  However, in my case, it is not, iview A only appears in that area when I load it once, same to view B.  When I load iview B, iview A links from D&R target will be wiped off.  Then how I can drag an item from iview A to B while each one of them can only appear at any time.
    Can anyone give me a simple guide (don't give me an internet link from help.com) I have been tired of this.
    First, I would to make sure if my so called self-learnt drag-and-relate simple action is correct in the steps or really I have made something wrong in the customisation or even a bug there.
    Can anyone on the planet have this experience, pls. act as my teacher in this area?
    Rgds
    Stephen

    Thanks
    I have tried the 1st way already.  But I can see both iviews existing in the D & R targets.  Now I try to drag an item with business object BUS2002 from iview A to relate to LFA1 of iview B of the same back end system.
    But iview B shown up with that data of LFA1 shown up (in my case the vendor no.)
    I have used autocomplete relationship and I have checked it has been well-defined already.  Also check from metadata at backend they are both active.
    Do you have any clues to the pitfall in my case?
    Rgds

  • A question about JTable .setValueAt(...)

    hi, I write some code which use the Table to represent the data fetched from MS-ACCESS.
    the problem is about the UpdateObject(...) method which is in the implement of the AbstractTableModel method setAtValue(). when transfered OBJECT TYPE is java.lang.String, I can't get the correct result in the JTable view.
    by the way, I use java2SE 6 Beta version
    my code is as below, could somebody point me out my problem
    public class MyTableModel extends AbstractTableModel {
        private ResultSet rs ;
        private ResultSetMetaData rsmd;
        /** Creates a new instance of MyTableModel */
        public MyTableModel() {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            String url = "jdbc:odbc:CoffeeBreak";
            try {
                Connection con = DriverManager.getConnection(url,"","");
                String strSQL = "SELECT * FROM COFFEES";
                Statement pSt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                rs = pSt.executeQuery(strSQL);
                rsmd = rs.getMetaData();
            } catch (SQLException ex) {
                ex.printStackTrace();
    /* table model retrieve the Class type of a column method here*/
    public Class getColumnClass(int c){
            try {
                return Class.forName(rsmd.getColumnClassName(c+1));
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return String.class;
    //method of update database and JTable after user edited a table cell
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            try {
                int concurrency = rs.getConcurrency();
                if(concurrency == 1008){
                    rs.absolute(rowIndex+1);    //the JTable row index is start from 0,so plus 1
                    rs.updateObject(columnIndex+1, aValue);//the JTable column index is start from 0, so plus 1
                    rs.updateRow();
            } catch (SQLException ex) {
                ex.printStackTrace();
        } when the column type is about java.lang.String, the cell's result is incorrect, it looks like "[B@1f8f72f" and database can't update.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Yes, I have implemented them all.
    I paste them all now. thank all here, first.
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.AbstractTableModel;
    * @author qhj
    public class MyTableModel extends AbstractTableModel {
        /** Creates a new instance of MyTableModel */
        private ResultSet rs ;
        private ResultSetMetaData rsmd;
        public MyTableModel() {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            String url = "jdbc:odbc:CoffeeBreak";
            try {
                Connection con = DriverManager.getConnection(url,"","");
                String strSQL = "SELECT * FROM COFFEES";
                Statement pSt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                rs = pSt.executeQuery(strSQL);
                rsmd = rs.getMetaData();
            } catch (SQLException ex) {
                ex.printStackTrace();
        public int getRowCount() {
            try {
                rs.last();
                return rs.getRow();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return 0;
        public int getColumnCount() {
            try {
                return rsmd.getColumnCount();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return 0;
        public Object getValueAt(int rowIndex, int columnIndex) {
            try {
                rs.absolute(rowIndex+1);
                return rs.getObject(columnIndex+1);
            } catch (SQLException ex) {
                ex.printStackTrace();
            return null;
        public String getColumnName(int column){
            try {
                return rsmd.getColumnName(column+1);
            } catch (SQLException ex) {
                ex.printStackTrace();
            return "N/A";
        public Class getColumnClass(int c){
            try {
                return Class.forName(rsmd.getColumnClassName(c+1));
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return String.class;
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            return true;
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            try {
                int concurrency = rs.getConcurrency();
                if(concurrency == 1008){
                    rs.absolute(rowIndex+1);
                    rs.updateObject(columnIndex+1, aValue);
                    rs.updateRow();
            } catch (SQLException ex) {
                ex.printStackTrace();
            fireTableDataChanged();
    }

  • Help required in JTable?

    I have a requirement from our client with following features in Table in java application. I have to find which features which they need are feasible to implement.
    I have searched in many places but mostly the features are not at all feasible to code. Anyway I am posting the, here to verify if my findings are correct.
    1. Vertical UI in the header.
    2. Horizontal scrollbar within JTable i.e. if there are 8 columns in a table means, 1st three columns must be fixed and rest 5 columns should be scrollable horizontally. (Like Freeze panes feature in MS Excel)
    3. Column wise sorting.
    4. Expanding a row in a table in a size equal to the size of highest length data in a row.
    Please guide me if the above features are feasible to implement in JTable. If so please provide some help on this.

    The item no 4 is
    Say there are some 5 columns in a row onw of which is a drop down. Each cell in the row shall have different text with different characters. The row height should be set to the length of highest text length in that row when an option Expand is selected from a dropdown in that row. This is the requirement.

  • Simple Questions about ESB and ftp adapter.

    We have the following Business Scenario:
    We have a partner company that provide us a ftp server with some files. We need to transfer these files from this server to other server, we don't need to read the file's content, we just need transfer the files.
    We are planning to use ESB in order to implement this solution but we have the following questions:
    Is it possible use the ftp adapter in order to transfer the files?
    Is there any example available about (Schema is Opaque feature) on a ftp adapter?
    Thanks
    Ramiro Ortiz

    Thank you very much for your reply.
    . I am trying to construct a FTP ( get) adapter with which I would like to do a simple FTP transfer from /var/out directory server xxx.oms.com (say) to a directory /home/in on the server bos1.oms.com (say) could not figure out this in jdeveloper 10.1.3.3 ( do i need upgraded jdeveloper?). The esb server and control exists on server bos1.oms.com. While constructing the adapter in jdeveloper it asks for physical directory? Is this the directory where it will the read the file from? How do I specify if the directory exists on the different server.
    is it something like xxx.oms.com:/var/out
    Please let me know.

  • Question about JTable...

    Hi people,
    I have a question about class JTable of Java and how can i add dynamic content to it. More specific i would like
    to create a table which has a dynamic content at its rows and columns (etc i will use a method which will generate
    dates of 1/02/05 to 1/03/05 format and i will add them as titles in the row section of my table and in the column
    section i will add times of the day divided in quarters like 00.00 00.15 00.30 00.45..... just like a calendar) Any ideas????

    Use the DefaultTableModel. It has addRow and addColumn methods.

  • Simple question about telnet and characters

    Hi all,
    We've installed for the first time a SUN machine. So i think it's for a SUN expert a very simple question.
    Normally when i type a special character it will be dispayed like " � " [alt+132]
    But when i use a telnet session and i type "alt+132" i get a "d" and not "�".
    Does someone know where i must start to find out how this works ?
    Thanks you very much.
    ESP

    This is probably related to the locale your server is in. I don't remember the default locale a box is installed in if you don't specify. I think its "C". I use the UTF-8 or en_US.ISO8859-1 locales at home. At work, usually C but sometimes applications may require UTF-8. BEA Weblogic required this for a project a while back. This is defined in /etc/init/tz.

Maybe you are looking for

  • Linked Smart Object:  Allowed File Type and Editor

    Please forgive my lack of knowledge.  I'm evaluating PS CC 2014, own PS 5.1 and am a hair shy of being a novice.  Presently I'm doing Photomerge Focus Stacking.  What I'm hoping is that DNG files can be Linked Smart Objects and that I can modify the

  • Disk Utility - Verify Disk Permissions / Repair

    I run Disk Utility > Verify Disk Permissions with this rsult: Verify permissions for "Macintosh HD" Permissions differ on "usr/share/derby", should be drwxr-xr-x , they are lrwxr-xr-x . The following repair was successful. A few minutes later I run V

  • ICM_HTTP_TIMEOUT error

    *Hi Experts,* found the following error in the integration engine for the message.  using File adapter(FTP) and we are using BPM for this scenario. <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> - <!--  Call Adapter   --> - <SAP:Error xmlns

  • Help with importing AVHD lite

    Ok.. hopefully someone can give me some help. I have a panasonic ZS3, and am frustrated with the importing of my video files. I have read and re-read the posts on this. My problem is that sometimes it works, and sometimes it doesn't. iMovie, iphoto A

  • Where could i place the RTF file (locally or in server custom top)

    Hi guys, I am very new to xml report publisher and I completed one RTF template successfully and i am accessing oracle apps through my client instances which is in USA. I dont knw where to place the RTF file whether in my local system or in the custo