954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

ArrayList<Object> Get Index

I have a question on how to get the index of a selected object. I'll briefly explain my project to help get a better understand of what I'm doing.

I have created a simple object (named InfoObject) which is made up of 2 jTextfields and 1 jComboBox. I have added focusListeners to the textfields. When a jTextField is clicked/focused it sets the background to a specified color (making it obvious that the object of information has been selected) Also, when the object is focused it sets a boolean to true, when it is no longer focused, the boolean is returned to false.

I then have a separate class containing my jPanel that adds an InfoObject to the panel upon reading a file and upon a users input. I also add each object to an arraylist. (ArrayList)

My Question:
Is there a way to get the index of the InfoObject when it is focused/clicked? My goal is that when the object is focused, I'll have the opportunity to click a button which removes the object from the jPanel and the ArrayList so that when I save the information it doens't have any old information in it.


I can provide source or extra details if need be. Looking forward to replies. Thanks to anyone and everyone who offer advice on the matter

KirkPatrick
Junior Poster
162 posts since Apr 2009
Reputation Points: 38
Solved Threads: 8
 

I think you want to get the index to be able to remove the InfoObject from the Arraylist list. You can do it without an index. You can directly pass the object to remove method.

InfoObject info1 = new InfoObject();
InfoObject info2 = new InfoObject();
ArrayList<InfoObject> list = new ArrayList<InfoObject>();
list.add(info1);
list.add(info2);

list.remove(info1);
gangsta1903
Junior Poster
111 posts since May 2008
Reputation Points: 12
Solved Threads: 8
 

The issue with that solution is that I have so many InfoObjects being added that I don't name them with numbers after it.

It looks like so (psuedocode):

for each line in text file {
            iObject = new InfoObject(param1, param2, array)
        }


Which is why I added the isSelected boolean to the object. When it is highlighted I would like to be able to have some way of knowing which object in the arraylist that it is so I can remove it.

So I figured I had to get the index of the InfoObject and then I can go about removing it.

I appreciate the help, but I don't think that will work for what I'm attempting to do. Any other ideas?

KirkPatrick
Junior Poster
162 posts since Apr 2009
Reputation Points: 38
Solved Threads: 8
 

I dont know the internals of your code.

The point I want to stress is that you say you have to find the index,well I say you just have to access the object. Do we agree on this?

gangsta1903
Junior Poster
111 posts since May 2008
Reputation Points: 12
Solved Threads: 8
 

I agree, I just need access to the object so I can remove it from the arraylist and the panel if need be.

If you would like code I can provide it. It is actually quite simple code. I just question on how to go about accessing the specific object that is selected for the time being.

KirkPatrick
Junior Poster
162 posts since Apr 2009
Reputation Points: 38
Solved Threads: 8
 

If you put the code, I can help. If I cant, maybe others can help.

gangsta1903
Junior Poster
111 posts since May 2008
Reputation Points: 12
Solved Threads: 8
 

You could:
a) add a 'parent' reference to the InfoObject so that when it's clicked it can set a property such as 'selectedInfo' on the parent to itself.

b) Simply loop the list and find the 'selected' object.

It really depends on the dependencies you're trying to support in your class structure.

Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 
If you put the code, I can help. If I cant, maybe others can help.

Thank you for the help thus far, I'll post the source (or what's needed of the source)


InfoObject:

public class InfoObject extends javax.swing.JPanel implements FocusListener {

  private String string1;
  private String string2;
  private ArrayList newList;

  //add to combobox after getting
  private String newList1;
  private String newList2;
  private String newList3;
  private String newList4;
  private String newList5;


  Boolean isFocused;

  Color rowSelected = new Color(198,226,255);

    /** Creates new form DatabaseObject */
    public DatabaseObject(String string1, String string2, ArrayList newList) {
        initComponents();

        this.string1 = string1;
        this.string2 = string2;
        this.newList = newList;

        for (int i = 0; i < newList.size(); i++){
           jComboBox1.addItem(newList.get(i));
        }

        jTextField1.setText(string1);
        jTextField2.setText(string2);


        jTextField1.addFocusListener(this);
        jTextField2.addFocusListener(this);

        
    }

  public String getstring1() {
    return this.string1;
  }

  public String getstring2() {
    return this.string2;
  }


  public ArrayList getDccComboBox() {
      return this.newList;
  }

  public boolean isFocused() {
      return isFocused;
  }



