Updating JTable? Very important..

Hi,
I have a JTable that uses a DefaultTableModel. First, I create the defaultTableModel with no entries in it. Then I display the table, which of course just shows the column names initially. Then I take a query from user to access the database. Then I display the results obtained from database into the table. But the table doesnt show any of the rows added later.
Here is the code:
/*code skipped */     
     public JPanel getPane()
/*code skipped */     
//display the table using the DefaultTableModel
          subPane=new JPanel();
          tableModel=new MyDefaultTableModel(new String[]{"Roll No","Name","Class","Grade","Marks","BirthDate","Interests"});
          JTable table=new JTable(tableModel);
          scrollPane=new JScrollPane(table);
          subPane.add(scrollPane);
          pane.add(subPane);
          return pane;
/*code skipped */     
          try
//excute query
               ResultSet rsPersonal=stPersonal.executeQuery(queryPersonal);
//add rows obtained from database
               while( rsPersonal.next() )
                    tableModel.addRow(new Object[]{"",rsPersonal.getString("name"),"","","",rsPersonal.getString("birthDate"),rsPersonal.getString("interests")});
//fire structure changed
               tableModel.fireTableStructureChanged();
          catch(Exception e)
               System.out.println(e);
//class that extends DefautTableModel
     public class MyDefaultTableModel extends DefaultTableModel
          String[] colNames;
          MyDefaultTableModel(String[] names)
               colNames=names;
          public int getColumnCount()
               return colNames.length;
          public String getColumnName(int col)
               return colNames[col];
          public boolean isCellEditable(int row,int col)
               return true;
          public Class getColumnClass(int col)
               return getValueAt(0,col).getClass();
          public Object getValueAt(int row, String columnName)
               int col=findColumn(columnName);
               return getValueAt(row,col);
          public void sortTable(String columnName)
               int col=findColumn(columnName);
               Vector tableData=getDataVector();
               Collections.sort( tableData.subList(0,tableData.size()), new ColumnSorter(col,true) );
               fireTableStructureChanged();
/*code skipped */     How can I display the new rows added?

here is a very simple code that first displays the window, then adds rows to the table model. This is working without the repaint() method! Any comments....
/* Table demo that reads from oracle database and then displays it */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
import javax.swing.table.DefaultTableModel;
public class tableDemo
     private boolean err=false;
     private Vector columnNames=new Vector(0,1);
     private Object queriedDataRow[]=new String[2];
     private MyDefaultTableModel dtm=new MyDefaultTableModel();
     private void activateDatabase()
          try
               Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
               Connection con=DriverManager.getConnection("jdbc:odbc:oracleDsn","scott","tiger");
               Statement st=con.createStatement();
               ResultSet rs=st.executeQuery("SELECT * FROM dummy");
               while( rs.next() )
                    queriedDataRow[0]=(Object)rs.getString("col1");
                    queriedDataRow[1]=(Object)rs.getString("col2");
                    dtm.addRow(queriedDataRow);
               rs.close();
               st.close();
          catch(Exception e)
               System.out.println(e);
               err=true;
     private void drawWindow()
          JTable table=new JTable(dtm);
          JScrollPane scrollPane=new JScrollPane(table);
          scrollPane.setPreferredSize(new Dimension(500,200));
          JPanel pane=new JPanel();
          pane.add(scrollPane);
          JFrame frame=new JFrame("Table");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(pane);
          frame.pack();
          frame.setVisible(true);
     public class MyDefaultTableModel extends DefaultTableModel
          String colNames[]={"col1","col2"};
          public int getColumnCount()
               return colNames.length;
          public String getColumnName(int col)
               return colNames[col];
          public boolean isCellEditable(int row,int col)
               return false;
          public Class getColumnClass(int col)
               return getValueAt(0,col).getClass();
     public static void main(String[] args)
          final tableDemo app=new tableDemo();
//          if(!app.err)
               javax.swing.SwingUtilities.invokeLater
                    new Runnable()
                         public void run()
                              app.drawWindow();
                              app.activateDatabase();
}

