Adding to an ArrayList

I have been staring at this for 2 days now, and finally decided to ask the experts.
I have a method of a class that should fetch records from a (textual) database en return an ArrayList with all the records. Each record in turn should contain all the (4) fields.
Well, it pretty much all works fine, except for the fact that the line 'dbRecs.add(rec)' overwrites ALL ArrayList elements with the new record, instead of just the last. That is, I presume this is the case, since this is what a spying-loop showing the content af all the entries of the ArrayList (not included in the code, but added right after the wretched line) tells me.
The code shows the method, and the class of the records with the fields.
Any enlightenment on what the ... is wrong would be greatly appreciated.
public ArrayList getDbRecords() {
          ArrayList dbRecs;
          String dbLine;
          String[] splitstring;
          dbRecs = new ArrayList(15);
          DbRecord rec;
          BufferedReader in;
          try {
               FileInputStream fstream = new FileInputStream(SystemVars.dbFileName); // Open the file
               in = new BufferedReader(new InputStreamReader(fstream));
               rec = new DbRecord();
               int i = 0;
               while ((dbLine = in.readLine()) != null) { // Continue to read lines until eof
                    i++;
                    splitstring = dbLine.split("\"");
                    rec.proverb     = splitstring[1];
                    rec.nl = splitstring[3];
                    rec.transl = splitstring[5];
                    rec.extra = splitstring[7];
                    dbRecs.add(rec); //add record to ArrayList
               } //end 'while'
               in.close();
     catch (Exception e) {
               System.err.println("File input error");
          dbRecs.trimToSize();
          return(dbRecs);
class DbRecord {
     String proverb,nl,transl,extra;
}

               rec = new DbRecord();
               int i = 0;
while ((dbLine = in.readLine()) != null) { //
// Continue to read lines until eof
                    i++;
                    splitstring = dbLine.split("\"");
                    rec.proverb     = splitstring[1];
                    rec.nl = splitstring[3];
                    rec.transl = splitstring[5];
                    rec.extra = splitstring[7];
dbRecs.add(rec); //add
/add record to ArrayList
} //end
end 'while'This is a real conceptual error. You are initialising the object outside the while loop and adding it to the list inside the loop. Everytime you reference the same object and the arraylist does nothing more than storing the references to them.
The solution is to initialise the object each time in the loop, so that every object in the arraylist would refer to a different object.
Another thing that I noticed is that the code is rather sloppy. You seem to have bypassed the concept of encapsulation totally... which defeats the very purpose of OOP. Make the member variables private and use getter/setter methods to access them.
Phew!
***Annie***

Similar Messages

  • Values added into arraylist are override with the last value

    Hi,
    I am running a very simple java program.
    Here is the sample program.
    CustProfAccountFid fid = new CustProfAccountFid();
    for(int i=0;i<cp104Result.size();i++ ){
    Hashtable cp104ht = (Hashtable)cp104Result.get(i);
    fid.setFidSeqNumber((String)cp104ht.get("x"));
    fid.setFidType((String)cp104ht.get("z"));
    fid.setFidName((String)cp104ht.get("c"));
    fid.setFidText((String)cp104ht.get("v"));
    custProfAccountFidList.add(fid);
    Here cp104Result and custProfAccountFidList, both are arraylist.
    I want to get all the values added to the arraylist.But the problem is when loop continues the arraylist values get
    override by the last value.
    As a result i get 5 or 6 same values in the arraylist.
    Please help me out for the solution.
    Thanks in advance.

    for(int i=0;i<cp104Result.size();i++ ){
        CustProfAccountFid fid = new CustProfAccountFid();
        Hashtable cp104ht = (Hashtable)cp104Result.get(i);
        fid.setFidSeqNumber((String)cp104ht.get("x"));
        fid.setFidType((String)cp104ht.get("z"));
        fid.setFidName((String)cp104ht.get("c"));
        fid.setFidText((String)cp104ht.get("v"));
        custProfAccountFidList.add(fid);
    }

  • Novice question: ArrayList error

    Two classes: Bank and Customer.
    Customer class has this constructor:
    public class Customer {
    protected String cust_name;
    protected int card_number;
    protected double current_bal;
    protected double credit_limit;
    public Customer(String ID, int CCN, double balance, double limit) {
    cust_name = ID;
    card_number =  CCN;
    current_bal = balance;
    credit_limit = limit;
    }Bank class has an ArrayList of Customer objects.
    import java.util.ArrayList;
    public class Bank extends Customer
    ArrayList<Customer> customers = new ArrayList<Customer>();
    /* here is the error on below line: compiler outputs "<identifier> expected"
    customers.add(new Customer("Nicholas Cage", 345, 225.0, 2600.0));Is it wanting an identifier in the add method? (i.e. customers.add(1, new Customer....)

    customer object being added to the arraylist is fine..u should have the customers.add() within a method...where you have that customers.add()?
    if its within a methed then just verify if the braces above are closed properly b'coz this error might come if the braces are not closed properly..

  • Checking for null value in arraylist

    Hi
    i have an excel file which i i am reading into an arraylist row by row but not necesarrily that all columns in the row mite be filled. So how do i check for null values in the array list.
    try
                        int cellCount = 0;
                        int emptyRow = 0;
                        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
                        HSSFSheet sheet = workbook.getSheetAt(0);
                        Iterator rows = sheet.rowIterator(); 
                        myRow = new ArrayList();
                        int r = 1;
                             while (rows.hasNext())
                                  System.out.println("Row # " + r);
                                  HSSFRow row = (HSSFRow) rows.next();
                                  Iterator cells = row.cellIterator();          
                                  cellCount = 0;
                                  boolean isValid = false;
                                  while (cells.hasNext())
                                       HSSFCell cell = (HSSFCell) cells.next();
                                       switch (cell.getCellType())
                                            case HSSFCell.CELL_TYPE_NUMERIC:
                                                 double num = cell.getNumericCellValue();     
                                                 DecimalFormat pattern = new DecimalFormat("###,###,###,###");     
                                                 NumberFormat testNumberFormat = NumberFormat.getNumberInstance();
                                                 String mob = testNumberFormat.format(num);               
                                                 Number n = null;
                                                 try
                                                      n = pattern.parse(mob);
                                                 catch ( ParseException e )
                                                      e.printStackTrace();
                                                 System.out.println(n);
                                                 myRow.add(n);                                             
                                                 //myRow.add(String.valueOf(cell.getNumericCellValue()).trim());
                                                 //System.out.println("numeric: " +cell.getNumericCellValue());
                                                 break;
                                            case HSSFCell.CELL_TYPE_STRING:
                                                 myRow.add(cell.getStringCellValue().trim());
                                                 System.out.println("string: " + cell.getStringCellValue().trim());
                                                 break;
                                            case HSSFCell.CELL_TYPE_BLANK:
                                                 myRow.add(" ");
                                                 System.out.println("add empty:");
                                                 break;
                                       } // end switch
                                       cellCount++;
                                  } // end while                    
                                  r++;
                             }// end while
                   } myRow is the arrayList i am adding the cells of the excel file to. I have checked for blank spaces in my coding so please help with how to check for the black spaces that has been added to my arraylist.
    I have tried checking by looping through the ArrayList and then checking for null values like this
    if(myRow.get(i)!=null)
      // do something
    // i have tried this also
    if(myRow.get(i)!="")
    //do something
    }Edited by: nb123 on Feb 3, 2008 11:23 PM

    From your post I see you are using a 3rd party package to access the Excel SpreadSheets, you will have to look in your API for you 3rd party package and see if there is a method that will identify a blank row, if there is and it does not work, then you have to take that problem up with them. I know this is a pain, but it is the price we pay for 3rd party object use.
    In the mean time, you can make a workaround by checking every column in your row and seeing if it is null, or perhaps even better: check and see if the trimmed value of each cell has a lenth of 0.

  • ArrayList concept

    Hi,
    I know how to add elements in ArrayList,
    My requirement is
    ArrayList al=new Arraylist();
    al.add(12);//this is my requirement i need code for these method can u able to send successful code.
    I know we can add like this
    al.add(new Float(12.090909));
    but I need add(12);

    ArrayList al=new Arraylist();
    al.add(12);//this is my requirement i need code for
    these method can u able to send successful code.If I am allowed to take this very literally, I can solve your problem. Declare a class Arraylist (with a lowercase l) that extends ArrayList (which has a capital L) and provide a method add(int). You're done.
    That was intended to be a joke!
    Seriously, either box your int into an Integer before adding to the ArrayList, or write your own int list class. The latter may or may not use ArrayList for implementation, either through inheritance or composition. Only, give it a descriptive name, list IntArrayList, for example.

  • Text files into Object ArrayList

    I have another class reading line-for-line text file, send each line to a class object and that class splits the line into fields. An ArrayList holds the objects. No problem.
    Then, an almost similar setup. This time, the file is clusters. A blank line separates the records. Here's the code:
    * DBKlass.java
    * from file.io
    * a text file with blocks of data
    * "records" are 3-10 lines of text separated by blank-line-return
    * all lines read into an Arraylist<Klass> klasList
    *  file.io also added the micron character to any blank lines
    * pass a loaded ArrayList which is a long line-for-line storage
    *  of my file I read in to a field formater DBKlass
    * to make Objects of type Klass
    package org.vcbrad.mainframe;
    import java.util.ArrayList;
    import javax.swing.JOptionPane;
    public class DBKlass {
        ArrayList<Klass> klasList;  
        public DBKlass( ArrayList<String> al ) {
            if( al != null && al.size() >= 1 )
                loadDB(  al  );
            else
                JOptionPane.showMessageDialog(MainFrame.desktop,"File not found");      
        private void loadDB( final ArrayList<String> al ) {
            String fldSep = "\u00B5"; // unicode = ? micron
            int alSize = al.size();
    klasList = new ArrayList<Klass>();
            for (int i = 0; i < alSize; i++) {
                if(al.get(i).equalsIgnoreCase(fldSep)) {
                    String temp = al.get(     i+1        ) + "]";
                    al.set(i+1,temp);
            String coursework = "";
            for (String s : al) {
                coursework += s;
            String[] courses = coursework.split(fldSep);
            for (int i = 0; i < courses.length; i++) {
                System.out.println(courses);
    klasList.add( new Klass( courses[i] ) );
    * System.out displays what I want
    * Ex: LPE17]Koordination Hauswirt-schaftlicher Arbetisprocesse.
    * pass that line to the new Klass( String rowrecord );
    * and then ...
    * Klass k = klasList.get(0) ... .get(1) ... .get(2) etc.
    * ALL objects from klasList
    * have the only the last record from my original text
    My question: Am I defeating ArrayList with my look-ahead feature? I realize ArrayList is not synchronized. Or, do I need to write out to a new file, read it again to make my objects???
    Message was edited by:
    vcbrad
    OK, after spending a lot of time with my original problem I went back and made a method call to the ArrayList<Klass> from outside this class. For whatever reason, jumping and/or manipulating the the internal Iterator of ArrayList won't let me make Objects. And, trying to manipulate Strings twice just makes the logic hard to untangle. So, it works now. Baffling because I have an identical class that does work line-for-line manipulating Strings before adding myObjects to ArrayList<myObject>

    First of all: Take a deep breath, and feel your feet... Don't panic, and do not cross-post or re-post with more exclamation marks just to get some attention!
    What kind of data are you going to process in your program? Probably images. Have a look at how images are handled in a Java program. How you read them, and how you display them. Then decide on the type of data you are going to keep in which data structure.
    Figure out what you want to do.
    Take a peak at some java example classes and programs.
    Perhaps have a look at the java.awt.Image class. Just an idea...
    Kind regards

  • Adding Objects to ArraysLists (BlueJ)

    Hi,
    Below, I have created a Book class that allows books to be created, loaned out returned and displayed.
    The next phase in this assignment is to create an ArrayList in a seperate abstract class called Library. To store the objects created in Book class. i.e. book1, book2 etc. These objects are to be added to this ArrayList.
    After that, the abstract Library class should hold a method that displays all books in the ArrayList followed by No of Books as integer value.
    Could anyone help?
    Thanks in advance.
    * Write a description of class Book here.
    * @author (Shah)
    * @version (28/01/2008)
    public class Book extends Library
        public String Author;
        public String Title;
        public String Media;
        public double Price;
        public boolean OnLoan;
        public String ShelfMark;
        public String Classification;
        public int BorrowerID;
        public String Library;
        /** Constructor for creating new object.instances (Books) */
        public Book(String author, String library, String title, String media, double price, String classification)
            /** Data input stored indirectly into instance variable*/
            Author=author;
            Title=title;
            setMedia(media);
            Price=price;
            setClassification(classification);
            Library=library;
        public void setClassification(String classification)
            Classification = classification; /** indirect access to instance variable */
            if(classification=="Fiction" || classification=="Non-fiction" || classification=="Factual" || classification=="Children" || classification=="Educational")
            { /** sets classification if one of the above are entered. */ }
            else
            {   /** Print error if one of the above is not entered. */
                System.out.println("Invalid Entry! Please Enter from the following:"); // Print Error Message
                System.out.println("Fiction, Non-Fiction, Factual, Children, Educational");
        public void setMedia(String media)
            Media = media;
            if(media=="Book" || media=="Tape" || media=="CD" )
                /** Sets Media, only from the above choices (Book, Tape, CD) */
            else
                System.out.println("You Entered Wrong Media Type! Please Enter from the following:");
                System.out.println("Book, Tape or CD.");
        public void setShelfMark()
            /** Sets the ShelfMark as "value of Classification + value of Author" */
            ShelfMark = this.Library + " " + this.Author;
        public void displayBook()
          /** call method - ShelfMark */
          setShelfMark();
          System.out.println(" ");
          /** Retrieve and Print details onto screen/canvas */
          System.out.println("Title: " + this.Title);
          System.out.println("Author: " + this.Author);
          System.out.println("Media: " + this.Media);
          System.out.println("Genre: " + this.Classification);
          System.out.println("ShelfMark: " + this.ShelfMark);
          System.out.println("On Loan?: " + this.OnLoan);
          System.out.println("Borrower ID: " + this.BorrowerID);
          System.out.println("Loan Price: " + this.Price);
        /** Require BorrowerID and Date for Loan */
        public void LoanOut(int borrowerID)
            /** If not already loaned, Loan book to requestee */
            if(OnLoan==false)
                BorrowerID=borrowerID;
                /** BorrowerID Range is set between 1-1000, value outside this range is not allowed */
                if (borrowerID<1 || borrowerID>1000)
                    System.out.println("Out of Range. BorrowerID must be between 1-1000");
                else
                    /**Book is now on Loan */
                    OnLoan = true;
                    /** Prints/Shows details of Book Loaned */
                    displayBook();
                    System.out.println("This book is now loaned out to you!");         
                else
                /**Ensures you cannot loan a book that is already loaned to you */
                System.out.println("This book is already Out On Loan!");
        public void ReturnBook()
                if(OnLoan==true)
                BorrowerID=0;
                OnLoan=false;
                displayBook();
                    System.out.println("This book has now been returned");
                else
                    System.out.println("This Book Has not been loaned out");  
    }

    TopDollar wrote:
    I checked, your code which is right, however, i still cant get it to work. i tried this:
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.*;
    public abstract class Library
    public static ArrayList BooksDB = new ArrayList();
    public Book search;
    public void Display()
         int index = 0;
    while(index < BooksDB.size()) {
    System.out.println(BooksDB.get(index));
    index++;
    public void displayInfotwo()
    Iterator it = BooksDB.iterator();
    while(it.hasNext())
    ((Book)(it.next())).displayBooks();
    Upgrage to atleast Java 5 and you're laughing: combine generic collections with the enhanced for loop and that mess of a
    displayInfotwo becomes:
    public void displayInfotwo() {
        for (Book book : BooksDB) {
            book.display();
        }

  • How to exclude exisiting objects when combining ArrayLists?

    Hi there, I'm new to Java and im trying to find a way to combine 2 ArrayLists and exclude any objects that may already exist in the customer ArrayList. I have a program that loads/saves data from a text file into a class object and I want the function to load the data 1 time and check if it already exisits.
    I have tried using if(!customers.contains(obj)), but I think this only references the ArrayList Key and not the actual data.
    Below is a test class I have been using to debug. Any help would be great!!!
    public class test {
         public static void main(String[] args){
              ArrayList<Customer> temp  = new ArrayList<Customer>();
              ArrayList<Customer> customers  = new ArrayList<Customer>();
              Customer cs1 = new Customer(1,"sophie",'m',23,"asdasd");
              Customer cs2 = new Customer(1,"sophie",'m',23,"asdasd");
              Customer cs3 = new Customer(2,"asd",'m',23,"sdfghh");
              Customer cs4 = new Customer(3,"sdfff",'m',23,"hhhrrr");
              temp.add(cs1); temp.add(cs3); temp.add(cs4);
              customers.add(cs2);
              for(Customer c : temp){
                   if(!customers.contains(c))
                   customers.add(c);
              Collections.sort(customers, new CustomerComparator());
              System.out.println(customers);
              System.out.println(customers.contains(cs2));
    }Edited by: newToJavaPro on May 21, 2010 10:18 PM

    paulcw wrote:
    newToJavaPro wrote:
    Thanks for your reply I tried using a HashSet, which works for removing objects from the same origin, but it doesn't seem to remove the same data when added to the ArrayList from different objects. For example, id like to use cs1 to remove an instance of cs2 as they contain the same data but are assigned using different objects.No, that doesn't make any sense. More likely, you didn't properly override .equals() and hashcode(), so the set can't compare them properly. It seems to happen when they come "from different objects" because you're creating different instances of Customer each time, so the default implementations of .equals() and .hashcode() identify them as non-equivalent.Thanks, I I didn't realize HashSet and Equals compared object instance by default. Overridden methods and works a treat.

  • Is there any default size for ArrayList

    The default capacity of Vector is 10.
    Is there any default size for ArrayList ??
    Vector v = new Vector();
    System.out.println("==> "+v.capacity()); // output is ==> 10
    java.util.List alist = new ArrayList();
    System.out.println("==> "+v.capacity()); // here the out put is ==> 0
    Regards
    Dhinesh

    No default size for arraylist.initially it's zero.
    I think u r comparing capacity with a size those two are different.
    Size- represents number of elements in the array.
    capacity- the capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.
    it depends on the ensureCapacity() method in the arraylist.

  • I need help with comparing Objects of an ArrayList

    Hi,
    I am trying to compare a certain variable of objects which are stored in an arrayList.
    for example i have a class called AuctionBid(String bidderID, BitSet itemSet, int bidValue)
    and i have another class called AuctionBidFactory which creates AuctionBid objects and stores them into an arrayList
    I have another Gui class which acts as a user interface where the user can create bids but then i want to compare the itemSet of the AuctionBid which is created by the user to the itemSets of the AuctionBid objects which already exist in the arrayList and if that itemSet does not exist in the arraylist then will add the new AuctionBid to the arrayList.
    I have the following method in the AuctionBidFactory which is supposed to compare the itemSets of the AuctionBids in the arrayList and it does not work:
    public boolean containsItem(AuctionBid auctionBid) {
              if (auctionBids.contains(auctionBid.itemSet)) {
                   return true;
              return false;
    where auctionBids is the arrayList where the AuctionBid objects are stored
    I hope the information above is enough to see where the problem is.
    many thanks

    Amit, unfortunately I dont have a different object for the user bids. Basically I just have the AuctionBid(String bidder,BitSet items, int value) and the reason why im using bitSet is that im modelling a combinatorial auction where the bidder can bid on combination of items.
    now when the user puts a bid that bid is added to an arrayList of ArrayList<AuctionBid>
    then once all the bidings have finished i want to create autoBids for those single items only for which there are no bids. so for example lets say there are 6 items for auction and if there are the following bids in the arrayList:
    AuctionBid(bidder1,{1},5)
    AuctionBid(bidder2,{5},8)
    i want to create autobids as follow:
    AuctionBid(autoBid,{0},0)
    AuctionBid(autoBid,{2},0)
    AuctionBid(autoBid,{3},0)
    AuctionBid(autoBid,{4},0)
    and then i want to add these created bids to the same arrayList where all the bids are.
    but if I use the arrayList.contains() method it will compare the whole objects to each other rather than just comparing the bitSets(items) in each bid.
    so i dont know whether i can still do this without overriding the equals() method in the AuctionBid class or not
    regards
    Arneh

  • 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.

  • Reg: ArrayList

    Hi All,
    I have a ArrayList in my application and some objects are added to that arraylist for ex: "arr.add("document"); 
    I am unable to understand the concept of this arraylist. What type of attributes can be added to arraylist.
    Thanks in advance.

    Hi Bharath,
                      Check this:
    <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html">http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html</a>
    regards
    Sumit

  • How do I get at a JTable on a JInternalFrame?

    I've been working on this Multiple Document Interface application, and things have been great up to this point. The user chooses to run a "report" and then selects an entity to get the info for. I then hit the database. Each row returned from the database query goes into it's own data object, which is added to an ArrayList in my custom table model, and that ArrayList is used to generate the JTable, which is then added to a ScrollPane, which is then added to the JInternalFrame, which is then added to the JDesktop pane. Good stuff, right?
    I'm now trying to add Print functionality, and I'm at a loss. What I want to do is have the user do the standard File->Print, which will print out the JTable on the currently selected inner frame. I can get a JTable to print using JTable.print(). What I can't do is find a way to get the JTable from the selected frame.
    I can get the selected frame using desktop.getSelectedFrame(), but I'm at a loss as to what to do next. I've played around with .getComponent, but I'm not having any luck. the components returned don't seem to do me any good...for example, JViewPort?
    Am I going about this the wrong way? Have I poorly designed this? Am I missing the obvious?
    Thanks,
    -Adam

    Well, if you only have a single component on the internal frame then you can use getComponent(0). But then you need to go up the parent chain to get the actual table. You will initially get the JScrollPane, then use that to get the JViewport and then use that to get the viewport component.
    Another option is to extend the JInternalFrame class and insted using the add method to add a component you create get/setTable(...) methods. Then you can save the table as a class variable before adding it the scrollpane and adding the scrollpane to the internal frame.

  • Checkbox in datatable

    Hi,
    I use a data table in my jsf page.I have give a f:selectbooleanchkbox.
    When i select the chk box my data table has to be updated with the checked ones.
    problem here is:
    I have a button at the bottom of my page named reassign.when i click on the reassign button i shud get a pop up and this pop up has to be loaded with dynamic values.since a java script for pop up & both action cannot be called at a single shot , i use a use bean tag in my pop up to call a method in backing bean to load the pop mup with dynamic values.
    Doing this way(calling a bean method), will my data table be automatically updated?
    Presently am using a value changed listener on click of my chk box.but doing this way cant be efficient & does not seem to be user friendly as the form is submitted each time.
    Your suggestions would be appreciated.
    Thanks,
    padma.

    I think I finally pulled it of; I added an empty arraylist and assigned the value of the checkbox to it.
    I don't really know how to point to a certain element in that list, as value="#{theBean.theList[person.id]}" or value="#{theBean.theList['person.id']}" or value="#{theBean.theList[0]}" don't seem to evaluate to something meaningfull.
    It's kinda ugly, and I was hoping binding the tag to a method would get me a cleaner solution, but it appears it doesn't pass the f:attribute (??)...

  • How do i update a JTextArea?

    Hey
    I have a main GUI class where i can add one number to an ArrayList in an ohter class (Basket). After i added the number to the ArrayList
    i can click a button to open anohter window (which is created in BasketGUI class) where a JTextArea are showing the numbers i have
    added in the ArrayList.
    But notthing is showing, i know the addition to the ArrayList works because it works with a System.out.println.
    I have to post alot of code, so you could just skip the code and eksplain to me in generel how to update a JTextArea.
    BasketGUI:
    * Basket.java
    * Created on 5. februar 2008, 15:29
    package userclasses;
    import java.util.ArrayList;
    * @author  Lille mus
    public class BasketGUI extends javax.swing.JFrame {
        private Basket basket;
        private Stock stock;
        private String newline = "\n";
        /** Creates new form Basket */
        public BasketGUI() {
            stock = new Stock();
            basket = new Basket();
            initComponents();
        public String showBasket(){
            ArrayList newBasket = basket.getArrayList();
            String returnBasket = "";
            for(Object item : newBasket){
                returnBasket += item+newline;
            return returnBasket;
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Indk?bskurv");
            jLabel1.setText("Indk?bskurv");
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jTextArea1.setText(stock.printAllStockItems());
            jTextArea1.setText(showBasket());
            jScrollPane1.setViewportView(jTextArea1);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(21, 21, 21)
                            .addComponent(jLabel1))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(224, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1)
                    .addGap(20, 20, 20)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(159, Short.MAX_VALUE))
            pack();
        }// </editor-fold>
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new BasketGUI().setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JLabel jLabel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        // End of variables declaration
    }This code is what happends when i click the button which adds a number to the ArrayList:
    private void putInBasket(java.awt.event.ActionEvent evt) {                            
            //Integer itemId = Integer.parseInt(itemIdField.getText());
            basket.addItemToBasket(3);
            System.out.println(basket.showBasket());
        }Basket class:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package userclasses;
    import java.util.ArrayList;
    * @author Jesper
    public class Basket {
        private ArrayList<Integer> basket;
        private String returnBasket;
        private Stock stock;
        private String newline = "\n";
        public Basket(){
            basket = new ArrayList<Integer>();
            add4ItemsToBasket();
        public void addItemToBasket(int itemId){
            basket.add(itemId);
        public void add4ItemsToBasket(){
            addItemToBasket(1);
            addItemToBasket(2);
        public String showBasket(){
            for(Integer item : basket){
                returnBasket += item+newline;
            return returnBasket;
        public ArrayList getArrayList(){      
            return basket;
    }Thank you!

    okay... i cant figure out the logic in this. i have put this code into the BasketGUI class:
    public void setBasketList(){
            basketListTextArea.append(basket.showBasket());
        }this function i call in my MainGUI here:
    private void putInBasket(java.awt.event.ActionEvent evt) {                            
            //Integer itemId = Integer.parseInt(itemIdField.getText());
            basket.addItemToBasket(3);
            basketGUI.setBasketList();
            System.out.println(basket.showBasket());
        }What am i doing wrong?

Maybe you are looking for

  • ITunes takes ages to load

    When it finally does it takes ages to be able to select anything and when I plug in either my iPhone or iPad it freezes and has to be shut down throughout the control menu. Everything else starts and play correctly on the laptop

  • Adobe AIR is not installing on my LSC

    I installed the correct version of Adobe AIR base on this link http://get.adobe.com/air/ vesrion 15. This version should fix the problem but I still get the same problem. The installation of Adobe AIR has failed. Now exiting the setup. Can some one h

  • HT201210 Cant update as iphone firmware not compatible what does this mean

    I cna't update my iphone 4 ios as it says that the firmware is not compatible, what doe sthat mean and what can i do ?

  • SQL Exception with the message "executeQuery, Exception = null"

    Hi , Iam getting an SQL Exception with the message "executeQuery, Exception = null". Other thing is, the SQLException.getErrorCode gives me 0. Below is the stack trace. Could you please help me, why Iam getting this message: com.ups.ops.dm.dao.DAOSev

  • ADF application deployment on Oracle Apps server?

    OAFramework is used to create and deploy oracle application pages...can ADF framework be used instead of OAFramework and be deployed and accessed in Oracle Applications? or as both OAF and ADF have different structures/framework they are for differen