    public void focusGained(FocusEvent e) {
        isFocused = true;
        jTextField1.setBackground(rowSelected);
        jTextField2.setBackground(rowSelected);
        jTextField3.setBackground(rowSelected);
        jTextField4.setBackground(rowSelected);
        jTextField5.setBackground(rowSelected);
        jTextField6.setBackground(rowSelected);
        System.out.println("true");
    }

    public void focusLost(FocusEvent e) {
        isFocused = false;
        jTextField1.setBackground(Color.WHITE);
        jTextField2.setBackground(Color.WHITE);
        jTextField3.setBackground(Color.WHITE);
        jTextField4.setBackground(Color.WHITE);
        jTextField5.setBackground(Color.WHITE);
        jTextField6.setBackground(Color.WHITE);
        System.out.println("false");
    }

}


My jPanel only contains a function inside the class which ill post below (along with the soon to be delete button):

public void ReadFile() {

        String string1, string2, newList1, newList2, newList3, newList4, newList5;

        try {
            com.csvreader.CsvReader reader = new CsvReader(computerCsvPath);
            reader.readHeaders();
            while(reader.readRecord()) {

                ArrayList allList = new ArrayList();

                //get the data from file
                string1 = reader.get("Title1");
                string2 = reader.get("Title2");
                newList1 = reader.get("Title3");
                newList2 = reader.get("Title4");
                newList3 = reader.get("Title5");
                newList4 = reader.get("Title6");
                newList5 = reader.get("Title7");

                //add dcc numbers to array
                allList.add(newList1);
                allList.add(newList2);
                allList.add(newList3);
                allList.add(newList4);
                allList.add(newList5);


                //grab the info and put it in a new info object
                ndbo = new InfoObject(string1, string2, newList1, newList2, newList3, newList4, allList);

                //grab info from info object and store for writing to file
                list.add(ndbo);
            }

            //close reader
            reader.close();
            
            //iterate through and add InfoObjects to jPanel
            Iterator<InfoObject> iter = list.iterator();
            while(iter.hasNext()) {
                ndbo = iter.next();
                row++;
                constraints(row, ndbo, jPanel4); //specifies where to place the object
            }
            System.out.println(list);

        } catch(Exception e) {
            e.printStackTrace();
        }
    }



private void DeleteRowActionPerformed(java.awt.event.ActionEvent evt) {                                          

        if(ndbo.isFocused()) {
  	   //remove from arraylist and jpanel
	   //repaint all info objects once arraylist is re-iterated
        }
}

You could: a) add a 'parent' reference to the InfoObject so that when it's clicked it can set a property such as 'selectedInfo' on the parent to itself.

b) Simply loop the list and find the 'selected' object.

It really depends on the dependencies you're trying to support in your class structure.

a)
So I could add a parameter for int that would increment and place a getter which would be equivalent to the index?

b)
This is specifically what I was trying to learn how to do. I just wasn't positive on how to go about it. So I took a stab at it and posted to see if I was heading in the correct direction.

KirkPatrick
Junior Poster
162 posts since Apr 2009
Reputation Points: 38
Solved Threads: 8
 

I dont know how and where you use deleteRowActionPerformed.

But as far as I see, this is what you are looking for.

You can find the object which causes(has) the event. If you wanna find the InfoObject on focus, then you should access the InfoObject focused by the following line inside of your event handling method.

// now you get the InfoObject which InfoObject focused            
        InfoObject ndbo = (InfoObject) evt.getSource();
gangsta1903
Junior Poster
111 posts since May 2008
Reputation Points: 12
Solved Threads: 8
 

I dont know how and where you use deleteRowActionPerformed.

But as far as I see, this is what you are looking for.

You can find the object which causes(has) the event. If you wanna find the InfoObject on focus, then you should access the InfoObject focused by the following line inside of your event handling method.

// now you get the InfoObject which InfoObject focused            
        InfoObject ndbo = (InfoObject) evt.getSource();

DeleteRowActionPerformed is my button. I'm going to put the code in it when I figure out which code is necessary.Psuedocode:

if(object is selected) {
   remove object from list
   remove object from panel
}


Can you elaborate on your example? I currently don't have an event listener on the object itself. I have a focus listener on the textfields of the object. The listener only changes the background colors and returns a boolean true or false.

I don't seem to follow what you are suggestion, maybe I'm looking at it from the wrong angle.

I think you are suggesting that I add an focus listener to each InfoObject I add?

KirkPatrick
Junior Poster
162 posts since Apr 2009
Reputation Points: 38
Solved Threads: 8
 
JTextField jt =  (JTextField) evt.getSource();

        InfoObject info = (InfoObject) jt.getParent();

        // now you have the info object, remove it 
        list.remove(info);