Similar Messages

  • Problems whit Jtable(very important)

    I have a Jtable and i want to do something like this:
    when you press ENTER on a cell all the cells in the same row have the same value.
    Can anybody help me!!!!!

    You don't need to capture the key event. The key event is captured and dealt with by the JTextField that is the editor for the cell in your table.
    When the setValueAt method is called the table has already captured and processed the key event. At this time the table will be able to tell you the row and column which was edited, and the current value of the cell. This value will be the value after editing.
    The only problem with this is that it is a loss of focus event and will not be recieved until the user presses enter, tabs or clicks on a new table cell.
    If you really feel you need to capture the key events, you will need to use a custom cell editor.
    regards,
    Terry

  • I have numbers on my ipad and after the latest update I can't open a spreadsheet in it, a very important spreadsheet. I have rebooted a number of times but this does not seem to have fixed it can someone advise what I can do??

    I have an ipad and have just downloaded the lastest update, now I have a very very important spreadsheet that will not open!!!! other spreadsheets open fine but for some just this one will not open. I have rebooted the ipad and tried re-syncing but to no avail, can anyone HELP?????

    I had the same problem. I created an iCloud account and backed up my iPad to iCloud. I then went to www.iCloud.com, signed-in and then I was able to download my spread sheet data. At least I have my data.

  • I have several very important school related documents on my iPad in the Pages app. Ever since i updated to iOS5, i can no longer open any documents in Pages that I made before I updated. Please help

    I have several very important school related documents on my iPad in the Pages app. Ever since i updated to iOS5, i can no longer open any documents in Pages that I made before I updated. Please help

    Without the iPad connected, open up iTunes on your computer.  Go to iTunes/Preferences/Devices and delete the backups that you're absolutely certain do not have the documents.  Refer to figure below.
    iTunes, select the iPad and then select the Summary tab.  Follow directions for Restore and be sure to say "NO" to creating a backup.  (You don't want to create a new backup that does not have the docs.)  You will then be warned that all data (apps, music, movies, etc.) will be erased but, as the Restore finishes, you will be asked if you wish the contents of the backup to be copied to the iPad.  This time, say "yes."
    Repeat all of the above as required until you get the docs.

  • I updated 6.1.2 to my iphone 4 via itunes. when i finished, i lost all my messages and pictures. how can i restore it? please help. they're very important to me

    i updated my iphone 4 via itunes from 5.1.1 to 6.1.2. when i finished update it, it deleted all my messages and pictures and they're very important to me. please help me to restore it. thanks

    If you did this on the Computer you Usually use... then Sync the content back...
    If not... See Here...
    Download Past Purchases
    http://support.apple.com/kb/HT2519

  • I updated to 8.1.3 on my 5s and my very important notes are gone!I bought extra space in icloud and backed up to icloud before the upgrade. Should n\my notes not be there somewhere? Where?

    I updated my 5s to 8.1.3 and my very important notes are gone. Before the upgrade I bought extra space in icloud and backed up to icloud. Should my notes not be there? Where? How do I get them back?

    i did go to notes in gmail and none of thm where there but i havent connected my ipod to a computer for about a month so majoriy of the important ones will be backed up i hope to god  thank you

  • Hello , Recently my company purchased a Fujifilm X30 . We were surprised that Adobe has not updated the plug in for this camera. Since we are your customers, we would like to know, when they will perform this update ? For us it is very important to work w

    Hello , Recently my company purchased a Fujifilm X30 . We were surprised that Adobe has not updated the plug in for this camera. Since we are your customers, we would like to know, when they will perform this update ? For us it is very important to work with all our tools work quickly and efficiently, I guess I understand.
    We await your response .
    Thank you very much .

    This is a user to user forum with "some" Adobe staff participation, make requests at this link
    https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform

  • HT1414 Hi All, i recently done a back up and update & restore, but ive lost my notes, my text messages and my reminders and notes on the calender, i also have lost the data i had in an app which was very important to me. Please Please help me,  i,m total

    Hi All, i recently done a back up and update & restore, but ive lost my notes, my text messages and my reminders and notes on the calender, i also have lost the data i had in an app which was very important to me. Please Please help me,  i,m total novice.
    I did this back up because i was instructed by my service provider. This was supposed to sort out my losing connection problem, which it didn't, it instead gave me a new problem. If there is anyone out there who can help me to retrieve my lost information i would appreciate it.
    Thank You in advance.

    You should be syncing your contacts with an app on your computer or cloud service (iCloud, Gmail, Yahoo, etc), and not relying on a backup.  If you haven't been doing this, start now and then restore your old backup.  You will then be able to sync the new contacts back into the phone.  However, you will lose all messages, etc newer thant the backup.

  • Clear and update JTable.

    Hi. this is a follow up from [Original Tread in "New To Java"|http://forums.sun.com/thread.jspa?messageID=10886612�]
    Hope you can help me here. For you who dont read the link. This application is build only to lay up here. So the Layout aint pretty. It compiles and run tho. What i want and cant get to work is to reload table when i push my JTabbedPane.
    Main Class
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Main {
        public Main() {
            run();
        public void run(){
         frame();
        // clear and update JTable in class three
        public void clearThree() {
            Three t = new Three();
             t.clearVector();
        public JFrame frame() {
            JFrame frame = new JFrame();
            JTabbedPane tab = new JTabbedPane();
            tab.addTab("two",new Two());
            tab.addTab("three", new Three());
            tab.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    clearThree();// this dont work
            frame.add(tab);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800,400);
             frame.setVisible(true);
             frame.pack();
            return frame;
        public static void main(String[] args) {
             java.awt.EventQueue.invokeLater(new Runnable() {
                         public void run(){
           new Main();
    }// class two
    package test;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.swing.*;
    // class twoś only purpose is to  call clear() in class Three
    public class Two extends JPanel{
    public Two(){
    toolBar();
      public void clearThree () {
       Three t = new Three();
       t.clearVector();
      public void toolBar(){
      JToolBar bar = new JToolBar();
      JButton button = new JButton("clear");
      button.addActionListener(new ActionListener (){
          public void actionPerformed(ActionEvent e){
          clearThree(); // this dont work
    bar.add(button);
    add(bar);
    }// class three hold the table.
    package test;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    public class Three extends JPanel{ 
            DefaultTableModel model;
            JTable table;
            Vector v = new Vector();
            Vector a = new Vector();
            Vector<Vector> r = new Vector<Vector>();
        public Three() {
            jBar();
            jTable();
        public void clearVector(){
            v.removeAllElements();
            a.removeAllElements();
            r.removeAllElements();
            model.fireTableDataChanged();
        public void jBar() {
            JToolBar bar = new JToolBar();
            JButton button =  new JButton("clear");
            button.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    clearVector();// this does work
            bar.add(button);
            add(bar);
        public JScrollPane jTable(){
            v.addElement("ID");
            v.addElement("Name");
            a.addElement("01");
            a.addElement("Magnus");
            r.add(a);
            model = new DefaultTableModel(r,v);
            table = new JTable(model);
             JScrollPane pane = new JScrollPane(table);
             add(pane);
             return pane;
    }

    Thank you for your replay, I have taken all of your tips and modifed my original application. but the problem is still there. This has been a very messy thread. and it is becouse i thougth it were a table/model problem. But it&#347; not. In the code below I have a JTextField. When i push the JTabbedPanes i want the setText(); to kick in. this compile and run.
    // class One
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Main {
        public Main() {
            run();
        public void run(){
         frame();
        public JFrame frame() {
            JTabbedPane tab = new JTabbedPane();
            final  Three t = new Three();
            JFrame frame = new JFrame();
            JPanel panel = new JPanel();
            tab.addTab("two",new Two());
            tab.addTab("three", new Three());
            tab.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                      t.setText(); // should call setText() in class Three.
            frame.add(panel);
            frame.add(tab);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800,400);
             frame.setVisible(true);
             frame.pack();
            return frame;
        public static void main(String[] args) {
             java.awt.EventQueue.invokeLater(new Runnable() {
                         public void run(){
           new Main();
    }class Two. Does nothing more then holding an empty tab
    package test;
    import javax.swing.*;
    public class Two extends JPanel{
    public Two(){
    emptyPane();
      public void emptyPane () {
      JLabel  label = new JLabel("Just an empty JTabbedPane");
      add(label);
      }class Three
    package test;
    import javax.swing.*;
    public class Three extends JPanel{ 
             JTextField text;
        public Three() {
            text();
        public void setText() {
            text.setText("Hello"); // this piece of code i want to insert in my JTextField
            validate();                // when i push the JTabbedPanes.
            repaint();
            updateUI();
        public JTextField text(){
             JToolBar bar = new JToolBar();
            text = new JTextField("",20);
            bar.add(text);
            add(bar);
            return text;
    }

  • SoundFonts - small problem. Please help me because this is very important to

    Hello everyone. I have just upgraded from a SoundBlaster Audigy, to a SoundBlaster X-Fi Music edition.
    I have a collection of soundfonts which I used to use on my Audigy. They worked fine. Now that I'm using the X-Fi, they all work well, apart from one, and the one that doesn't work is my most used, most important soundfont.
    Description of problem:
    When I run my midi file, it starts playing the music using the new soundfont, but after about 0 seconds or so, the sound stops - even though the music is still playing. I then can occasionally hear a note or two, but its no longer playing properly. All my other soundfonts work perfectly, so I really dont understand why this one would cause troubles. They are all .SF2 files.
    Other Information:
    ) I am using "SoundFont Bank Manager" to load the soundfonts. They all work great apart from the main one I want to use. It worked fine on my Audigy. The Cache part says 7.3mb Used/ 229.8mb Free.
    2) I am on Windows XP Professional - Service pack 2.
    3) The rest of my computer is very powerful. Its a core2duo, 2gig of RAM, 320gig seagate barracuda hard dri've etc. Regularly defragged.
    4) I have the latest soundcard drivers (And direct X, video drivers, bios drivers, etc.).
    5) I have no other problems with the computer.
    6) My Midi program is Guitar Pro, which plays special midi files. It is set up properly, and it plays everything perfectly - using all my soundfonts, except the one I most want to use..
    Please help me get this working. It is very important to me, and I need to get it working as soon as possible. I'll keep searching this thread incase I need to give any more information.
    Thanks in advance.Message Edited by acrobat on 02-09-200705:0 AM

    Why do you have two threads dealing with the exact same issue. That makes it confusing and hard to follow your issue to help you.
    Who is your carrier, I asked in the other thread?
    Have you tried YOUR sim card in another device, what happens?
    1. If any post helps you please click the below the post(s) that helped you.
    2. Please resolve your thread by marking the post "Solution?" which solved it for you!
    3. Install free BlackBerry Protect today for backups of contacts and data.
    4. Guide to Unlocking your BlackBerry & Unlock Codes
    Join our BBM Channels (Beta)
    BlackBerry Support Forums Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

  • I deleted a very important pages file from my iPad and I need it back

    I deleted a very important pages file from my iPad and I need it back pronto! I just updated my iPad without a computer and it had the file there. I need to know how to get back the file very quickly.
    thx in advance

    Thne unfortunately, your document is gone. You can restore lost or deleted documents from backups if you have backups - and as long as the backup contains the document - but if you did not copy the file to your computer - or backup the iPad, the document is gone.
    You really should start backup up your iPad. You can sign up for a free 5GB iCloud account right on the iPad and then you can use iCloud for backing up. You can do it right on the iPad.

  • VERY IMPORTANT QUESTION

    hello , i have just had a very important personal voice conversation which is very important for me i would like very much to get this coversation in media file is it possible , please help me this is extremely important for me
    thank you , if you anyone can help me please contact me , this is really very important this was a conversation of my life and i would very much have it for myself and some other people
    please help me , thank you

    Unfortunately, Skype doesn't save calls and video calls. 
    CONTACT SKYPE CUSTOMER SERVICE   |  HOW TO RECORD SKYPE VIDEO CALLS  | HOW TO HANDLE SUPICIOUS CALLS AND MESSAGES   |  WINDOWS PROBLEMS TROUBLESHOOTING   |  SKYPE DOWNLOAD LINKS  
    MORE TIPS, TRICKS AND UPDATES AT
    skypefordummies.blogspot.com

  • Cell color from input ... very  important

    how to convert a string (binary) of 8 bit , i have to put every bit into a cell of a table 2rows � 4columns, and color the background red in bit is 1 and blue if bit is 0...any idea, please is very important

    U have to convert your String of bits in a array of bits , and then create a procedure in a for cycle that scans the array and read the value of each postion , and then change the backgroundcolor
    However I have a problem to create a JTable and set different Backgrounds color for the cells of my JTable can you show me , how can I do ? a little example
    it's very important
    Thanks

  • Please help a very important

    Please help a very important
    There I have a database 8i
    An area of 36 GB and night Eugene space on the hard disk is 2 GB
    I want to reduce the database space has decided to delete the tables from 2006 to 2010,
    But the database space 36 still Kiev and what to do

    I wish I could locate the apple document about backups, I know there's an official one but I can't find it. If you have a .mac account you can use the "backup" program to do that. The other way is third party programs that will backup any updated files to a remote computer on your network, or another drive. Probably the easiest though is just burning the files you need to save to DVDs or CDs. Someone else could probably explain this a whole lot better than me though, so give it a try.
    Oh! And just out of curiocity, how did the program not work? Did you get an error, or was the folder just too far gone to get back? If the lisence you purchaced is transferable, you might just want to sell it to someone here or on ebay. Good luck.

  • Rollback Very Important

    Dear All,
    I have updated some table contents using some scripts. When i complete the update transactions, the power failure occurred and my system is rebooted. So my transactions are auto committed.
    Is any way to rollback my transactions.....?
    Very important issue.. Kindly help me.......
    Cheers,
    Moorthy.GS

    Once a transaction is committed, there is no way to uncommit it.
    Depending on the Oracle version and configuration, you may be able to flashback one or more tables to a point in time before the scripts ran, flashback the entire database to that point in time, or recover the database to that point in time, but those options will have their downsides.
    Justin

  • How to update link and import data of relocated incx file into inca file?

    Subject : <br />how to update link and import data of relocated incx file into inca file.?<br />The incx file was originally part of the inca file and it has been relocated.<br />-------------------<br /><br />Hello All,<br /><br />I am working on InDesignCS2 and InCopyCS2.<br />From indesign I am creating an assignment file as well as incopy files.(.inca and .incx file created through exporing).<br />Now indesign hardcodes the path of the incx files in inca file.So if I put the incx files in different folder then after opening the inca file in InCopy , I am getting the alert stating that " The document doesn't consists of any incopy story" and all the linked story will flag a red question mark icon.<br />So I tried to recreate and update the links.<br />Below is my code for that<br /><br />//code start*****************************<br />//creating kDataLinkHelperBoss<br />InterfacePtr<IDataLinkHelper> dataLinkHelper(static_cast<IDataLinkHelper*><br />(CreateObject2<IDataLinkHelper>(kDataLinkHelperBoss)));<br /><br />/**<br />The newFileToBeLinkedPath is the path of the incx file which is relocated.<br />And it was previously part of the inca file.<br />eg. earlier it was c:\\test.incx now it is d:\\test.incx<br />*/<br />IDFile newIDFileToBeLinked(newFileToBeLinkedPath);<br /><br />//create the datelink<br />IDataLink * dlk = dataLinkHelper->CreateDataLink(newIDFileToBeLinked);<br /><br />NameInfo name;<br />PMString type;<br />uint32 fileType;<br /><br />dlk->GetNameInfo(&name,&type,&fileType);<br /><br />//relink the story     <br />InterfacePtr<ICommand> relinkCmd(CmdUtils::CreateCommand(kRestoreLinkCmdBoss)); <br /><br />InterfacePtr<IRestoreLinkCmdData> relinkCmdData(relinkCmd, IID_IRESTORELINKCMDDATA);<br /><br />relinkCmdData->Set(database, dataLinkUID, &name, &type, fileType, IDataLink::kLinkNormal); <br /><br />ErrorCode err = CmdUtils::ProcessCommand(relinkCmd); <br /><br />//Update the link now                         <br />InterfacePtr<IUpdateLink> updateLink(dataLinkHelper, UseDefaultIID()); <br />UID newLinkUID; <br />err = updateLink->DoUpdateLink(dl, &newLinkUID, kFullUI); <br />//code end*********************<br /><br />I am able to create the proper link.But the data which is there in the incx file is not getting imported in the linked story.But if I modify the newlinked story from the inca file,the incx file will be getting update.(all its previous content will be deleted.)<br />I tried using <br />Utils<IInCopyWorkflow>()->ImportStory()<br /> ,But its import the incx file in xml format.<br /><br />What is the solution of this then?<br />Kindly help me as I am terribly stuck since last few days.<br /><br />Thanks and Regards,<br />Yopangjo

    >
    I can say that anybody with
    no experience could easily do an export/import in
    MSSQLServer 2000.
    Anybody with no experience should not mess up my Oracle Databases !

Maybe you are looking for

  • Supplier Sites open interface

    Hi, I got a problem in Supplier Sites open interface in 12,After importing it to Interface we are running concurrent program Supplier Sites open interface in this it was not picking the records, in the output file it was showing , Zero records import

  • To call Jsp in Iframe.

    hi Experts, I am using an iframe in my project i want to display a .jsp page in my iframe. The code i used is <% String jsp = componentRequest.getWebResourcePath() + "/pagelet/divcode.jsp";%> <iframe src=="<%=jsp %>"  height="70" width="900" top="0px

  • How to connect two pcs SQLPLUS

    I m on pc ip=11 and want to connect to the listener of pc ip 12...how do i do it? c:\sqlplus sys as sysdba/oracle@????????????????

  • Upgrading from 4.7 to ECC 6.0 And GTS 2.0 to a newer version

    Hi everyone, I am new to SAP SD, I am involved in upgrading from R/3 4.7 to ecc 6.0 and GTS 2.0 to a newer version. Can somebody tell me the major differences in these two vesions and also some link through which I can get some info. It is very urgen

  • Service Tax credit in TAXINN Process.

    Dear All. Is it mandatory to transfer of Credit from the Interim Service Tax Account to the Final Service Tax Credit Account after the Vendor's Invoice has been paid for.Is there any other alternative to this.We are on ECC 6.0 Do we need to define th