Passing the array into actionPerformed method

Hi friends! I am new at java. I made a tictactoe game board with GUI and it is designed according to nxn (desired any n value). When I pressed to any button, it should write an X to my board but I could not passed the button's action. My problem is that my actionPerformed method does not accept array button[j]. In the below there is a part of my code :
for(int j=0;j<button.length;j++)     // adding the buttons
button[j].addActionListener(this);
public void actionPerformed(ActonEvent evt)
// what can I read here for detecting the right button? button length is changable, it is depent on what we desire at first.
// I tried this code in this area but it does not work:
// if (evt.getSource()==button[j])
// button[j].setText("X");
// normally, it works if I write every button individually like that:
// button1.addActionListener(this); (same for other buttons)
// public void actionPerformed (ActionPerformed evt)
// if (evt.getSource()==button1)
// button1.setText("X"); (same code for other buttons)
// but I want to make a generalized board action
}I will be appreciated with your helps...
Musty

Hi musty4284,
The getSource method of ActionEvent(not ActonEvent) returns an object and the way you're comparing objects is wrong.
Theorically, you should do something like this :
public void actionPerformed(ActionEvent evt) {
    JButton b = (JButton) evt.getSource();
    if ( button[j].equals(b) ) {
}Edit :
When using a listener for an array of JButton, it is a good idea to give a unique identifier to each button (for example, their index in the array). The JButton class has a setName method not to confuse with the setText method.
While building your array of JButton, you can do :
JButton[] button = new JButton[9];
for (int i = 0; i < 9; i++) {
    button[i] = new JButton();
    button.setName(i);
While handling the event :public void actionPerformed(ActionEvent evt) {
JButton b = (JButton) evt.getSource();
int index = Integer.parseInt(b.getName());
button[index].setText("X");
Edited by: Chicon on Oct 4, 2009 11:20 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • Passing an array to a method taking an Object?

    Hi,
    I need to pass an array of randomly generated numbers to a method that takes an Object.
    I can't seem to figure out how to do this...
    Here is my code for creating the array of random numbers:
    Random generator = new Random();
    for (int i = 0; i < size; i++)
    a[ i ] = generator.nextInt();
    mySort(a);
    Here is the signature of the method I am trying to pass it to:
    public static void mySort(Comparable [] a)
    When I compile I get the following message: mySort ( java.lang.Comparable[] ) cannot be applied to (int[]) mySort(a);
    How can I convert the array into an Object?
    Any help is much appreciated!

    >
    It'll be easier in java 1.5...But will result in terrible code being written by folks who don't understand the penalties incurred with auto-boxing.
    If you have to sort an array of integers, grab a QuickSort implementation that works with int[] directly (there is one built into the Arrays class) - creating all of those temporary objects kills performance.
    - K

  • Pass an arrayList into a method

    I am looking to pass and  arraylist into a method and I am wondering how this is done...

    I figured it out:
    public function someMethod(someArray:ArrayList){}
    I figured it was the same.
    This is dealing with flex, How ever on the AS side, so its a pure AS question

  • How do I pass an array to a method?

    Hopefully you guys don't mind answering one of my stupid questions :o(
    I have problem passing an array to a method.
    //Here is the code that calls to the method:
    String[] Folder = new String[19];
    int cnt;
    for(cnt=0; cnt<20; cnt++){
    Folder[cnt] = request.getParameter("searchfolder_name" + (cnt + 1));
    ProcessNotify(Folder[cnt]);
    //================================================================
    //Here the the method that is supposed to take in the array
    private void ProcessNotify(String FolderName[]){
    FolderName = new String[19];
    int cnt;
    for(cnt=0; cnt<20; cnt++){
    System.out.println("Folder Name: " + FolderName[cnt]);
    I got an error that says java.lang.String[] can not be applied to java.lang.String
    I thought "String FolderName[]" is an array? Anyway... I'm confused. If you know the answer, plz let me know :o) big thx
    lil

    ProcessNotify(Folder[cnt]);
    Are you trying to pass the whole array or just one piece from it? What you coded, tried to pass just one piece by specifying a subscript. BTW variable cnt is a subscript out of range.
    If you meant to pass the whole array, just use it's name with no subscript.

  • Passing the array in sp

    can be pass the array in sp 2005 sql server

    RSingh()
    Option
    two describes the method which is supported only since SQL Server 2008.
    @skc_chat
    www.projectdmx.com/tsql/sqlarrays.aspx
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • In BADi , How to pass the values between two Method

    Hi Experts,
    We have two methods in BADis. How to pass the value  between two Methods. Can you guys explain me out with one example...
    Thanks & Regards,
    Sivakumar S

    Hi Sivakumar!
    Create a function group.
    Define global data (there is a similiar menu point to jump to the top include).
    Create one or two function modules, with which you can read and write the global data.
    In your BADI methods you can access the global data with help of your function modules. It will stay in memory through the whole transaction.
    Regards,
    Christian

  • How i can pass the value into 1 line

    Hi expert,
    how do i pass all the value for sales document flow item in one line?
    i'm using this function
    CALL FUNCTION 'RV_ORDER_FLOW_INFORMATION'
        EXPORTING
          aufbereitung  = '2'
          belegtyp      = i_del-vbtyp
          comwa         = l_comwa
          nachfolger    = ' '
          vorgaenger    = 'X'
          v_stufen      = '50'
        TABLES
          vbfa_tab      = lt_vbfa
        EXCEPTIONS
          no_vbfa       = 1
          no_vbuk_found = 2
          OTHERS        = 3.
    so now lt_vbfa already got data line by line....
    line 1 : contract : 00010 : 1000000 : 19,000.00
    line 2 : order     : 00010 : 2000000 : 10000.00
    line 3 : delivery : 00010 : 3000000 : 10000.00
    how i can pass the value into 1 line?
    for example :
    contract  | line     | amount     | Order     | line     | amount    | delivery   | line     | amount     |
    1000000 | 00010| 19,000.00 | 2000000 |00010 | 10000.00 | 3000000 | 00010 | 10000.00 |
    Edited by: anuar jusoh on Aug 17, 2009 4:02 AM

    Hi,
    What is requirement for passing the data in a single line ? Do you finally need to append the same in the internal table and pass it in the module ?
    You can create an internal table of type 1000 character and can loop the existing internal table. Then you can append the Work area in a single line and can finally append it to the table.
    DATA : ITAB type standard table of char1000.
    Loop at <existing table>.
    concatenate table work area wa_char100 into Itab_char_1000.
    endloop.
    APPEND itab_char_1000 into itab.
    Hope this helps.
    Thanks,
    Samantak.

  • Passing an array to a method

    This is probably a really simple question - but I'm new to java!
    Object (is that the right word?) Car consists of some information about a car - registration number, engine size etc.
    I have defined an array of objects of type car, and I want to pass the whole thing to a method.
    Specifically...
    I want to pass an inputted search term - the registration number, to a search method to return the number of the element of the array in which that record is stored. Presumably I need to pass the whole array?
    I think what might be causing the problem is the definition of the method:
    private int searchCar(String regNumber, int records, Car carArray[]Also, I don't know how to refer to regNumber as stored in carArray. I'm guessing it's carArray[number].regNumber or something like that.
    Do I need to initialise the whole array before I use it?
    Thanks for any help - I'm clueless!

    You should provide in your class Car ,methods to get (and set if necessary) each of the instance variables associated with a Car object. For example your car class should look something like this:
    public class Car
    private String make, model, colour, regNumber;
    public Car(String a, String b, String c, String d)
    make = a;
    model =b;
    colour = c;
    regNumber = d;
    public String getModel()
    return model;
    public String getMake()
    { return make;
    public string getColour()
    return colour;
    public string getRegNumber()
    return regNumber;
    public string to String()
    return getMake() + " " + getModel() + " " + getColour() + " " + getRegNumber;
    }in your main method
    // create your Array of Car objects and the mthod as below.
    public int searchCar(Car [ ] cars, String reg)
    int found =-1;
    for (int counter = 0; counter < cars.length;  ++ counter)
    if (cars[counter].getRegNumber.equals(reg))
    found = counter;
    break;
    return found;
    }// end searchCarCall this method with something like:
    int index = carSearch(carArray, "SM51 KJL");
    if(index != -1)
    System.out.println("This full details of the requested car are : " + carArray[index].toString());
    else
    System.out.println("This car has not been recorded on our System");
    Haven't compiled this so aplogies for any typing errors.

  • How to pass 1D array into matlab?

    1 had 2 1-D array
    array1 = 1D array signed 32-bit integer numeric
    array2 = 1D array double-precision floating-point numeric
    how do i pass this 2 arrays to matlab script??
    help....as i'm very new to both labview and matlab.
    thks,lyn

    LabVIEW has a Matlab Script Node (Programs >> Mathematics >> Formula) that you can use to interface between the two programs. To pass arrays into the script node do the following:
    1. Right-click on the left edge and select "Add Input"
    2. Give the input a variable name in the termainal that was created.
    3. Right click on the terminal and select Choose Data Type >> Real Vector.
    You can now wire the 1D array to this terminal. You enter your Matlab Commands as text inside the node and you can create outputs the same way to created inputs.

  • Passing an array from one method to another

    I am passing an array from my "load" method and passing it to be displayed in my "display" method in an applet .
    I made the array a class variable (to be able to pass it to the "display" method).
    The applet runs, but nothing seems to be in the array.The screen says applet started, but nothing else. There does not seem to be any CPU activity.
    Trying to debug this, I have tried to paint the screen during the array build. I never figured out how to do this. So I made this a non applet class, put it in debug, and the array seems to load okay.
    Any help is appreciated.
    This is the applet code:
    import java.applet.Applet;
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import java.net.*;
    public class urla extends java.applet.Applet
    int par1;
    int i = 1;
    int j = 20;
    int m = 0;
    int k = 0;
    String arr[] = new String[1000];
    String inputLine;
        public void load() throws Exception
          try
            URL mysite = new URL("http://www.xxxxxxxxxxxxxx.html");
           URLConnection ms = mysite.openConnection();
           BufferedReader in = new BufferedReader(
           new InputStreamReader(
           ms.getInputStream()));
             while ((inputLine = in.readLine()) != null)
               arr[m] = inputLine;
               m++;
           in.close();
          catch (MalformedURLException e)
            k++;
        public void display(Graphics screen)
          screen.drawString("THE FOLLOWING HAVE ADDED THEIR BIOS:",5 ,5);
          for (int i = 0; i < 20; i++);
            j = j + 20;
            screen.drawString("output - "
            + arr, 5, j);
            repaint() ;
    }

    String arr[] = new String[1000];is this typing mistake????? because if u did it in
    program as well i don think it will work.. the tag is
    innnside array lenght... hope iam saying this right!!no, he had the bold form tags (b and /b inside square brackets) in his previous non-code tagged post. He carried it over to this post and they caused an error. I highly doubt that they were in his actual program. Just delete them.
    Message was edited by:
    petes1234

  • How do u pass an object into a method

    I want to create a method getData that takes an object of type Helper and returns an object of the same type.
    how do u pass objects into a method and how do u get objects as returns im a bit confused

    That will just allow you to pass a parameter. If you want to return a helper object
    Helper paramHelper = new Helper();
    Helper someHelper = callMethod(paramHelper);
    public Helper callMethod(Helper hobj) {
        //<some code>
        Helper retHelper = new Helper();
        //<blah, blah>
        return retHelper;

  • How to pass the array as a hidden variable

    hi im trying to pass the list of employees as an array and pass it to servlet as a hidden variable and retrieve the same array in servlet
    can any one help me in this . urgently required.

    I have created only one
    <input type="hidden" name="empName">
    when the user check the check box i want to add all the values in the empName, click the Next page, Again we show some check box i want to add some more names to the hidden value
    When the user click back i want to show which chekboxes user selected.

  • Help needed with passing an array to a method

    here is a small class i'm working on. it's supposed to take each address on an array, and check it for an iis machine, then check a couple of known malformed urls to see if the machine has been patched. my problem is that i can't get the method that does the probing to accept input from the array. it won't even compile, and i'm sure my problem's pretty simple, it's just that i don't quite have afull grasp on java yet. btw, the get/set methods are mandatory, as my instructor refuses to even look at code without them.
    import java.net.*;
    import java.io.*;
    public class PortProbe
         * attribute(s)
         private String[] addressesToBeScanned;
         * accessor methods
         public String[] getAddressesToBeScanned()
              return addressesToBeScanned;
         public void setAddressesToBeScanned(String[] addressesToBeScanned)
              this.addressesToBeScanned = addressesToBeScanned;
         public String getAddressesToBeScanned(int index)
              return addressesToBeScanned[index];
         public void setAddressesToBeScanned(int index, String value)
              addressesToBeScanned[index] = value;
         * helping method to determine the software running on the server
         public void probe80()
              URL myurl = null;
    URLConnection urlConnection = null;
              try
                   myurl = new URL(getAddressesToBeScanned());
              catch (MalformedURLException mal)
                   System.out.println("Exception caught: " + mal);
              try
                   urlConnection = myurl.openConnection();
    catch (IOException ioe)
                   System.out.println("Exception caught: " + ioe);
              System.out.println(urlConnection.getURL());
              System.out.println(urlConnection.getHeaderField("Server"));
         * constructor method(s)
         public PortProbe() //this constructor will initialize each array element individually
              setAddressesToBeScanned(new String[3]);
              setAddressesToBeScanned(0, "http://216.18.80.142/scripts/..%255c..%255c..%255c..%255cwinnt/system32/cmd.exe?/c+dir");
              setAddressesToBeScanned(1, "http://216.18.84.152/scripts/..%255c..%255c..%255c..%255cwinnt/system32/cmd.exe?/c+dir");
              setAddressesToBeScanned(2, "http://216.18.84.161/scripts/..%255c..%255c..%255c..%255cwinnt/system32/cmd.exe?/c+dir");
         * main method
         public static void main(String[] args)
              PortProbe myProbe = new PortProbe();
              for (int i = 0; i < myProbe.addressesToBeScanned.length; i++)
                   myProbe.probe80();
                   i++;
    that's it. can anyone help me out.
    thanks

    thank you all for your responses. the program now compiles and runs successfully. but the results i'm getting aren't the same as what i'm expecting.
    here is the revised code that compiles and runs:
    import java.net.*;
    import java.io.*;
    public class PortProbe
         * attribute(s)
         private String[] addressesToBeScanned;
         * accessor methods
         public String[] getAddressesToBeScanned()
              return addressesToBeScanned;
         public void setAddressesToBeScanned(String[] addressesToBeScanned)
              this.addressesToBeScanned = addressesToBeScanned;
         public String getAddressesToBeScanned(int index)
              return addressesToBeScanned[index];
         public void setAddressesToBeScanned(int index, String value)
              addressesToBeScanned[index] = value;
         * helping method to determine the software running on the server
         public void probe80()
              URL myurl = null;
    URLConnection urlConnection = null;
              try
                   for (int i = 0; i < getAddressesToBeScanned().length; i++)
                        myurl = new URL(getAddressesToBeScanned());
              catch (MalformedURLException mal)
                   System.out.println("Exception caught: " + mal);
              try
                   urlConnection = myurl.openConnection();
    catch (IOException ioe)
                   System.out.println("Exception caught: " + ioe);
              System.out.println(urlConnection.getURL());
              System.out.println(urlConnection.getHeaderField("Server"));
         * constructor method(s)
         public PortProbe() //this constructor will initialize each array element individually
              setAddressesToBeScanned(new String[3]);
              setAddressesToBeScanned(0, "http://216.18.80.142");
              setAddressesToBeScanned(1, "http://137.113.192.101");
              setAddressesToBeScanned(2, "http://216.18.84.161");
         * main method
         public static void main(String[] args)
              PortProbe myProbe = new PortProbe();
              for (int i = 0; i < myProbe.addressesToBeScanned.length; i++)
                   myProbe.probe80();
                   i++;
    please pardon the formatting. there is a constructor that sets the elements in the array. but when i execute the program, this is the output i get:
    http://216.18.84.161
    null
    http://216.18.84.161
    null
    there is nothing else. and it appears that only one of the elements is being called. i don't know where the nulls are coming from. what the program should do (and did do fine before i started with the arrays) is determine the server software running on the machine being probed. there's got to be a mistake in my logic here somewhere, but i'm not experienced enough yet to find where it is.
    thanks again.

  • Passing in arrays into pl/sql process

    I have a package defined as such:
    MYPACKAGE_PKG.ASSIGNDESTINATIONS(p_destinations IN destination_array, p_user IN user_array);
    The two multiselect apex items are
    P103_DESTINATIONS
    P103_USERIDS
    the non-array call would be like this
    MYPACKAGE_PKG.ASSIGNDESTINATIONS(p_destinations => :P103_DESTINATIONS ,
    p_user => :P103_USERIDS);
    I just don't know how to input the arrays...any help would be appreciated.

    Something more like this would work - I put the procedure in the declare b/c i was too lazy to compile one-
    DECLARE
      destination_varray apex_application_global.vc_arr2;
      userid_varray      apex_application_global.vc_arr2;
      PROCEDURE do_something(p_destination IN apex_application_global.vc_arr2,
                             p_users       IN apex_application_global.vc_arr2) IS
      BEGIN
        FOR i IN 1 .. p_destination.COUNT LOOP
          dbms_output.put_line(p_destination(i));
        END LOOP;
        FOR j IN 1 .. p_users.COUNT LOOP
          dbms_output.put_line(p_users(j));
        END LOOP;
      END do_something;
    BEGIN
      destination_varray := apex_util.string_to_table('HAWAII:CHICAGO:NEW YORK');
      userid_varray      := apex_util.string_to_table('JOHN:CHRIS:MIKE');
      do_something(P_DESTINATION => destination_varray, P_USERS => userid_varray);
    END;

  • Passing the OUT parameter in method call after connection

    Hi,
        I have created the rfc connection through SAP.net Connector. Now when i want to show all the data of the particular RFC. i need to provide all the fields name and the tables name in method call.
    In that method call i need to provide one paramet which is of type OUT what is that and what i need to provide in that parameter.
    Can anybody suggest on this.
    I can send the code if u need to understand, what exactly i want.
    Regards,
    +Naren

    Its done i am able to connect.

Maybe you are looking for

  • Importing packages and classes

    Hi, I wanted to know if anyone could tell me how to import a packages under the following circumstances: Say the class i'm importing TO is called SourceClass1, and is in a folder SourceFolder1, and SourceFolder1 is in the folder Root. Let's say I wan

  • Unable to Modify standard program RAZUGA01

    Hello abapers,      I am trying to modify the standard program RAZUGA01.This is using logical database ADA.In this I am adding two new fields .When  I am trying to fetch data for the two fields from database  tables based on the third radio button on

  • Adding a tick box on checkout form to let people opt out of email listing

    hey guys ive set up a shopping site and have added an extra tick box at the bottom of the check out page to let people opt out the emailing listings if they choose to. Problem is I dont think the result of the tick shows up on my orders invoice insid

  • Removing photos from slideshow

    I have some photos in the slide show but one of them I want to remove How do I do that

  • Textarea with Read Only Condition Type

    A have a textarea (database field with Varchar2(4000) with the Read Only Condition Type set to Request != Expression 1. Works fine, except that data presented as a long 1 line text (like a Displayed text) when condition meet (no vertical scrollbar).