Find index in an array of components

I have an array of JButtons. Each JButton has an associated ActionListener. My problem is that when one of the buttons are clicked I need the index of the JButton that is clicked to do work inside the Actionlistener.
How do I get the index of the JButton being pressed?
JButton[ ] button = new JButton[300];
for(int i = 0 ; i < 300 ; i++)
button[i] = new JButton(("Test " + i));
button.addActionListener(new ActionListener()
public actionPerformed(ActionEvent evt)
/** I need to know what the value of i is when this button is pressed **/

I would think that you could just use the variable i from the loop, like this:
JButton buttonArray = new JButton[300];
JButton button;
for(int i = 0; i < 300; i++)
  button = new JButton("Test"+i);
  button.addActionListener(new ActionListener() {
    public actionPerformed(ActionEvent e)
      int index = i; // here index is the index of the JButton chosen
hope this helps!
  buttonArray[i] = button;

Similar Messages

  • IndexOf(obj)  to find index in Vector E

    hello,
    I use one array which components are some objects of one class.
    I use that class in the way C are used structs, to have a collection of different type objects (the class have only properties).
    So...., I need to have the index of one object in the arry that have one paricular value for one his property, and I thought to use for this purpose a Vector <E> instead a normal vectorwith the method indexOf(obj). But I was not able to write the code for this purpose, it need to locate the object by one his property...
    I thaugth what I will do is not possible, and I implemented a normal ector with methods that scann all the items in one traditional vector to find what I need...
    But this is not the best.., the algoritm is complex in the time of execution.. and I have to write a methods for each property that I will look for...
    Some one is able to suggest me one way to solve the problem using Vector<E> class.
    thank you very much
    regards
    tonyMrsangelo

    tonyMrsangelo wrote:
    thank you to answered me,
    I have to say that I am enough new to java, as well I already used other more traditional languages (like C and C++).
    My problem is to have one collection of objects that are not of the all same type_ (they can be String, int, boolean, Date, Objects, float ..).
    In those other languages the only way to collect them is to use "struct" in C , "records" in Pascal...
    And if you need you can group these complex object ("struct" or "records"...) in one array too.
    I did the same in java using one class where I put inside only properties (with different types, ..in the same way that in C you can use one struct).
    You suggest me to use one ArrayList of collections.
    That could be good for solve my problem if it is possible put, inside the collections, objects of different type.. but I am not sure this is possible.
    I already used collection, but I always put inside them only values of the same type...
    Now my ask is: can I put in one collection some data bilonging to different types (as boolean, String, int, float ...) ?
    regards tonyMrsangeloYou can add anything inside an ArrayList if you instantiate it like this:
    ArrayList<Object> list = new ArrayList<Object>();
    list.add(new Float(1.1f));
    list.add(new Integer(2));
    list.add(new Boolean(true));, although I would not recommend it to do it like that. Perhaps you could explain why you have the need for this, there probably is a better way to do it.
    I suspect you are looking for something like this:
    class CustomObject {
      private float f;
      private int i;
      private boolean b;
      // ... methods and c'tors here ...
    // inside another class:
    ArrayList<CustomObject> list = new ArrayList<CustomObject>();

  • Find row in 2d array

    please help...
    i have 2d array of double and i wanna find specific row an extract to new 2d array.
    My 2d array is:
    100
    31,3
    25,3
    32,1
    25,6
    100
    31,3
    25,3
    32,1
    25,6
    160
    32,4
    25,5
    33,5
    26
    170
    33,2
    25,8
    34,3
    26,2
    100
    33,9
    26
    35,2
    26,4
    160
    32,4
    25,5
    33,5
    26
    160
    32,4
    25,5
    33,5
    26
    100
    31,3
    25,3
    32,1
    25,6
    170
    33,2
    25,8
    34,3
    26,2
    and i wanna find row with numbers 100,160,170 and build new 2d array
    100
    31,3
    25,3
    32,1
    25,6
    160
    32,4
    25,5
    33,5
    26
    170
    33,2
    25,8
    34,3
    26,2
    please help....tnx, tnx
    Solved!
    Go to Solution.

    I guess you should be more specific about your question. If you are planning to find the values that are present in the 1st column then you can use search 1D array and pass the index to index the 2D array so you will get 1D array of row then build the array by finding the element.
    This is what Yamaeda explained
    The best solution is the one you find it by yourself

  • I need help with event structure. I am trying to feed the index of the array, the index can vary from 0 to 7. Based on the logic ouput of a comparison, the index buffer should increment ?

    I need help with event structure.
    I am trying to feed the index of the array, the index number can vary from 0 to 7.
    Based on the logic ouput of a comparison, the index buffer should increment
    or decrement every time the output of comparsion changes(event change). I guess I need to use event structure?
    (My event code doesn't execute when there is an  event at its input /comparator changes its boolean state.
    Anyone coded on similar lines? Any ideas appreciated.
    Thanks in advance!

    You don't need an Event Structure, a simple State Machine would be more appropriate.
    There are many examples of State Machines within this forum.
    RayR

  • I am looking to find out about specifications of the components of Hyper-V

    Hi,
    I am looking to find out about specifications of the components of Hyper-V, is someone able to reach out to me? Some features I am looking to find if Hyper-V covers (and the components that would be used) are:
    Automated   live migration
    Workload balancing
    Physical-to-virtual conversion
    Plug-in for SCOM
    Integrated StorageLink
    Distributed Virtual Switch
    Use of OpenStack?
    Thanks,
    Eric

    You can check with OpenStack to determine their support.
    SCOM support of Hyper-V - check wit the SCOM team.
    Automated Live Migration - this could be interpreted multiple ways.  However I suspect you are looking for the SCVMM PRO feature.
    Workload Balancing and StorageLink and Distributed Virtual Switch are feature / product names from companies other than MSFT - so you must elaborate on the use case.
    Not sure what your intent is, but it reads as if there is some feature comparison you are trying to do between apples and oranges.
    Brian Ehlert
    http://ITProctology.blogspot.com
    Learn. Apply. Repeat.

  • How to find index name with primarykey and column on a table?

    Hi,
    how to find index name with primarykey and column on a table?
    please help me.
    Thankyou.

      1  select ac.table_name, ac.index_name, aic.column_name
      2  from user_constraints ac, user_ind_columns aic
      3  where ac.constraint_type = 'P'
      4   and  ac.index_name = aic.index_name
      5* order by 1,2,3
    SQL> /
    TABLE_NAME                 INDEX_NAME                COLUMN_NAME
    ACTION_TABLE                 SYS_C0011033                NESTED_TABLE_ID
    ACTION_TABLE                 SYS_C0011033                SYS_NC_ARRAY_INDEX$
    CATEGORIES_TAB                 SYS_C0011038                CATEGORY_ID
    CUSTOMERS                 CUSTOMERS_PK                CUSTOMER_ID
    INVENTORIES                 INVENTORY_IX                PRODUCT_ID
    INVENTORIES                 INVENTORY_IX                WAREHOUSE_ID
    LINEITEM_TABLE                 SYS_C0011034                NESTED_TABLE_ID
    LINEITEM_TABLE                 SYS_C0011034                SYS_NC_ARRAY_INDEX$
    ORDERS                      ORDER_PK                 ORDER_ID
    ORDER_ITEMS                 ORDER_ITEMS_PK                LINE_ITEM_ID
    ORDER_ITEMS                 ORDER_ITEMS_PK                ORDER_ID
    PRODUCT_DESCRIPTIONS            PRD_DESC_PK                LANGUAGE_ID
    PRODUCT_DESCRIPTIONS            PRD_DESC_PK                PRODUCT_ID
    PRODUCT_INFORMATION            PRODUCT_INFORMATION_PK           PRODUCT_ID
    PROMOTIONS                 PROMO_ID_PK                PROMO_ID
    WAREHOUSES                 WAREHOUSES_PK                WAREHOUSE_ID
    16 rows selected.

  • Find Intersection of two array elements in Oracle 9i

    How to find intersection of two arrays in pl/sql for Oracle 9i.
    it is feasible in 11g using given code but this code is not working in 9i please help....
    DECLARE
    abc LIST := list(1,2,3,4);
    def LIST := list(4,5,6,7);
    BEGIN
    dbms_output.put_line(format_list(abc MULTISET EXCEPT def));
    END;
    Thanks in advance.... :)

    Argh. Never mind. My coordinates were reversed.
    People that made my data set specified the coordinates as lat/long and I didn't question it. I can now see that Oracle expects long/lat instead, so my example works now.

  • How to find indexes in sql tables

    Hi i need help for how to find the indexes for the sql tables.I had some tables in sql 2005 and i need to find indexes for that tables.Can anyone will help in this isssue.

    I think you can use one of the built-in db functions ... (but it depends upon which database you're using)
    in sql server:
    sp_helpindex tablename

  • Using buttons to make an array of components

    Im trying to use a JButton to create an array of components(JButtons)
    and put them in a panel.My code only generates one button not three as planned! The purpose is to allow the user to configure the GUI according to a list of parameters.
    void button1_actionPerformed(ActionEvent e) {
    // array to hold buttons
    JButton button2[] = new JButton[3];
    for (int i=0;i<3 ;i++){ //set up each button
    button2[i] = new JButton();
    button2.setBackground(Color.cyan);
    button2[i].setSize(50,50);
    button2[i].setText(String.valueOf(i));
    panel1.add(button2[i]);
    }//end for
    }///end button1_actionPerformed

    void button1_actionPerformed(ActionEvent e) {
    // array to hold buttons
    JButton button2[] = new JButton[3];
    for (int i=0;i<3 ;i++){ //set up each button
    button2[i] = new JButton();
    button2.setBackground(Color.cyan);
    button2[i].setSize(50,50);
    button2[i].setText(String.valueOf(i));
    panel1.add(button2[i]);
    panel1.validate(); // <<<<<< edited
    }//end for
    }///end button1_actionPerformed
    now it should works!

  • Current index to an Array

    I don't know how to get the current index to an array. I wrote a temp vi (attached file) to show my problem. Eventually the output of the array will go to the serial port.
    Attachments:
    temp.vi ‏13 KB

    Schmir1,
    In your program you have a 0 wired to the index array terminal and so you are always displaying the element at index 0. When you change increment or decrement the array index you are only changing the display on the frontpanel, the entire array is still present there and so it will still display the index 0 element.
    As I understand from your program you are trying to pass individual hex values to the serial port. You will have to wire different values to the index terminal of the index array function during each run to pass individual value.
    I modified your application for easier understanding.
    Hope this helps,
    Pravin
    Attachments:
    temp[1].vi ‏15 KB

  • Array of components

    Hi,
    Is there some way to create an array of components. What I'd
    like to be able to do is have an array of 8 panels or datagrids.
    Then be able to loop through each of those within the array.
    Thanks!

    Anyone have any thoughts? It seems one way might be to do a
    repeater, although I would prefer to do most of this within the
    scripting? Any direction would be great

  • Index of sorted array

    I have a unsorted array as follows:
    array_index = {0 1 2 3 4 5 6 7 8}
    array = {1 2 4 3 4 3 4 2 1}
    I would like to get the previous index of sorted array as follows:
    old_index = {2 4 6 3 5 1 7 0 8}
    arrray.sort doesn't return the index the previous index, please help me.

    You can do that using by creating an array containing the numbers 0 to n in increasing order and sorting that using a comparator that actually compares the content of the original array at the indices provided to it instead of the values themselves.
    But why would you need that? Could you describe your requirement in a broader scope?

  • Find Index for max value of array

    I can use arrayMax to get the max value for a small array, but I need to get which index the max value is located. That will determine which page the user goes to next. Here is my code:
    array:
    <cfset arrAverages[1]="#qryFairness.fairness#"/>
    <cfset arrAverages[2]="#qryHonesty.honesty#"/>
    <cfset arrAverages[3]="#qryCompassion.compassion#"/>
    <cfset arrAverages[4]="#qrySelfControl.SelfControl#"/>
    <cfset arrAverages[5]="#qryMoralConcern.MoralConcern#"/>
    These values are gathered from querying values stored in a table.
    I can get the max value in the array easily by:
    <cfdump var="#arrayMax(arrAverages)#">
    What I can't figure out is how to get the row in this array where that max value is located. It seems like it would be so simple, but nothing I have tried has worked.
    Thanks,
    Richard

    rking1966 wrote:
    I can use arrayMax to get the max value for a small array, but I need to get which index the max value is located. That will determine which page the user goes to next. Here is my code:
    array:
    <cfset arrAverages[1]="#qryFairness.fairness#"/>
    <cfset arrAverages[2]="#qryHonesty.honesty#"/>
    <cfset arrAverages[3]="#qryCompassion.compassion#"/>
    <cfset arrAverages[4]="#qrySelfControl.SelfControl#"/>
    <cfset arrAverages[5]="#qryMoralConcern.MoralConcern#"/>
    These values are gathered from querying values stored in a table.
    I can get the max value in the array easily by:
    <cfdump var="#arrayMax(arrAverages)#">
    What I can't figure out is how to get the row in this array where that max value is located. It seems like it would be so simple, but nothing I have tried has worked.
    You can find it in one line of code! Here is an example:
    <cfset testArr[1]=-183>
    <cfset testArr[2]=79>
    <cfset testArr[3]=6>
    Max.:  <cfoutput>#arraymax(testArr)#</cfoutput><br>
    Index of max.: <cfoutput>#arrayfindNocase(testArr, arraymax(testArr))#</cfoutput>

  • Find index number of an Object in an ArrayList

    hi guys
    I have an array list of of products which contains 8 strings.
    say productList[0]= "asaaas1212"
    now i want to get a method which can find out at what index the string "asaaas1212"
    is situated on the productList.
    thanks
    Message was edited by:
    sifatkhan

    thanks for your reply
    will it work if i try this
    int count= productList.indexOf("string")?
    cheerzyep.. If it doesn't.. blame SUN..
    Lots of knowledge available here http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html

  • Summing and Finding Maximum in 2d array

    So I have an 2d array of numbers and I am trying to find the maximum sum of the rows and give back the row number. So far I can get the sum and the maximum number but I need to give back the row number of the maximum value.
    public static void RowSumRow (int[][] table)
          static int sum[] = new int[5];
          int region=0;
          for (int row=0; row < table.length; row++)
                sum [row] = 0;
                for (int col=0; col < table[row].length; col++)
                   sum [row] = sum [row] + table[row][col];     
          int max = myMethods.maximumSearch(sum);
          System.out.println("The maximal revenue is $" + max + " at region " + region);
        }myMethods.maximumSearch
    public static int maximumSearch(int a[])
         int Max = a[0];
         for (int index=0; index < a.length; index++)
             if(Max < a[index])
              Max = a[index];
            return Max;
       }

    this is correct right?
    (the prarmeter rows is the rows that are to be tested)
    public static void RowSumRow (int[][] table, int rows)
          int sum[] = new int[rows];
          int region=0;
          for (int row=0; row < table.length; row++)
                sum [row] = 0;
                for (int col=0; col < table[row].length; col++)
                   sum [row] = sum [row] + table[row][col];     
          int max = myMethods.maximumSearch(sum);
          for(int x=0; x < sum.length; x++)
              if (max == sum[x])
                region = x-1;
          System.out.println("The maximal revenue is $" + sum[region] + " at region " + region);
        }This does what I want it to do right? Ive tested a few times and it is working, but is it logically correct?

Maybe you are looking for