gangsta1903
Junior Poster
111 posts since May 2008
Reputation Points: 12
Solved Threads: 8
 
JTextField jt =  (JTextField) evt.getSource();
        InfoObject info = (InfoObject) jt.getParent();
        
        // remove it from list, panel
        list.remove(info);
        panel.remove(info);
gangsta1903
Junior Poster
111 posts since May 2008
Reputation Points: 12
Solved Threads: 8
 

I don't believe that is possible either. My reasoning being that the jTextField is not accessible from the other class.

InfoObject:contains the jTextFields
holds the FocusListener
InfoViewer:contains the InfoObjects
when a textfield is clicked, all textfield's backgrounds are colored
each InfoObject is added either by being read from file (void function) or from the user which is then added in by a click of a button

For the way you show above, I believe I would need access to each textfield. Forgive me if I'm wrong, I'm a bit confused about it.

I'll put the source up and leave comments next to them, maybe this will help.

InfoObject (same as last post):

public class InfoObject extends javax.swing.JPanel implements FocusListener {

  private String string1;
  private String string2;
  private ArrayList newList;

  //add to combobox after getting
  private String newList1;
  private String newList2;
  private String newList3;
  private String newList4;
  private String newList5;


  Boolean isFocused;

  Color rowSelected = new Color(198,226,255);

    /** Creates new form InfoObject */
    public DatabaseObject(String string1, String string2, ArrayList newList) {
        initComponents();

        this.string1 = string1;
        this.string2 = string2;
        this.newList = newList;

        for (int i = 0; i < newList.size(); i++){
           jComboBox1.addItem(newList.get(i));
        }

        jTextField1.setText(string1);
        jTextField2.setText(string2);
        jTextField1.addFocusListener(this);
        jTextField2.addFocusListener(this);
    }

  public String getstring1() {
    return this.string1;
  }

  public String getstring2() {
    return this.string2;
  }


  public ArrayList getoComboBox() {
      return this.newList;
  }

  public boolean isFocused() {
      return isFocused;
  }


    public void focusGained(FocusEvent e) {
        isFocused = true;
        jTextField1.setBackground(rowSelected);
        jTextField2.setBackground(rowSelected);
        jTextField3.setBackground(rowSelected);
        jTextField4.setBackground(rowSelected);
        jTextField5.setBackground(rowSelected);
        jTextField6.setBackground(rowSelected);
        System.out.println("true");
    }

    public void focusLost(FocusEvent e) {
        isFocused = false;
        jTextField1.setBackground(Color.WHITE);
        jTextField2.setBackground(Color.WHITE);
        jTextField3.setBackground(Color.WHITE);
        jTextField4.setBackground(Color.WHITE);
        jTextField5.setBackground(Color.WHITE);
        jTextField6.setBackground(Color.WHITE);
        System.out.println("false");
    }

}


InfoViewer (contains the infoObjects which is where I want to be able to remove them if clicked):

public class InfoViewer extends javax.swing.JPanel {

    //text file to read from 
    private String computerCsvPath = C:testText.txt;

    //gives the number where to place info objects
    int row = 0; 

    //introduce Arraylist and InfoObject
    ArrayList<InfoObject> list = new ArrayList();
    InfoObject ndbo;

    /** Creates new form InfoViewer */
    public InfoViewer() throws FileNotFoundException, IOException {

        initComponents();
        
        ReadFile();

    }

