How to write contents of  an ArrayList to JTable

I have an ArrayList named 'innercell'. It contains the following contents
cs123, 0.34567
cs234, 0.5673
cs234,cs456, 0.5674
this arraylist is added to another arraylist 'cells'
cells.add(innercell);
now the contents of the 'cells' arraylist is
cs123, 0.34567
cs234, 0.5673
cs234,cs456, 0.5674
i have created a JTable and its variable name is 'jtable' (object) (*i'm using NetBeans IDE 6.0*)
and the model of this JTable is as below (it is the generated code by NetBeans IDE 6.0)
jtable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null},
{null, null},
{null, null},
{null, null},
{null, null},
{null, null},
{null, null},
{null, null},
{null, null}
new String [] {
"Title 1", "Title 2"
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
i have only 2 columns in the table, and 9 rows
now i want 2 place contents of 'cells' arraylist to JTable as below
Tittle 1 Title 2
cs123 0.34567
cs234 0.5673
cs234,cs456 0.5674
to write in this form i'm using following code
String[] columnNames={"Title 1","Title 2"};
Object[][] rowdata=new Object[9][2];
str=items;//items is the string value.the possible 'items' values {cs123,...}
sup=value;//value is the double value. the possible 'value' are {0.5674,......}.i'm not given how i'm geting these values
for(int k=0;k<2;k++){
if(k==0)
rowdata[i][k]=str;
else
rowdata[i][k]=sup;
jtable=new JTable(rowdata,columnNames);//is this statement is right to add the contents of arraylist to the table?
jtable.setVisible(true);
but it is not working....i'm getting "NullPointerException"

Swing related questions should be posted in the Swing forum.
Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.
Don't use an IDE to generate your code. Learn how to write your own code. Its hard enough to learn how to use Java without learning how to use the IDE as well.
Use the DefaultTableModel. You can build the model using Vectors or Arrays or by adding individuals rows of data to the model. There is no need to create a custom TableModel.

Similar Messages

  • How to add contents of an arrayList to a JList

    Hi,
    I am trying to figure out how to add the contents of an arraylist to a Jlist.
    Basically I have 3 classes which are as follow:
    1. AuctionItems(String name, int bid) which represents an item in auction
    2. AuctionItemsFactory which creates AuctionItems and adds them to an arraylist called stock
    3. AuctionBidsGui1 which is the interface where the user can see the items in the auction and select them from a JList.
    But I dont know how to read the contents of the stock(arraylist) into the JList which is in AuctionBidsGui1. Below are the 3 classes mentioned above
    public class AuctionItems {
         String name;
         int bid;
         public AuctionItems(){
              name = null;
              bid = 0;
         public AuctionItems(String name, int bid){
              this.name = name;
              this.bid = bid;
         public String getName(){
              return name;
         public int getBid() {
              return bid;
    public class AuctionItemsFactory {
         private ArrayList<AuctionItems> stock;
         int size;
         public AuctionItemsFactory() {
              stock = new ArrayList<AuctionItems>();
         public void addItems(AuctionItems item) {
              stock.add(item);
    //removes last element of the arrayList
         public void removeItems() {
              int n = stock.size() - 1;
              stock.remove(n);
         public void printNumOfItems() {
              int n = stock.size();
              System.out.println(n);
         public int numberOfItems(){
              return stock.size();
         public void printItems(){
              for (AuctionItems item : stock) System.out.println(item);
    and this one is a small part of the AuctionBidsGui1 class which represents the JList where the list of the items will go.
    public void addItemListWidgets() {
              itemsList = new JList();
              itemsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
              itemsList.setLayoutOrientation(JList.VERTICAL);
              itemsList.setVisibleRowCount(10);
              itemsList.setSelectedIndex(0);
              JScrollPane itemsListScroller = new JScrollPane(itemsList); // put the list in the scroller
              itemsListScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
              itemsListScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
              itemsListPanel.add(itemsListScroller);
         }

    I know that I have to use the toArray() but i dont know what type of method to use for this because i will need to implement a method in my AuctionItemsFactory class which will copy the contents of the arraylist into an array so then i can call this methos from my AuctionBidGui1 class.
    I would appreciate if you could give me a bit more hints.

  • How to write content of the file under folder

    Hi Experts,
    I have following scenario, I have list of files under folder in local desktop(for eg D:\mani)
    I have only filename, using this filename i want to search and get content of the particular file and write in some other location? how to do that? give your suggestions?
    Regards,
    P.Manivannan

    You could go two ways here:
    The first possibility requires that (a) you know what operating system you are working with, and (b) you only need to copy the file, and not do anything else with the contents of it. In this case, probably the easiest way to do this is to use a Runtime exec command for the file you want to copy:
    java.lang.Runtime.getRuntime().exec( "cp D:\mani D:\mani2" );Otherwise, if you need your code to be portable, you can't assume anything about the operating system. Since java.io.File doesn't provide a copy method, you will need to read the entire contents of the file into the vm, and then write them out to a new file. Also, if you need to use the contents of your file in some other way, as well, then you also need to read the entire contents into the vm. In this second case, how you read the file may depend on what kind of data the file contains.
    In general, the following code should work for you:
    final FileInputSteam  fis = new FileInputStream ( new File( "D:\mani"  ) );
    final FileOutputStream fos = new FileOutputStream( new File( "D:\mani2" ) );
    final byte [] buf = new byte[ 1024 ];
    int bytesRead;
    while ( ( bytesRead = fis.read( buf ) ) != 0 )
        fos.write( buf, 0, bytesRead );Don't forget to catch or throw IOException.
    Hope this helps.
    - Adam

  • How to write contents of one file to another file

    We have some file Recon80 (RECON80HB01141005.TXT) which need to be modified . i.e we need to add 2 more columns in the file and write the file record into other file with trailer information. Please suggest to accomplish along with code snippet in SSIS 2008.
    PFA

    Easiest way is to use script task to add header and footer information. 
    http://agilebi.com/jwelch/2008/02/08/adding-headers-and-footers-to-flat-files/
    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • 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

  • I am new in indesign scripting, please tell me how to write a script to get  content of a element in xml and then sort all the content

    I am new in indesign scripting, please tell me how to write a script to get  content of a element in xml and then sort all the content

    Hi,
    May the below code is useful for you, but I dont know how to sort.
    Edit the tag as per your job request.
    alert(app.activeDocument.xmlElements[0].contents)
    //Second alert
    var xe = app.activeDocument.xmlElements[0].evaluateXPathExpression("//marginalnote");
    alert(xe.length)
    for(i=0; i<xe.length; i++)
        alert(xe[i].texts[0].contents)
    Regards
    Siraj

  • How to write program to list the system directory(content of pc)

    how to write a program that will display all the folder n directory of the pc like:
    +My Computer
    +c:
    +d:                                                                                                                                                                                                                                       

    Copy this line and save it in a file named "dirlist.bat":
    for %%* in (%1) do dir /b %2 %1To use it, change to the directory it's in and at the command prompt type
    dirlist directory [/s] directory is the name of the directory that you want listed.
    /s is optional and will list the contents of all subdirectories also.
    (You didn't say it had to be Java - use the right tool for the job)

  • How to write an element in a  JTable Cell

    Probably it's a stupid question but I have this problem:
    I have a the necessity to build a JTable in which, when I edit a cell and I push a keyboard button, a new Frame opens to edit the content of the cell.
    But the problem is how to write something in the JTable cell, before setting its model. Because, I know, setCellAT() method of JTree inserts the value in the model and not in the table view. And repainting doesn't function!
    What to do??
    Thanks

    Hi there
    Depending on your table model you should normally change the "cell value" of the tablemodel.
    This could look like:
    JTable table = new JTable();
    TableModel model = table.getModel();
    int rowIndex = 0, columnIndex = 0;
    model.setValueAt("This is a test", rowIndex, columnIndex);
    The tablemodel should then fire an event to the view (i.e. JTable) and the table should be updated.
    Hope this helps you

  • How to write the folder path in standard webi report - Most Accessed Documents

    How to write the folder path in standard webi report - Most Accessed Documents
    All
       -> Public Folders
                      -> Auditor
                      -> ABCD
    I want to give path of folder 'ABCD' and all the reports/ subfolders under it?
    Prompt - 'Enter the Folder Path(Add % at the end to include Sub Folders)' ?
    Give me exact path syntax

    Hi Daniel,
    But when I give my URL as
    http://serverA:80/irj/portal??NavigationTarget=ROLES://portal_content/crm-practice/14-Feb/Test_Page
    I am able to access the iview but the thing is I am getting TLN,Toolarea,Masthead,etc.
    I will tell my requirement,
    ServerA (EP 7.0) has some iviews,pages...
    I need to access these iviews from serverB(EP 6.0)....
    In ServerB only the iviews has to be displayed in the content area but not TLN,Toolarea,etc.
    Kindly help me in this regard.
    Thanks and regards,
    Purushothaman.
    Message was edited by: Purushothaman Vyasarao

  • How to write Sync service in ABAP

    Dear Experts,
                  i m very new to ABAP dev, can anybody help me how to write a sync service in ABAP and how to call a function module in to that sync service.
                   My requirement is i want to upload the data from the clint and download the data to client from the backend. i had written the function module to create a customer in CRM, now i want to push the data to create a customer from the client, for this i need to write a sync service for above requirement,
                plz help me out how to write a sync service.
                           Regards
                            eswar

    Hi Jyotirmoy,
    Check this thread for Subquery
    http://help.sap.com/saphelp_nw04/helpdata/en/dc/dc7614099b11d295320000e8353423/content.htm
    Correlated, non-scalar subquery:
    REPORT demo_select_subquery_1.
    DATA: name_tab TYPE TABLE OF scarr-carrname,
          name  LIKE LINE OF name_tab.
    SELECT  carrname
      INTO  TABLE name_tab
      FROM  scarr
      WHERE EXISTS ( select  *
                       FROM  spfli
                       WHERE carrid   =  scarr~carrid AND
                             cityfrom = 'NEW YORK'        ).
    LOOP AT name_tab INTO name.
      WRITE: / name.
    ENDLOOP.
    This example selects all lines from database table SCARR for airlines that fly from New York.
    Scalar subquery:
    REPORT demo_select_subquery_2.
    DATA: carr_id TYPE spfli-carrid VALUE 'LH',
          conn_id TYPE spfli-connid VALUE '0400'.
    DATA: city  TYPE sgeocity-city,
          lati  TYPE p DECIMALS 2,
          longi TYPE p DECIMALS 2.
    SELECT  SINGLE city latitude longitude
      INTO  (city, lati, longi)
      FROM  sgeocity
      WHERE city IN ( select  cityfrom
                        FROM  spfli
                        WHERE carrid = carr_id AND
                              connid = conn_id      ).
    WRITE: city, lati, longi.
    This example reads the latitude and longitude of the departure city of flight LH 402 from database table SGEOCITY.
    Thanks,
    Vinay

  • How to write Protect endprotect concept in Smartforms

    hi
    can any one suggest me
    How to write Protect endprotect concept in Smartforms
    i have some content to coem without break in SMARTFORM
    how to do that
    Thanks & Regards
    kalyan
    <thread moved, has nothing to do with ABAP Objects. Please choose your forums more carefully in future>
    Edited by: Mike Pokraka on Sep 26, 2008 12:50 AM

    Hi,
    For 4.7 version if you are using tables, there are two options for protection against line break: 
    - You can protect a line type against page break.
    - You can protect several table lines against page break for output in the main area.
    Protection against page break for line types 
    - Double-click on your table node and choose the Table tab page. 
    - Switch to the detail view by choosing the Details pushbutton. 
    - Set the Protection against page break checkbox in the table for the relevant line type.  Table lines that use this line type are output on one page. 
    Protection against page break for several table lines 
    - Expand the main area of your table node in the navigation tree. 
    - Insert a file node for the table lines to be protected in the main area. 
    - If you have already created table lines in the main area, you can put the lines that you want to protect again page break under the file using Drag&Drop. Otherwise, create the table lines as subnodes of the file. 
    - Choose the Output Options tab page of the file node and set the Page Protection option.   All table lines that are in the file with the Page Protection option set are output on one page. 
    In 4.6, Alternatively in a paragraph format use the Page protection attribute to determine whether or not to display a paragraph completely on one page. Mark it if you want to avoid that a paragraph is split up by a page break. If on the current page (only in the main window) there is not enough space left for the paragraph, the entire paragraph appears on the next page. 
    Regards,
    Himanshu Verma

  • How to write a file using mod pl/sql

    hi,
    i am having a submit button in my procedure. which should inturn create .sql file in a file path.
    is there any way to create a fileusing htp and htf methods.
    Thanks in advance
    Hari

    >
    i am having a submit button in my procedure. which should in turn create .sql file in a file path.
    is there any way to create a file using htp and htf methods.
    >
    Why are you wasting your time coding from scratch using the PL/SQL Web Toolkit instead of the APEX framework?
    From Re: how to write a file using mod pl/sql it appears that you are not using APEX, so a number of the approaches APEX offers are not relevant. You appear to be looking for a file download solution using the <tt>wpg_docload.download_file</tt> method, such as:
    create or replace procedure download_file (
        p_filename  in     varchar2
      , p_mimetype  in     varchar2
      , p_content   in out nocopy blob)
    is
    begin
      -- Set up HTTP header.
      -- Use "application/octet" as default MIME type.
      owa_util.mime_header(nvl(p_mimetype, 'application/octet'), false);
      -- Set the size so the browser knows how much to download.
      htp.p('Content-length: ' || dbms_lob.getlength(p_content));
      -- Filename will be used as default by the browser in "Save as..."
      htp.p('Content-Disposition: attachment; filename="' || p_filename || '"');
      -- Close header.
      owa_util.http_header_close();
      -- Stream the file content to the browser.
      wpg_docload.download_file(p_content);
    end download_file;

  • How to write data to existing file using spool command?

    Hi,
    I am calling a stored procedure from a shell script. This stored procedure is having a CLOB object as an OUT parameter. How to write the data in CLOB object a existing file which is there in my client system. Below is the shell and sql scripts.
    Shell script
    ( echo "hello" ) > /root/file.txt
    sqlplus -s $user/$pass@$tns @/root/proc.sql /root/file.txt << EOF
    EOFSQL script
    set pages 0
    set trimspool off
    set serveroutput off
    set feedback off
    set term off
    set echo off
    variable out CLOB
    define file='&1'
    begin
    pack.proc(:out);
    end;
    spool &file
    select :out from dual;
    spool offThis code writes contents of the OUT variable to file.txt, but my existing data ('hello') is lost. Please help me.
    I figured the it...Use append in the spool command... :)
    Edited by: Balaji on Jul 19, 2012 8:55 PM

    >
    Hi Balaji
    I figured the it...Use append in the spool command... :Please mark the thread as answered as per the FAQ.
    Paul...

  • OSM7 how to write the xq in Order State Policy

    In Order State Policy I set for
         state:In Progress Order State
         request: Cancel Order     
    a xq code in the Condition Transiction form, which check a xml field and return true or false base on the content, but it does not works.
    Now, can I log the input of Order State Policy and how can I debug the xq?
    Please helpme to undestund how to write and debug the xq code?
    below my xq:
    declare namespace saxon="http://saxon.sf.net/";
    declare namespace xsl="http://www.w3.org/1999/XSL/Transform";
    let $taskData := fn:root(.)/GetOrder.Response
    let $ponr := $taskData/_root/PONR
    let $ponr_value := fn:normalize-space( $ponr/text() )
    return
    if (fn:exists($taskData) )
    then (
    if ("NO" = $ponr_value) then (
    true()
    else (
    false()
    else(
         false()
    input example:
    <GetOrder.Response>
    <_root
    <PONR>NO</PONR>

    So, I can debug the xq adding the line below step by step...
    fn:trace($taskData, "label")
    Below my final xq that I put on the policy.
    declare namespace saxon="http://saxon.sf.net/";
    declare namespace xsl="http://www.w3.org/1999/XSL/Transform";
    let $taskData := fn:root(.)/GetOrder.Response
    let $ponr := $taskData/_root/PONR
    let $ponr_value := fn:normalize-space( $ponr/text() )
    return
    if (fn:exists($taskData) )
    then (
    if ( $ponr_value = "NO" ) then (
    true()
    else (
              fn:error(fn:QName("urn:com:metasolv:oms:xmlapi:1", "PointOfNoReturn"), "PONR reached.")
    else(
         fn:error(fn:QName("urn:com:metasolv:oms:xmlapi:1", "PointOfNoReturn"), "PONR reached taskData does not exist.")
    )

  • How to write comments for a class

    hi
    how to write comments for a class

    I'm reeling with incredulity, and as such am unable to do anything except just post some code
    // this is a single line comment
    /* this is a multiline comment.
        it can be spread over as many lines as you
        want */Or are you asking about how to decide what the content should be?

Maybe you are looking for

  • How to tell if a user has logged in to teststand

    I am using a custom LV UI. I would like to know if there is a way to tell if the user has clicked the cancel button on the standard TS login. I would like to keep using the standard TS login if possible. Thanks Joe. "NOTHING IS EVER EASY"

  • RFC lookup Vs Database lookup

    Dear experts, When it comes to PI mappings which one is resource or time intensive between RFC lookup Vs Database lookup where the table is hosted in PI itself.  I really looking for this comparision in PI 7.1.  If anybody looked to compare the pros

  • PS CS6 - What happened to Page Setup?

    Please help - I'm about to bang my head on the desk in complete frustration, and it shouldn't be this difficult!! What happened to Page setup in CS6?  I'm trying to print a document with canvas size 11x17.  When I try to print, the media box is liste

  • HT5463 I turned on "Do not disturb" mode on my iPhone4 but it didn't work. Pls kindly advise.

    I turned on "Do not disturb" mode on my iPhone4 but it didn't work. Pls kindly advise.

  • Iphone 4 Apple store

    Hello, i  want to buy Iphone 4 for 99 $ ,is that whole prices of mobile phone?  Do i need to pay more later ? Im from Croatia so here is cheaper so i planning to order