Refreshing JTable Contents Correctly

I am using a JTable within a JScrollPane. The porblem I am having is getting the JTable to redisplay correctly when the TableModel data changes.
I tried creating a new instance of TableModel each time I update data to be displayed, and (re)setting the JTable's model to the new instance. this displays the data correctly. (Any of the fixed viewport space that is not occupied is gray.) Unfortunately with this strategy, each time the JTable is updated, the scrollbar position changes (sometimes overlapping the data, sometimes outside the data) or if no scrollbar is needed, blank space appears whenever the previous display had a scrollbar.
The second strategy I tried was clearing the values in the SAME TableModel (no new instance) and loading the new data into it. This works, except that when a new set of data is displayed, if the previous display had more rows displayable, white space fills the now vacant space. I tried revalidating the table, but that throws an array-out-of-bounds exception at the model's "getValueAt(r,c)" method.
Can someone tell me the correct strategy for loading new data into a JTable, and get the data to re-display correctly?
Thanks for your help.

You don't have to create a new instance every time. To redisplay the whole data, just get the current Table Model say tableModel and set row count to 0 like tableModel.setRowCount(0). Now add all the rows into the model.
Also sometime getAutoCreateColumnsFromModel() when set to true gives problems when you define your own TableColumn's. So you have to set it to false.
I will suggest using the TableColumnModel along with TableModel for a table. (For advanced development it helps)
It should display correctly. You can fine tune the table with lot of properties available for table. You have to read doc for the same.
Hope it helps.