    public void ReadFile() {

        String string1, string2, newList1, newList2, newList3, newList4, newList5;

        try {
            com.csvreader.CsvReader reader = new CsvReader(computerCsvPath);
            reader.readHeaders();
            while(reader.readRecord()) {

                ArrayList newLists = new ArrayList();

                //get the data from file
                string1 = reader.get("string1");
                string2 = reader.get("String2");
                newList1 = reader.get("NewList1");
                newList2 = reader.get("NewList2");
                newList3 = reader.get("NewList3");
                newList4 = reader.get("NewList4");
                newList5 = reader.get("NewList5");

                //add list numbers to array
                newLists.add(newList1);
                newLists.add(newList2);
                newLists.add(newList3);
                newLists.add(newList4);
                newLists.add(newList5);

                //grab the info and put it in a new info object
                ndbo = new InfoObject(string1, string2, newLists);

                //grab info from info object and store for writing to file
                list.add(ndbo);
            }

            //close reader
            reader.close();
            
            //iterate through and add InfoObjects to jPanel
            Iterator<InfoObject> iter = list.iterator();
            while(iter.hasNext()) {
                ndbo = iter.next();
                row++;
                constraints(row, ndbo, jPanel4);
            }
            System.out.println(list);

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

                       

    //insert new InfoObjects based on user input and click of a button
    private void InsertNewDataActionPerformed(java.awt.event.ActionEvent evt) {                                              


        //add string1, string2, InfoObject
        String dif = string1Field.getText();
        String osf = string2Field.getText();

        //add dcc numbers for the combobox
        ArrayList<String> dccComboBox = new ArrayList<String>();
        if (!NewListTextField.getText().equals("") && (!NewListTextField.getText().equals("-"))) {
            oComboBox.add(NewListTextField.getText());
        }
        if (!NewListTextField2.getText().equals("") && (!NewListTextField2.getText().equals("-"))) {
            dccComboBox.add(NewListTextField2.getText());
        }
        if (!NewListTextField3.getText().equals("") && (!NewListTextField3.getText().equals("-"))) {
            oComboBox.add(NewListTextField3.getText());
        }
        if (!NewListTextField4.getText().equals("") && (!NewListTextField4.getText().equals("-"))) {
            oComboBox.add(NewListTextField4.getText());
        }
        if (!NewListTextField5.getText().equals("") && (!NewListTextField5.getText().equals("-"))) {
            oComboBox.add(NewListTextField5.getText());
        }


        //add info object to jpanel
        ndbo = new DatabaseObject(dif, osf, mnf, tnf, rnf, driveCounted, dccComboBox);

        //add InfoObjects to list
        list.add(ndbo);

        //clear the jPanel
        jPanel4.removeAll();

        //iterate through and add InfoObjects to jPanel
            Iterator<InfoObject> iter = list.iterator();
            while(iter.hasNext()) {
                ndbo = iter.next();
                row++;
                constraints(row, ndbo, jPanel4);
            }

            System.out.println(list);

        //Clear the all fields from the GUI
        NewListTextField.setText((""));
        NewListTextField2.setText((""));
        NewListTextField3.setText((""));
        NewListTextField4.setText((""));
        NewListTextField5.setText((""));
        string1Field.setText((""));
        string2Field.setText((""));
        odccComboBox.clear();

   }                                             

    //save info objects currently located in the ArrayList list
    private void SaveCsvActionPerformed(java.awt.event.ActionEvent evt) {                                        

        String path = "C:\\test.csv";
        File file = new File(path);
        BufferedWriter out = null;

        try {
            out = new BufferedWriter(new FileWriter(file));

            Iterator<InfoObject> iter = list.iterator();
            while(iter.hasNext()) {
                ndbo = iter.next();
                String s = ndbo.toString();
                System.out.println(s);
                out.write(s);
                out.newLine();
            }
            out.close();
        } catch (IOException e) {
            System.out.println("IO error for " + path + ": " + e.getMessage());
        }

   }                                       

    //if user highlights an info object, give the option to remove it from ArrayList and jPanel by clicking this button
    private void DeleteRowActionPerformed(java.awt.event.ActionEvent evt) {                                          

        if(ndbo.isFocused()) {
  	   //remove focused InfoObject from ArrayList
	   //remove focused InfoObject from jPanel
        }
}


My apologies if I misunderstood your code above

KirkPatrick
Junior Poster
162 posts since Apr 2009
Reputation Points: 38
Solved Threads: 8
 

I thought your textFields had action listeners but your InfoObjects didnt. And I told you that you could access your InfoObject in the actionperformed methods of your textFields by using getParent() method.

Lets clear the situation:
- You want to remove a component from another component.
- Of course, you can do it upon events. An event can be clicking, focusing, resizing, moving, etc ....
- So, if you want to catch these events, you have to add corresponding listeners to your components.
- If a component does not listen to any events, how can you catch it?
- Thus, you have to add listeners.

#
//grab the info and put it in a new info object
#
ndbo = new InfoObject(string1, string2, newLists);
#
 // you created an InfoObject, now add action listener for example
ndbo.addActionListener(yourActionListener);
// or focus listener, add what event you want to listen
ndbo.addFocusListener(yourFocusListener);
#
//grab info from info object and store for writing to file
#
list.add(ndbo);
gangsta1903
Junior Poster
111 posts since May 2008
Reputation Points: 12
Solved Threads: 8
 

I thought your textFields had action listeners but your InfoObjects didnt. And I told you that you could access your InfoObject in the actionperformed methods of your textFields by using getParent() method.

Lets clear the situation: - You want to remove a component from another component. - Of course, you can do it upon events. An event can be clicking, focusing, resizing, moving, etc .... - So, if you want to catch these events, you have to add corresponding listeners to your components. - If a component does not listen to any events, how can you catch it? - Thus, you have to add listeners.

#
//grab the info and put it in a new info object
#
ndbo = new InfoObject(string1, string2, newLists);
#
 // you created an InfoObject, now add action listener for example
ndbo.addActionListener(yourActionListener);
// or focus listener, add what event you want to listen
ndbo.addFocusListener(yourFocusListener);
#
//grab info from info object and store for writing to file
#
list.add(ndbo);


Correct, I attempted to add Listeners to my InfoObjects but some of them are added in a void function. What would I change my return type to?

Also, I just realized, upon clicking a button doesn't the focus change? Ie. My InfoObject is focused (and highlighted) but when I click the "Delete Row" button it now becomes the focus and can't delete the row?

Also I took your example above, added a getter into the other class where the text fields are so that I could pass along the information to my other class.

Before I go further, I probably need to know if you suggest a better way of going about this since I think the focus listener will be an issue if I have to click a button to remove the currently focused object.

So I have 2 main issues at the moment. By the way, thank you for sticking with this thread and helping out

KirkPatrick
Junior Poster
162 posts since Apr 2009
Reputation Points: 38
Solved Threads: 8
 

you considered that "highlighting" of the button as a focus event...
in fact, its true. focusing can be gained by mouse and keyboard.

Do you want to do it when it gains focus or when it is clicked?

you can read following tutorials to learn the differences between event listeners, and also how you can use them.

http://java.sun.com/docs/books/tutorial/uiswing/events/index.html

gangsta1903
Junior Poster
111 posts since May 2008
Reputation Points: 12
Solved Threads: 8
 

The easiest thing for you to do is loop the InfoObjects in your array to find the "selected" one and remove it.

There is a lot you could do to add listeners, models, etc to make this more MVC, but it would require a decent amount of extra work because your UI objects are your data objects at this point.

You're correct that focus will change when you click the button. Also consider that you don't want to code the InfoViewer operations into the InfoObjects. Keep your separation of responsibilities in mind with the container and the contained items.

Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

you considered that "highlighting" of the button as a focus event... in fact, its true. focusing can be gained by mouse and keyboard.

Do you want to do it when it gains focus or when it is clicked?

you can read following tutorials to learn the differences between event listeners, and also how you can use them.

http://java.sun.com/docs/books/tutorial/uiswing/events/index.html

Correct when it gains focus (in my case the user clicks on a textfield of the InfoObject) I want to be able to click my button "Delete Row" and get rid of that information from the ArrayList and jPanel.

However, below, Ezzaral confirmed that the focus has changed as soon as I click "Delete Row"

I'll start reading from the link you have provided me with. I'll have to find a listener than will keep that ViewObject focused while clicking the "Delete Row" button.The easiest thing for you to do is loop the InfoObjects in your array to find the "selected" one and remove it.

Can you elaborate on how it would find which one is "selected". That the issue I'm trying to resolve, is how to tell that specific object is currently selected (at least from the arraylists perspective)There is a lot you could do to add listeners, models, etc to make this more MVC, but it would require a decent amount of extra work because your UI objects are your data objects at this point.

Would you mind elaborating on this? I don't really plan on changing it much, but in the future you never know. It also never hurts to know extra knowledge in case I stumble upon the need for it later.You're correct that focus will change when you click the button. Also consider that you don't want to code the InfoViewer operations into the InfoObjects. Keep your separation of responsibilities in mind with the container and the contained items.

Thank you for confirming this before I went any further

KirkPatrick
Junior Poster
162 posts since Apr 2009
Reputation Points: 38
Solved Threads: 8
 

The easiest thing to do would be just add a checkbox to the panel to set a boolean "selected" property on the object. That would allow multiple selection as well.

Here's an article on MVC if you care to read more on that topic: http://java.sun.com/developer/technicalArticles/javase/mvc/?intcmp=3273#3

Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

The easiest thing to do would be just add a checkbox to the panel to set a boolean "selected" property on the object. That would allow multiple selection as well.

Here's an article on MVC if you care to read more on that topic: http://java.sun.com/developer/technicalArticles/javase/mvc/?intcmp=3273#3

Just to clear this up, are you suggesting I add a JCheckBox to the InfoObject, or add a JCheckBox to the side on the panel when I add each InfoObject?

KirkPatrick
Junior Poster
162 posts since Apr 2009
Reputation Points: 38
Solved Threads: 8
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You