Similar Messages

  • Refreshing JTable contents (rows and columns) handling.

    Hi,
    I have a general question related to refreshing the contents of JTable and handling some application specific requirements.In our application we are planning to refresh the contents of JTable automatically after certain period of time by fetching data from database and update the JTable contents or user has clicked refresh button.
    But following scenarios we are planning to handle when refresh is called automatically or user has clicked refresh button.
    1) User is working with data of JTable. Like rows of JTable has checkBoxes and user selects them and doing operation like viewing the details of selected rows in new details dialog. So if refreshing is done then the selection will be lost if I update the whole data in JTable.
    a)Will it be possible to append the data at the end of JTable rows without disturbing the existing JTable contents.
    b) Is it feasible to compare the data of existing rows and newly fetched rows and update only the rows whose values are changed in database or update specifically updated columns. But this comparision for finding changed values will result in performance problems.So are there any other alternatives of doing this, ideas are most welcome.
    c) Simple way is to alert the user that data will be updated and everything will be refreshed will be the choice in worst case.
    I guess many may have encountered such problems and may have solved it depending on the product requirements.
    Ideas and suggestions are most welcome.
    Regards.

    Hi,
    Here are my views and my assumptions.
    Assumptions :
    1) Your JTable is populated with list of Objects.
    2) Your tables in database is having columns like created date, created time, updated date updated time
    3) Order by clause for all the time will remain same.
    If these assumptions are correct then I think you can achieve your goal.
    Here how it is.
    Your application session will maintain last db hit time and will maintain for every hit that applicate made to fetch data from db.
    When object is created on the server side once it fetch data from table it will compare the created date/time or update date/time with the session varibale that holds last visit date/time. Based on this flag need to be set to indicate if this item is added/updated/deleted since last visit.
    And when all these object is returned to your client, the table model will iterate through the list and based on object index in the list and and if object is changed will update only that perticular row.
    Hope this is what you want to achieve.
    Regards

  • Refreshing JTable (JDBC)

    Hi there!
    I would like to ask your help regarding JTable.
    I am just new in Java comming from VB. I really cannot understand how JTable works.. since in VB it is very easy to refresh the table/grid.
    Any one who got a simple program (Even using MS Access) that will display DB Table's content to a JTable object and will be able to refresh JTable's content everytime a record is updated? (Even the refreshing of table side only).
    Hope you guys can help me with this since its been weeks already looking for a sample and explanation which is easy to understand.
    Thanks!

    have you tried sun's tutorial: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html ?
    JTable is implemented with a data model (table model) as its data container.
    So you need to update the table model first before re-displaying your table. :)

  • Page is not refreshing with the correct data.

    Hello experts,
    I have an unusual situation and I'm not sure why it is happening. We have 3 instances and the error is occurring in one of them.
    So here is the issue:
    1) I created a custom extended controller for a customer site form to check the character length of address lines 1 and 2.
    2) User creates a new contact under customer site. On the contact creation page, the contact information is entered and click Apply.
    After the contact has been created, the application directs you back to the customer site page.
    3) On the customer site page, the user clicks Apply again. The custom extended controller runs and then it takes you back to the customer site page.
    4) Now the page has some other address that is not in anyway related to the customer.
    5) I checked in the back end and the address is associated to hz_parties.party_id = -1.
    If I remove the custom controller the page refreshes with the correct address information. What I am baffled is that it is only happening in 1 of the 3 instances (all using Release 12.1.3).
    I already asked the dba to bounce middle tier/apache, cleared the cache and it is still having the same issue.
    Anyone have any idea why this is happening?

    Here's the custom controller code:
    package xbol.oracle.apps.ar.cusstd.acctSite.webui;
    import java.io.PrintStream;
    import oracle.apps.ar.cusstd.acctSite.webui.ArAcctSiteOverviewCO;
    import oracle.apps.fnd.framework.*;
    import oracle.apps.fnd.framework.webui.OADialogPage;
    import oracle.apps.fnd.framework.webui.OAPageContext;
    import oracle.apps.fnd.framework.webui.beans.OAWebBean;
    import oracle.jbo.Row;
    public class XXF5ArAcctSiteOverviewCO extends ArAcctSiteOverviewCO
    public void processRequest(OAPageContext oapagecontext, OAWebBean oawebbean)
    System.out.println("Running extended controller processRequest......");
    super.processRequest(oapagecontext, oawebbean);
    public void processFormRequest(OAPageContext oapagecontext, OAWebBean oawebbean)
    System.out.println("Running extended controller processFormRequest......");
    OAApplicationModule oaapplicationmodule = oapagecontext.getApplicationModule(oawebbean);
    String s = oapagecontext.getParameter("event");
    System.out.println((new StringBuilder()).append("Event: ").append(s).toString());
    System.out.println((new StringBuilder()).append("OkButton: ").append(oapagecontext.getParameter("OkButton")).toString());
    if(oapagecontext.getParameter("Save") != null || oapagecontext.getParameter("Apply") != null)
    System.out.println("Start of validation");
    OAApplicationModule AddressAM = (OAApplicationModule)oaapplicationmodule.findApplicationModule("HzPuiAddressAM");
    if(AddressAM == null)
    throw new OAException("Error: Stale Data - The requested page contains stale data. This error could hav" +
    "e been caused through the use of the browser's navigation buttons (the browser B" +
    "ack button, for example)."
    , (byte)0);
    System.out.println((new StringBuilder()).append("HzPuiAddressAM: ").append(AddressAM).toString());
    OAViewObject AddressVO = (OAViewObject)AddressAM.findViewObject("HzPuiLocationVO");
    System.out.println((new StringBuilder()).append("HzPuiLocationVO: ").append(AddressVO).toString());
    if(AddressVO == null)
    throw new OAException("Error: Stale Data - The requested page contains stale data. This error could hav" +
    "e been caused through the use of the browser's navigation buttons (the browser B" +
    "ack button, for example)."
    , (byte)0);
    Row AddressRow = AddressVO.getCurrentRow();
    System.out.println((new StringBuilder()).append("AddressRow1: ").append(AddressRow).toString());
    if(AddressRow == null)
    AddressRow = AddressVO.last();
    System.out.println((new StringBuilder()).append("AddressRow2: ").append(AddressRow).toString());
    String Address1 = (String)AddressRow.getAttribute("Address1");
    String Address2 = (String)AddressRow.getAttribute("Address2");
    System.out.println((new StringBuilder()).append("Address1: ").append(Address1).toString());
    System.out.println((new StringBuilder()).append("Address2: ").append(Address2).toString());
    int length1 = 0;
    if(Address1 != null)
    length1 = Address1.length();
    int length2 = 0;
    if(Address2 != null)
    length2 = Address2.length();
    System.out.println((new StringBuilder()).append("Address length1: ").append(length1).toString());
    System.out.println((new StringBuilder()).append("Address length2: ").append(length2).toString());
    if(length1 > 35 || length2 > 35)
    OAApplicationModule PurposeAM = (OAApplicationModule)oaapplicationmodule.findApplicationModule("HzPuiAccountSiteAM");
    OAViewObject PurposeVO = (OAViewObject)PurposeAM.findViewObject("HzPuiCustSiteUsesVO");
    int BPcount = PurposeVO.getRowCount();
    System.out.println((new StringBuilder()).append("Business Purpose Row Count: ").append(BPcount).toString());
    Row PurposeRow1 = PurposeVO.getFirstFilteredRow("SiteUseCode", "SHIP_TO");
    System.out.println((new StringBuilder()).append("Ship_to row: ").append(PurposeRow1).toString());
    System.out.println((new StringBuilder()).append("Length1: ").append(length1).append(" Length2: ").append(length2).append(" Ship_to row: ").append(PurposeRow1).toString());
    if(PurposeRow1 != null)
    System.out.println("Throwing exception.");
    System.out.println("Before SuperPFR2");
    super.processFormRequest(oapagecontext, oawebbean);
    System.out.println("After SuperPFR2");
    OAException ErrorMessage = new OAException("WARNING: Ship_To sites address lines 1 and/or 2 have more than 35 characters.", (byte)3);
    OADialogPage dialogPage = new OADialogPage((byte)1, ErrorMessage, null, "", null);
    dialogPage.setOkButtonItemName("OkButton");
    dialogPage.setOkButtonToPost(true);
    dialogPage.setPostToCallingPage(true);
    dialogPage.setOkButtonLabel("OK");
    oapagecontext.redirectToDialogPage(dialogPage);
    } else
    System.out.println("SuperPFR3");
    super.processFormRequest(oapagecontext, oawebbean);
    } else
    System.out.println("SuperPFR4");
    super.processFormRequest(oapagecontext, oawebbean);
    System.out.println("End of validation");
    } else
    System.out.println("SuperPFR5");
    super.processFormRequest(oapagecontext, oawebbean);
    public XXF5ArAcctSiteOverviewCO()
    }

  • How to write the JTables Content into the CSV File.

    Hi Friends
    I managed to write the Database records into the CSV Files. Now i would like to add the JTables contend into the CSV Files.
    I just add the Code which Used to write the Database records into the CSV Files.
    void exportApi()throws Exception
              try
                   PrintWriter writing= new PrintWriter(new FileWriter("Report.csv"));
                   System.out.println("Connected");
                   stexport=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                   rsexport=stexport.executeQuery("Select * from IssuedBook ");
                   ResultSetMetaData md = rsexport.getMetaData();
                   int columns = md.getColumnCount();
                   String fieldNames[]={"No","Name","Author","Date","Id","Issued","Return"};
                   //write fields names
                   String rec = "";
                   for (int i=0; i < fieldNames.length; i++)
                        rec +='\"'+fieldNames[i]+'\"';
                        rec+=",";
                   if (rec.endsWith(",")) rec=rec.substring(0, (rec.length()-1));
                   writing.println(rec);
                   //write values from result set to file
                    rsexport.beforeFirst();
                   while(rsexport.next())
                        rec = "";
                         for (int i=1; i < (columns+1); i++)
                             try
                                    rec +="\""+rsexport.getString(i)+"\",";
                                    rec +="\""+rsexport.getInt(i)+"\",";
                             catch(SQLException sqle)
                                  // I would add this System.out.println("Exception in retrieval in for loop:\n"+sqle);
                         if (rec.endsWith(",")) rec=rec.substring(0,(rec.length()-1));
                        writing.println(rec);
                   writing.close();
         }With this Same code how to Write the JTable content into the CSV Files.
    Please tell me how to implement this.
    Thank you for your Service
    Jofin

    Hi Friends
    I just modified my code and tried according to your suggestion. But here it does not print the records inside CSV File. But when i use ResultSet it prints the Records inside the CSV. Now i want to Display only the JTable content.
    I am posting my code here. Please run this code and find the Report.csv file in your current Directory. and please help me to come out of this Problem.
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    public class Exporting extends JDialog implements ActionListener
         private JRadioButton rby,rbn,rbr,rbnore,rbnorest;
         private ButtonGroup bg;
         private JPanel exportpanel;
         private JButton btnExpots;
         FileReader reading=null;
         FileWriter writing=null;
         JTable table;
         JScrollPane scroll;
         public Exporting()throws Exception
              setSize(550,450);
              setTitle("Export Results");
              this.setLocation(100,100);
              String Heading[]={"BOOK ID","NAME","AUTHOR","PRICE"};
              String records[][]={{"B0201","JAVA PROGRAMING","JAMES","1234.00"},
                               {"B0202","SERVLET PROGRAMING","GOSLIN","1425.00"},
                               {"B0203","PHP DEVELOPMENT","SUNITHA","123"},
                               {"B0204","PRIAM","SELVI","1354"},
                               {"B0205","JAVA PROGRAMING","JAMES","1234.00"},
                               {"B0206","SERVLET PROGRAMING","GOSLIN","1425.00"},
                               {"B0207","PHP DEVELOPMENT","SUNITHA","123"},
                               {"B0208","PRIAM","SELVI","1354"}};
              btnExpots= new JButton("Export");
              btnExpots.addActionListener(this);
              btnExpots.setBounds(140,200,60,25);
              table = new JTable();
              scroll=new JScrollPane(table);
              ((DefaultTableModel)table.getModel()).setDataVector(records,Heading);
              System.out.println(table.getModel());
              exportpanel= new JPanel();
              exportpanel.add(btnExpots,BorderLayout.SOUTH);
              exportpanel.add(scroll);
              getContentPane().add(exportpanel);
              setVisible(true);
          public void actionPerformed(ActionEvent ae)
              Object obj=ae.getSource();
              try {
              PrintWriter writing= new PrintWriter(new FileWriter("Report.csv"));
              if(obj==btnExpots)
                   for(int row=0;row<table.getRowCount();++row)
                             for(int col=0;col<table.getColumnCount();++col)
                                  Object ob=table.getValueAt(row,col);
                                  //exportApi(ob);
                                  System.out.println(ob);
                                  System.out.println("Connected");
                                  String fieldNames[]={"BOOK ID","NAME","AUTHOR","PRICE"};
                                  String rec = "";
                                  for (int i=0; i <fieldNames.length; i++)
                                       rec +='\"'+fieldNames[i]+'\"';
                                       rec+=",";
                                  if (rec.endsWith(",")) rec=rec.substring(0, (rec.length()-1));
                                  writing.println(rec);
                                  //write values from result set to file
                                   rec +="\""+ob+"\",";     
                                   if (rec.endsWith(",")) rec=rec.substring(0,(rec.length()-1));
                                   writing.println(rec);
                                   writing.close();
         catch(Exception ex)
              ex.printStackTrace();
         public static void main(String arg[]) throws Exception
              Exporting ex= new Exporting();
    }Could anyone Please modify my code and help me out.
    Thank you for your service
    Cheers
    Jofin

  • Podcasts app not refreshing new content?

    Hi, my podcasts app is not refreshing new content for last 4 days, is anyone else facing the same issue?

    Hello there, ikgandhi.
    The following Knowledge Base article offers up some great steps to review for issues with the Podcasts app for iOS:
    Podcasts app for iOS: Managing subscriptions
    http://support.apple.com/kb/HT6190
    Default settings: From your Home screen, tap Settings and then Podcasts. These settings are shared by all of your podcast subscriptions. These are known as default podcast settings.
    Refresh Every: You can choose how often your iOS device checks for new episodes to your subscriptions. It's set to check every six hours by default.
    Limit Episodes: You can pick how many episodes you see for subscriptions.
    Download Episodes: The latest episodes of your podcasts will download automatically if your iOS device is connected to Wi-Fi.
    Delete Played Episodes: If this is turned on, episodes will delete 24 hours after you finish playing them.
    Use Cellular Data: If your iOS device has a cellular connection, you can allow downloads to use cellular data when Wi-Fi isn't available. This is off by default. Downloads using cellular data are limited to 100MB per episode. If an episode is larger than that, it won't start downloading until you're connected to Wi-Fi.
    Podcast-specific settings: The second place you'll find subscription settings is within the Podcasts app. Tap a podcast subscription under My Podcasts and pull down with one finger to reveal the settings buttons. These settings are unique to each subscription. If you don't change anything here, the podcast subscription will just use the default settings. If you do make changes to a specific subscription’s settings, they'll only apply to that podcast.
    Play: This setting lets you change the order in which a subscription plays. If you're listening to a news style podcast, you may want to set this to play the new episodes first. If the series is more episodic, you may prefer to play oldest to newest.
    Sort Order: This changes the sort order of episodes that appear for a podcast (not its playback order).
    Subscribed: When this is on, new episodes of this podcast will be marked as unplayed as they become available.
    Refresh Every: You can choose how often your iOS device checks for new episodes to your subscriptions. It's set to check every six hours by default.
    Limit Episodes: You can pick how many episodes you see for subscriptions.
    Download Episodes: The latest episodes of your podcasts will download automatically.
    Delete Played Episodes: If this is on, episodes will be deleted 24 hours after you finish playing them unless you've marked them as Saved.
    Inactive subscriptions
    If you do not play or access a subscription within 15 days, your subscription to that podcast will go inactive and you will no longer receive updates to it. As soon as you access the subscription again it will refresh. 
    Thanks for reaching out to Apple Support Communities.
    Cheers,
    Pedro.

  • Error in Cache Refresh(Unable to refresh cache contents)

    Hi All,
    When i am refreshing Cache from the browser using link CPACache/refresh?mode=full it says success.
    When i do from SXI_CACHE it gives an error.
       Error during last attempt to refresh cache
       Unable to refresh cache contents
    So when i run any schenario in message monitoring i get the following error-
    <i>SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1">
      <SAP:Category>XIServer</SAP:Category>
      <SAP:Code area="XICACHE">UPDATE</SAP:Code>
      <SAP:P1 />
      <SAP:P2 />
      <SAP:P3 />
      <SAP:P4 />
      <SAP:AdditionalText>http response does not contain a valid XML root tag</SAP:AdditionalText>
      <SAP:ApplicationFaultMessage namespace="" />
      <SAP:Stack>An error occurred when refreshing the XI runtime cache</SAP:Stack>
      <SAP:Retry>N</SAP:Retry>
      </SAP:Error></i>
    I checked the INTEGRATION_DIRECTORY_HMI connection...
    here the response which im getting is..
    <i> HEADER NAME                HEADER VALUE
    response_line               HTTP/1.0 200
    server_protocol             HTTP/1.0
    status_code                 200
    status_reason
    ragma                       no-cache
    ache-control                no-cache
    ontent-type                 text/html
    ontent-length               87
    HTTP BODY
    TITLE>Error</TITLE>#<BODY>#<H1>Error</H1>#FW-1 at nebula: Unknown WWW s
    rver.</BODY>##
    Time (ms)                                 17</i>
    I believe that is not the right response.
    Everything was working fine yesterday when all of a sudden this error cropped up from no where.
    Regards,
    Rahul

    Hi,
    This is the error it shows there..
    <b>ERROR ID</b>      <i>UPDATE</i>
    <i>http response does not contain a valid XML root tag</i>
    Regards,
    Rahul

  • SXI_CACHE Error:  Unable to refresh cache contents

    Hello everybody,
    in SXI_CACHE we get the error:
    "Unable to refresh cache contents"
    "Error during last attempt to refresh cache"
    and on double clicking we get the message:
    Error Id: Communication
    if_http_client receive http_communication_failure.
    Any suggestions.
    We can't afford to restart the machines every time.
    Regards Mario

    Mario,
    Please refer to the Trouble SHooting section of this guide,
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/1a69ea11-0d01-0010-fa80-b47a79301290
    Also, check the HTTP Connection INTEGRATION_DIRECTORY_HMI and try a test connection of this. It should return  HTTP Code : 500
    Regards
    Bhavesh

  • Refresh the content of a page

    I' am developing a web monitoring console. Therefore I must be able to refresh the content of a page(table) and requery the underlying sql. Must I use a timer or are the other methods and alternatives.

    I am creating a project in Java Studio Creator 2. It starts out with a login screen and depending on the user rights, it lists(in a listbox) the possible pages the user has access to. From here the user selects the page they want to go to and takes them there. Now the problem that I am having is that this final page they are taken too needs to be refreshed every 5 seconds.
    I tried to add <meta http-equiv="refresh" content="5"/> in my <ui:head, but it just returned an error. After a little tweaking, I came up with <ui:meta httpEquiv="refresh" content="5"/>.
    The problem that I'm now having is that the page will wait 5 sec, and then reloads the previous page with the listbox. What am I doing wrong?
    The JSP head code that I have is as follows:
    <ui:head binding="#{Page3.head1}" id="head1">
    <ui:link binding="#{Page3.link1}" id="link1" url="/resources/stylesheet.css"/>
    <ui:meta httpEquiv="refresh" content="5"/>
    </ui:head>
    Now another question that I have, is how can I get a different page to start refreshing every 5 seconds after pressing a button and have it stop after pressing a second button.
    Thanks in advance,
    Raimie

  • Refreshing Form contents

    I have got three elements in my JFrame form. I removes one and want to refresh the contents of the window. Id I try to use repaint method, javac says its deprecated. Can somebody help me?
    Regards
    fahda

    Hi,
    Try calling the validate method. It's used to cause a container to lay out its subcomponents again after the components it contains have been added to or modified.
    Hope this helps.
    Bye!
    Pablo

  • To refresh the contents in JTextArea on selection of a row in JTable.

    This is the block of code that i have tried :
    import java.awt.GridBagConstraints;
    import java.awt.SystemColor;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.table.DefaultTableModel;
    import ui.layouts.ComponentsBox;
    import ui.layouts.GridPanel;
    import ui.layouts.LayoutConstants;
    import util.ui.UIUtil;
    public class ElectronicJournal extends GridPanel {
         private boolean DEBUG = false;
         private boolean ALLOW_COLUMN_SELECTION = false;
    private boolean ALLOW_ROW_SELECTION = true;
         private GridPanel jGPanel = new GridPanel();
         private GridPanel jGPanel1 = new GridPanel();
         private GridPanel jGPanel2 = new GridPanel();
         DefaultTableModel model;
         private JLabel jLblTillNo = UIUtil.getHeaderLabel("TillNo :");
         private JLabel jLblTillNoData = UIUtil.getBodyLabel("TILL123");
         private JLabel jLblData = UIUtil.getBodyLabel("Detailed View");
         private JTextArea textArea = new JTextArea();
         private JScrollPane spTimeEntryView = new JScrollPane();
         private JScrollPane pan = new JScrollPane();
         String html= " Item Description: Price Change \n Old Price: 40.00 \n New Price: 50.00 \n Authorized By:USER1123 \n";
         private JButton jBtnExporttoExcel = UIUtil.getButton(85,
                   "Export to Excel - F2", "");
         final String[] colHeads = { "Task No", "Data", "User ID", "Date Time",
                   "Description" };
         final Object[][] data = {
                   { "1", "50.00", "USER123", "12/10/2006 05:30", "Price Change" },
                   { "2", "100.00", "USER234", "15/10/2006 03:30", "Price Change12345"},
         final String[] colHeads1 = {"Detailed View" };
         final Object[][] data1 = {
                   { "Task:Price Change", "\n"," Old Price:50.00"," \n ","New Price:100.00"," \n" }
         JTable jtblTimeEntry = new JTable(data, colHeads);
         JTable jTbl1 = new JTable(data1,colHeads1);
         ComponentsBox jpBoxButton = new ComponentsBox(LayoutConstants.X_AXIS);
         public ElectronicJournal() {
              super();
              jtblTimeEntry.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              if (ALLOW_ROW_SELECTION) { // true by default
    ListSelectionModel rowSM = jtblTimeEntry.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow
    + " is now selected.");
    textArea.append("asd \n 123 \n");
    } else {
         jtblTimeEntry.setRowSelectionAllowed(false);
              if (DEBUG) {
                   jtblTimeEntry.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
         printDebugData(jtblTimeEntry);
              initialize();
         private void printDebugData(JTable table) {
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();
    System.out.println("Value of data: ");
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + model.getValueAt(i, j));
    System.out.println();
    System.out.println("--------------------------");
         private void initialize() {
              this.setSize(680, 200);
              this.setBackground(java.awt.SystemColor.control);
              jBtnExporttoExcel.setBackground(SystemColor.control);
              ComponentsBox cmpRibbonHORZ = new ComponentsBox(LayoutConstants.X_AXIS);
              cmpRibbonHORZ.addComponent(jBtnExporttoExcel, false);
              jpBoxButton.add(cmpRibbonHORZ);
              this.addFilledComponent(jGPanel, 1, 1, 1, 1, GridBagConstraints.BOTH);
              this.addFilledComponent(jGPanel1, 2, 1, 11, 5, GridBagConstraints.BOTH);
              this.addFilledComponent(jGPanel2, 2, 13, 17, 5, GridBagConstraints.BOTH);
              jGPanel.setSize(650, 91);
              jGPanel.setBackground(SystemColor.control);
              jGPanel.addFilledComponent(jLblTillNo,1,1,GridBagConstraints.WEST);
              jGPanel.addFilledComponent(jLblTillNoData,1,10,GridBagConstraints.BOTH);
              jGPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0));
              jGPanel1.setBackground(SystemColor.control);
              jGPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0,
                        0));
              spTimeEntryView.setViewportView(jtblTimeEntry);
              jGPanel1.addFilledComponent(spTimeEntryView, 1, 1, 11, 4,
                        GridBagConstraints.BOTH);
              jGPanel2.addFilledComponent(jLblData,1,1,GridBagConstraints.WEST);
              jGPanel2.setBackground(SystemColor.control);
              jGPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0,
                        0));
              //textArea.setText(html);
              pan.setViewportView(textArea);
         int selectedRow = jTbl1.getSelectedRow();
              System.out.println("selectedRow ::" +selectedRow);
              int colCount = jTbl1.getColumnCount();
              System.out.println("colCount ::" +colCount);
              StringBuffer buf = new StringBuffer();
              System.out.println("Out Of For");
              /*for(int count =0;count<colCount;count++)
              {System.out.println("Inside For");
              buf.append(jTbl1.getValueAt(selectedRow,count));
              // method 1 : Constructs a new text area with the specified text. 
              textArea  =new JTextArea(buf.toString());
              //method 2 :To Append the given string to the text area's current text.   
             textArea.append(buf.toString());
              jGPanel2.addFilledComponent(pan,2,1,5,5,GridBagConstraints.BOTH);
              this.addAnchoredComponent(jpBoxButton, 7, 5, 11, 5,
                        GridBagConstraints.CENTER);
    This code displays the same data on the JTextArea everytime i select each row,but my requirement is ,it has to refresh and display different datas in the JTextArea accordingly,as i select each row.Please help.Its urgent.
    Message was edited by: Samyuktha
    Samyuktha

    Please help.Its urgentThen why didn't you use the formatting tags to make it easier for use to read the code?
    Because of the above I didn't take a close look at your code, but i would suggest you should be using a ListSelectionListener to be notified when a row is selected, then you just populate the text area.

  • Updating JTable Contents

    I'm having trouble refreshing a JTable after changing it's 2D Object array data. Perhaps this is a stupid question, but any advice would be appreciated.
    Basically I've been building from the SimpleTableDemo.java file in the "How to Use Tables" tutorial. I set Object[][] data to a 2D Object array that is modified by other parts of my program.
    I added the public void tableChanged(TableModelEvent e) function to detect data changes, displaying a simple System.out, but it never seems to get called.
    Is there any way that the JTable can observe changes in the Object[][] data array and update it's self accordingly? I'm never sure if rows are being added or removed.
    I hope that made sense, and thank-you in advance to anyone who replies.
    -Arthur

    Couple of things...
    Whenever you change the contents of your TableModel you need to fire the appropriate event to get the JTable to update the viewed rows... in your case it sounds like you would have to call the "fireTableDataChanged()" method defined by AbstractTableModel so that your contents will be viewed.
    Also... it is rare that you really need to update the entire contents of your table model, most the time it is more efficient to just update the cell or row your need and call the appropriate "fire..." method to update
    Hope this helps
    Josh Castagno
    http://www.jdc-software.com

  • Refreshing JTable remotely or in another computer

    I have search the forums but i could not find the appropriate answer for my problem.
    I created a jtable with two buttons to add and delete row. This jtable and the mysql table which is the source of the data in the jtable, can be accessed by any computer on which the java program activating it, is installed. So it is possible that there could be several instances of the jtable running at the same time.
    On the computer where the add or delete button is activated, the mysql table and the jtable is updated/refreshed accordingly. There is no problem at all.
    However in the other computers where the instances of the jtable is running, the jtable is not refreshed at all. I can only refresh the jtable if I exit and restart the program.
    How can i refresh all the instances of the jtable everytime its contents are changed by any one of the computers running it?
    I have experimented using table.repaint, table.setUI, model.repaint to no avail.
    I wonder if I have to use RMI for this. Any help is very much appreciated as I have been wrestling with this problem for sometime.

    This solution by camickr works! My only problem is that it will not activate the cellrenderers and the methods to customize the columns. Thank you camickr. I hope you can help me with the cellrenderers.
    These cellrenderers work well with the original table.
    Here is the code:
    JButton Button_Refresh1 = new JButton("Refresh");
    Button_Refresh1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    Object skedData[][] = getSchedule(); //returns data from database;
    DefaultTableModel updtskedModel = new DefaultTableModel() {
    public boolean isCellEditable(int row, int column) {
    if (column == 1) {
    return false;
    } else {
    return true;
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    updtskedModel.addColumn("Date");
    updtskedModel.addColumn("Patient Name");
    updtskedModel.addColumn("Status");
    updtskedModel.addColumn("PatientNo");
    updtskedModel.addColumn("SeqNo");
    for (int i = 0; i < skedData.length; i++) {
    if (skedData[0] != null) {
    updtskedModel.addRow(new Object[]{skedData[i][1], skedData[i][2], skedData[i][3], skedData[i][0], skedData[i][4]});
    TableColumn col1 = skedTable.getColumn("Date");
    TableColumn col2 = skedTable.getColumn("Patient Name");
    TableColumn col3 = skedTable.getColumn("Status");
    TableColumn col4 = skedTable.getColumn("SeqNo");
    col1.setPreferredWidth(75); //this does not work
    col1.setCellRenderer(new DateRenderer()); // this one does not work and there are no error messages also.
    col2.setPreferredWidth(100); //this does not work
    col3.setCellEditor(new DefaultCellEditor(StatusBox)); //this one does not work and there are no error messages also
    skedTable.setModel(updtskedModel);
    //elsewhere in the code, the following class was defined.
    static class DateRenderer extends DefaultTableCellRenderer {
    public DateRenderer() { super(); }
    public void setValue(Object value) {
    setText((value == null) ? "" : regdf.format(value)); //regdf is defined elsewhere using SimpleDateFormat.

  • Unable to refresh JComboBox Content

    Hi all,
    I have 2 JComboBoxx boxes on a jTable. They need to be dynamically updated. It works, but sometimes the combobox appears as a empty list even though it it has content. At that moment, the combobox will return to normal with a more mouse click on the list.
    I feel that there is sth. wrong with the refresh. I do the refresh with the following codes. Do you have any idea on this??
    jComboBox1.repaint();j>>ComboBox2.repaint();
    j>>Table.revalidate();
    j>>Table.repaint();
    Thanks,
    Eva

    Have you tried the fire methodes in Abstract/DefaultTableModel ?
    --> fireTableDataChanged()
    perhaps this could be a solution ?
    have fun
    grtz Kristof

  • Refresh jTable after inserting new data into the Database

    Hey all,
    I'm using Netbeans 6.5 to create a Desktop Application which is connected to a Java DB (Derby).
    The first simple steps were all very successfull:
    Create the jTable and bind it to the Database => everything works fine. When the application starts it correctly shows all data from the database.
    The problem starts when I try to insert new data to the database.
    For that reason I've created textfields and a button "Save". When I press the button it successfully inserts the data to the database but they are not displayed in the jTable (when the application starts they are all there, they are not updated at runtime) . I've tried table.invalidate() and table.repaint() but they just don't work.
    Any help will be GREATLY appreciated. But please have in mind that most of the code is Netbeans-generated and most of it not editable.
    Many thanks in advance.
    George

    Once again you are right my friend. I jumped to conclusion way too fast, when I shouldn't. (Give me a break, I've been busting my head with this well over a week). The response I saw when I did that was that indeed a line is added to the jTable. Because I falsly set the index of the object to be added to be second to last the row appeared on the table, what I didn't see at the time was that the last one disappeared. Hmm...
    A new adventure begins...
    So after a few hours of messing around with it here are my observations:
    1) It was not an observable list. When I add the new element with employeesList.add(newEmp); , the table gets notified but a get a bunch of exceptions:
    xception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 84, Size: 84
            at java.util.ArrayList.RangeCheck(ArrayList.java:546)
            at java.util.ArrayList.get(ArrayList.java:321)
            at org.jdesktop.swingbinding.impl.ListBindingManager$ColumnDescriptionManager.validateBinding(ListBindingManager.java:191)
            at org.jdesktop.swingbinding.impl.ListBindingManager.valueAt(ListBindingManager.java:99)
            at org.jdesktop.swingbinding.JTableBinding$BindingTableModel.getValueAt(JTableBinding.java:713)
            at javax.swing.JTable.getValueAt(JTable.java:1903)
            at javax.swing.JTable.prepareRenderer(JTable.java:3911)
            at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2072)
            at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1974)
            at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1897)
            at javax.swing.plaf.ComponentUI.update(ComponentUI.java:154)
            at javax.swing.JComponent.paintComponent(JComponent.java:743)
            at javax.swing.JComponent.paint(JComponent.java:1006)
            at javax.swing.JViewport.blitDoubleBuffered(JViewport.java:1602)
            at javax.swing.JViewport.windowBlitPaint(JViewport.java:1568)
            at javax.swing.JViewport.setViewPosition(JViewport.java:1098)
            at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.vsbStateChanged(BasicScrollPaneUI.java:818)
            at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.stateChanged(BasicScrollPaneUI.java:807)
            at javax.swing.DefaultBoundedRangeModel.fireStateChanged(DefaultBoundedRangeModel.java:348)
            at javax.swing.DefaultBoundedRangeModel.setRangeProperties(DefaultBoundedRangeModel.java:285)
            at javax.swing.DefaultBoundedRangeModel.setValue(DefaultBoundedRangeModel.java:151)
            at javax.swing.JScrollBar.setValue(JScrollBar.java:441)
            at javax.swing.plaf.basic.BasicScrollBarUI.scrollByUnits(BasicScrollBarUI.java:907)
            at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.mouseWheelMoved(BasicScrollPaneUI.java:778)
            at javax.swing.plaf.basic.BasicScrollPaneUI$MouseWheelHandler.mouseWheelMoved(BasicScrollPaneUI.java:449)
            at apple.laf.CUIAquaScrollPane$XYMouseWheelHandler.mouseWheelMoved(CUIAquaScrollPane.java:38)
            at java.awt.Component.processMouseWheelEvent(Component.java:5690)
            at java.awt.Component.processEvent(Component.java:5374)
            at java.awt.Container.processEvent(Container.java:2010)
            at java.awt.Component.dispatchEventImpl(Component.java:4068)
            at java.awt.Container.dispatchEventImpl(Container.java:2068)
            at java.awt.Component.dispatchMouseWheelToAncestor(Component.java:4211)
            at java.awt.Component.dispatchEventImpl(Component.java:3955)
            at java.awt.Container.dispatchEventImpl(Container.java:2068)
            at java.awt.Component.dispatchEvent(Component.java:3903)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4256)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3965)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3866)
            at java.awt.Container.dispatchEventImpl(Container.java:2054)
            at java.awt.Window.dispatchEventImpl(Window.java:1801)
            at java.awt.Component.dispatchEvent(Component.java:3903)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:269)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:184)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:176)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 84, Size: 84
            at java.util.ArrayList.RangeCheck(ArrayList.java:546)
            at java.util.ArrayList.get(ArrayList.java:321)
            at org.jdesktop.swingbinding.impl.ListBindingManager$ColumnDescriptionManager.validateBinding(ListBindingManager.java:191)
            at org.jdesktop.swingbinding.impl.ListBindingManager.valueAt(ListBindingManager.java:99)
            at org.jdesktop.swingbinding.JTableBinding$BindingTableModel.getValueAt(JTableBinding.java:713)
            at javax.swing.JTable.getValueAt(JTable.java:1903)
            at javax.swing.JTable.prepareRenderer(JTable.java:3911)
            at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2072)
    ... and a lot morewhich from my poor understanding means that the jTable succesfully notices the change but it is not able (??) to adjust to the new change. What is more interesting is that when I plainly add the element to the end of the list (without an idex that is), a blank row appears at the end of my Table. The weird thing is that I've bound the table to some text fields below it, and when I select that empty row all the data appear correctly to the text fields.
    I tried going through:
                    org.jdesktop.observablecollections.ObservableCollections.observableList(employeesList).add(newEmp);as well as
                    help = org.jdesktop.observablecollections.ObservableCollections.observableListHelper(employeesList);
                    help.getObservableList().add(newEmp);
                    help.fireElementChanged(employeesList.lastIndexOf(newEmp));and
                    obsemployeesList = org.jdesktop.observablecollections.ObservableCollections.observableList(employeesList);
                    obsemployeesList.add(newEmp);and I still get the same results (both the exeptions and the mysterious empty row at the end of the table
    So, I'm again in terrible need of your advice. I can't thank you enough for the effort you put into this.
    Best regards,
    George
    Edited by: tougeo on May 30, 2009 11:06 AM
    Edited by: tougeo on May 30, 2009 11:21 AM
    Edited by: tougeo on May 30, 2009 11:30 AM

Maybe you are looking for

  • Can't see ipod in itunes or my computer

    HELP.Tried all recomended fixes in help forum. Background: power outage while ipod connected to PC. ipod frooze. Have reset ipod and ipod works, however when connecting to pc it is not visible in my computer or itunes. Have deleted itunes (V8) as rec

  • Problem with non modal ADM dialog

    I have problem with focus and mouse and keyboard event passing to non modal dialog if some modal window was opened and closed on Windows platform. I have this problem in my plugin, but also I did some tests with SDK WordFinder Plugin.There are 2 dial

  • IDVD crash in middle of creation

    I have a project created in imovie that got transferred to idvd. It is a fairly big movie so I opted to burn a double layer disc. After the audio is encoded (which takes quite a long time), it prepares to burn the disc, then ejects the disc before an

  • Photo date help.

    Hello. I did do a search and found some info on this, but that info was a few years old so i thought id touch base again. When i upload pics from my camera to i-photo the dates and times the pictures were taken is in the info of each pic. However, wh

  • Hi all, i need Help in Arrays

    Hi All, I have some problems on the below questions scenario; Program 1 You are to write a program using a method other than main. The program is to �     collect monthly rainfall figures for 12 months �     pass the total annual rainfall to another