Passing array to a method through actionevent? ??

what the hell is this guy on about your asking..
well.. i have a user defined data structures (people)
and i'm creating my first gui, so i have an action caught with
public static void main(String[] args)
int MAX = 1000;
person[] ppl;
ppl = new person[MAX];
public void actionPerformed(ActionEvent e) {
if(e.getSource() == addNewPerson) {
//method call in here to add new person
//but how can i pass the array this far so i can then give it
//to my method, or am i looking at this all wrong?
}if as the comments suggests, i'm calling this all wrong, what way should i implement this? i'm basically getting cannot resolve symbol, pointing to my method which adds a new person (so as i said before, it needs to be passed to the method)

You might want start by reading a few books on OO design first.
What you will probably want to do is have a class which stores the array and extends ActionListener...
public class Gui extends ActionListener {
  Person[] ppl = new Person[100];
  Component comp;
  Button addPersonButton;
  public Gui () {
    comp = new .....;
    addPersonButton = new Button("Add person");
    comp.add(addPersonButton);
    comp.addActionListener(this);
  public static void main(String args[]) {
    Gui gui = new Gui();
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == addPersonButton) {
      doAddPerson();
  pulbic void doAddPerson() {
    ppl[0] = ....
}Hope this shows you a bit more. Not sure how good my design of gui's is though :-/
Rob.

Similar Messages

  • Passing Array to Another Method

    Hello, I created a program with an array in one of the methods. I have been trying to figure out how to correctly pass the array to another method in the same class. I know my problem is in my method delcaration statements. Could someone please show me what I am doing wrong? Please let me know if you have any questions. Thanks for your help.
    import javax.swing.*;
    import java.util.*;
    class Bank1 {
         public static void main(String[] args) {
              Bank1 bank = new Bank1();
              bank.menu();
         //Main Menu that initializes other methods
         public void menu( ) {
              Scanner scanner = new Scanner(System.in);
              System.out.println("Welcome to the bank.  Please choose from the following options:");
              System.out.println("O - Open new account");
              System.out.println("T - Perform transaction on an account");
              System.out.println("Q - Quit program");
              String initial = scanner.next();
              char uInitial = initial.toUpperCase().charAt(0);
              while (uInitial != 'O' && uInitial != 'T' && uInitial != 'Q') {
                   System.out.println("That was an invalid input. Please try again.");
                   System.out.println();
                   initial = scanner.next();
                   uInitial = initial.toUpperCase().charAt(0);
              if (uInitial == 'O') newAccount();
              if (uInitial == 'T') transaction();
         //Method that creates new bank account
         public Person[] newAccount( ) {
              Person[] userData = new Person[1];
              for (int i = 0; i < userData.length; i++) {
                   Scanner scanner1 = new Scanner(System.in);
                   System.out.println("Enter your first and last name:");
                   String name = scanner1.next();
                   Scanner scanner2 = new Scanner(System.in);
                   System.out.println("Enter your address:");
                   String address = scanner2.next();
                   Scanner scanner3 = new Scanner(System.in);
                   System.out.println("Enter your telephone number:");
                   int telephone = scanner3.nextInt();
                   Scanner scanner4 = new Scanner(System.in);
                   System.out.println("Enter an initial balance:");
                   int balance = scanner4.nextInt();
                   int account = i + 578;
                   userData[i] = new Person( );
                   userData.setName               ( name );
                   userData[i].setAddress          ( address );
                   userData[i].setTelephone     ( telephone );
                   userData[i].setBalance          ( balance     );
                   userData[i].setAccount          ( account     );
                   System.out.println();
                   System.out.println("Your bank account number is: " + userData[i].getAccount());
              return userData;
              menu();
         //Method that gives transaction options
         public void transaction(Person userData[] ) {
              System.out.println(userData[0].getBalance());

    Thank you jverd, I was able to get that to work for me.
    I have another basic question about arrarys now. In all of the arrary examples I have seen, the array is populated all at once using a for statement like in my program.
    userData = new Person[50];
    for (int i = 0; i < userData.length; i++) In my program though, I want it to only fill the first array parameter and then go up to the main menu. If the user chooses to add another account, the next spot in the array will be used. Can someone point me in the right direction for doing this?

  • Passing Array to a method

    Hi,
    There is a class MyClass that implements Serializable. I need to create array of this class and pass to a method.
    In java, this can be done as following:
                   MyClass[] myClassVariables=new MyClass[2];
                   MyClass myClassInstance1=new MyClass();
                   MyClass myClassInstance2=new MyClass();
                   myClassVariables[0]=myClassInstance1;
                   myClassVariables[1]=myClassInstance2;
                   String message = getValues(myClassVariables);
    import java.io.Serializable;
    public class MyClass implements Serializable{
    public String getValues(MyClass[] myClassVariables)
    When I implement this in a workflow, I get the following error:
    XPRESS exception:
    com.waveset.util.WavesetException: Couldn't find method getValues(java.lang.String, java.lang.String) in class MyClass
    java.lang.NoSuchMethodException: MyClass.getValues(java.lang.String, java.util.ArrayList)
    Code I am using is as following:
    <set name='myClassInstance1'>
    <new class='com.marathon.MyClass'/>
    </set>
    <set name='myClassInstance2'>
    <new class='com.marathon.MyClass'/>
    </set>
    <set name='myList'>
    <new class='java.util.ArrayList'/>
    </set>
    <set name='myClassVariables'>
    <list>
    <ref>myClassInstance1</ref>
    <ref>myClassInstance2</ref>
    </list>
    </set>
    <set name='message'>
    <invoke name='getValues' class='MyClass'>
    <ref>myClassVariables</ref>
    </invoke>
    </set>
    <ref>message</ref>
    Please help me,
    Thanks

    You might want start by reading a few books on OO design first.
    What you will probably want to do is have a class which stores the array and extends ActionListener...
    public class Gui extends ActionListener {
      Person[] ppl = new Person[100];
      Component comp;
      Button addPersonButton;
      public Gui () {
        comp = new .....;
        addPersonButton = new Button("Add person");
        comp.add(addPersonButton);
        comp.addActionListener(this);
      public static void main(String args[]) {
        Gui gui = new Gui();
      public void actionPerformed(ActionEvent e) {
        if (e.getSource() == addPersonButton) {
          doAddPerson();
      pulbic void doAddPerson() {
        ppl[0] = ....
    }Hope this shows you a bit more. Not sure how good my design of gui's is though :-/
    Rob.

  • Passing array values to methods & Classes

    Hi,
    I have written the following two classes, I want to pass the value from one class - insersortest to the other class what kind of return statement do I do ? I am not sure what does this Comparable object do in this program ? I am trying the program (algorithm specfieid) from one of the Data Structure book.
    import java.io.*;
    import java.lang.*;
    public class Insersortest
    public static void main(String args[]) throws IOException
    Insersort ghl = new Insersort();
              Comparable a[] = {1, 3, 5, 9, 1};          
                   System.out.println("Detecting duplicates"+ ghl.insertA(a));               
    -=-=-=-
    class Insersort
    public static int insertA( Comparable [ ] a )
    for( int p = 1; p < a.length; p++ )
    Comparable tmp = a[ p ];
    int j = p;
    for( ; j > 0 && tmp.compareTo( a[ j - 1 ] ) < 0; j-- )
    a[ j ] = a[ j - 1 ];
    a[ j ] = tmp;
    Could somebody provide their view please.
    PK

    You return arrays just like any object:
    public Object[] getArray()Comparable is an interface. Any object that implements Comparable (and can therefore be stored in a Comparable's reference) is guarenteed to have a compareTo method.
    Does that help?

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How can i pass array as argument in magento api method calling using sudzc API in iphone Native APP

    0down votefavorite
    I am implementing magento standard api method in native iphone app. I use webservice generated by sudzc. To call method I use:
    [service call:self action:@selector(callHandler:) sessionId:@" " resourcePath:@" " args:@""];
    When I used methods e.g. cart.info or product.info in which I have to pass one parameter; it gives valid response. But when I used method e.g. cart_product.add in which I have to pass an argument as value of array it gives error
    SQLSTATE[42000]: Syntax error or access violation:
        1064 You have an error in your SQL syntax;
        check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
    I have tested in SOAP UI also. There also it gives me same error. But same method works in PHP file. Even I tried by creating same soap request which I created using JavaScript but still it doesn't work.
    Can anyone help me to pass array as a parameter using sudzc api to call magento web services?

    There is an error in your SQL.

  • Getting Type Mismatch Error while passing Array of Interfaces from C#(VSTO) to VBA through IDispatch interface

    Hi,
    I am facing issues like Type Mismatch while passing Array of interfaces from .NET  to VBA and vice versa using VSTO technology.
    My requirement is that ComInterfaceType needs to be InterfaceIsIDispatch.
    My Interface definition is somewhat like this
        [ComVisible(true)]
        [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
        [Guid("AAF48FBC-52B6-4179-A8D2-944D7FBF264E")]
        public interface IInterface1
            [DispId(0)]
            IInterface2[] GetObj();
            [DispId(1)]
            void SetObj(ref IInterface2[] obj);
        [ComVisible(true)]
        [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
        [Guid("CDC06E1D-FE8C-477E-97F1-604B73EF868F")]
        public interface IInterface2
    IF i am passing array of above interface (created in C#.Net) to VBA using GetObj API,i am getting type mismatch error in VBA while assigning the value to variable in VBA.Even assigning to variant type variable gives TypeMismatch.
    Also while passing Array of interfaces from VBA using SetObj API,excel crashes and sometimes it says method doesn't exists.
    Kindly provide some assistance regarding the same.
    Thanks

    Hi,
    I am facing issues like Type Mismatch while passing Array of interfaces from .NET  to VBA and vice versa using VSTO technology.
    My requirement is that ComInterfaceType needs to be InterfaceIsIDispatch.
    My Interface definition is somewhat like this
        [ComVisible(true)]
        [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
        [Guid("AAF48FBC-52B6-4179-A8D2-944D7FBF264E")]
        public interface IInterface1
            [DispId(0)]
            IInterface2[] GetObj();
            [DispId(1)]
            void SetObj(ref IInterface2[] obj);
        [ComVisible(true)]
        [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
        [Guid("CDC06E1D-FE8C-477E-97F1-604B73EF868F")]
        public interface IInterface2
    IF i am passing array of above interface (created in C#.Net) to VBA using GetObj API,i am getting type mismatch error in VBA while assigning the value to variable in VBA.Even assigning to variant type variable gives TypeMismatch.
    Also while passing Array of interfaces from VBA using SetObj API,excel crashes and sometimes it says method doesn't exists.
    Kindly provide some assistance regarding the same.
    Thanks

  • Passing array from JS to method of applet

    There is unable in IE pass array of values from javascript to method of applet, but in Mozilla it's working fine. In IE i have got exception:
    Exception:
    java.lang.Exception: setTest{0} :no such method exists
         at sun.plugin.com.JavaClass.getMethod1(Unknown Source)
         at sun.plugin.com.JavaClass.getDispatcher(Unknown Source)
         at sun.plugin.com.DispatchImpl.invokeImpl(Unknown Source)
         at sun.plugin.com.DispatchImpl$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.plugin.com.DispatchImpl.invoke(Unknown Source)
    java.lang.Exception: java.lang.Exception: setTest{0} :no such method exists
         at sun.plugin.com.DispatchImpl.invokeImpl(Unknown Source)
         at sun.plugin.com.DispatchImpl$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.plugin.com.DispatchImpl.invoke(Unknown Source)
    JavaScript code:
    var testArr=[];
        testArr[0]=1;
        testArr[1]=2;
        testArr[2]=3;
        document.sync.setTest(testArr);
    Applet method:
    public void setTest(Object[] test){
            System.out.println("Test "+test.length);
            for (Object o: test){
                System.out.println(o.toString());
        }How do passing in IE?

    yes, MAYSCRIPT just allow to call methods. but as i know it's unable to pass simply array from js to applet and from applet to js. so i convert array of values to String and in applet i use StringTokenizer to parsing. Thanks. ;)

  • Passing hard coded array to a method

    how to passing hard coded array to a method
    like method1("eee","eoe","eee",.....)
    which should populate a array of strings (say arr[]) for the method
    what can be done??

    or if you're using Java 5.0 declare the method aspublic void method(String... array) {
    }

  • 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 arrays to methods?

    Hi all,
    Thanks to most of the main contributors in this forum nearly all of my major hurdles in transitioning from proc-C to Cocoa have been overcome. However, while I was shown how to use NSMutableArray in conjunction with NSDictionary to do pretty much the same job as a C-style multi-dimensional array, dictionaries aren't always the perfect solution in every situation. So, let's suppose I wanted to construct a pure Cocoa facsimile of a C-style [4][x] array like this...
    NSArray *replicaArray = [NSArray arrayWithObjects:
    [NSNull null], // index 0 (unused)
    [NSMutableArray array], // index 1
    [NSMutableArray array], // index 2
    [NSMutableArray array],nil]; // index 3
    I threw in an NSNull as the first array object because (whenever possible) I adopted the habit of leaving row0 and column0 of multidimensional arrays unused to make for more natural, readable iteration ops and stuff. The above code works perfectly well, but with 4-5 different arrays in the same proc-C apps I often had to pass them to common functions (to handle things like bubble-sorting etc.) like the one below:
    void bubbleSortSimpleArray (short arry[ ], short numsToSort)
    short ctr,loopCtr,storeValue;
    for (loopCtr = 1; loopCtr <= numsToSort; loopCtr++)
    ctr = 1;
    while (ctr < numsToSort)
    if (arry[ctr] > arry[ctr+1])
    storeValue = arry[ctr+1];
    arry[ctr+1] = arry[ctr];
    arry[ctr] = storeValue;
    ++ctr;
    Of course, thanks to the advantages of Cocoa this entire code block can be replaced in just a couple lines with 'sortUsingSelector'. Sorry for the lengthy outline in attempting to describe my problem as clearly as possible , but (finally) _is it possible to pass arrays to methods_ in our Cocoa code in a similar way? I was thinking something along the lines of:
    - (void)doMoreProcessing:(id)array
    //do some other common stuff on my array(s) here...
    That'd simplify converting some of my old code and be a real bonus for me, but I haven't been able to find any reference about this on the net so far, and experimenting with my code hasn't provided me with any answers yet, either... Any guidance on this would be very much appreciated!
    Thanks in advance.
    Ernie

    Hi Bang A. Lore,
    Thanks for your input but I've got it figured out now However, while you quite correctly say:
    Pointers work the same way as they do in C.
    the cause of my problems wasn't a lack of understanding of pointers, but by the syntax differences between proc-C and obj-C. I'm well aware of the fact that the name of a passed array is just a pointer to its address in memory of course, but attempting to use a mandatory 'C' style header declaration along the lines of:
    - (void)test2DArray:(NSMutableArray*)array[][];
    just kept giving me parse errors, as did any attempt to use square brackets in the implementation file. While 'C' insists on using them, I found (after some more experimentation) that obj-C will quite happily accept:
    - (void)test2DArray:(NSMutableArray*)array;
    ...or the even simpler...
    - (void)test2DArray:(id)array;
    Also pleasantly surprised to find that Cocoa doesn't seem to give a hoot whether the (array) object you pass it is flat OR multidimensional -- whereas 'C' insists you even provide the called function with the number of rows contained in a multi-subscripted array -- which often meant I had to include two versions of many functions containing identical code, depending on whether they were called by 1D or 2D arrays.
    Once I hit on the idea of omitting the square brackets entirely (just to stop the darned parse errors and see what would happen out of curiosity), the problem just went away.
    Thanks once again. Appreciate it!

  • Passing paramaters to a method

    I am passing objects to another method.
    I do some changes to them and expect the changed objects to be available in the calling method ( since they are supposedely passed by reference) when the execution is returned to it. However, I don't get the changed objects but rather the old ones, before the method execution.
    Can someone explain?
    Thanks,
    Boris.

    This is an extremely common question. A search through this forum would be very useful to you.
    Java does not pass-by-reference in the same way C/C++ do. When you pass an object to a method, you can change the contents of the object using its methods and see the changes after the method completes in the calling method. In this way Java is similar to C/C++.
    However, you cannot change an object to equal another object or a new object inside a method and expect the changes to be visible after the method completes in the calling method.
    Here is an example.
    This will show changes and the line "String" would be printed.
      StringBuffer sb = new StringBuffer();
      method(sb);
      System.out.println(sb);
      public void method(StringBuffer buf) {
        buf.append("String");
      }However, this would not show changes and the line "Old String would be printed:
      String string = "Old String";
      method(string);
      System.out.println(string);
      public void method(String string) {
        string = "New String";
        // string.concat("New String) would also fail to work

  • Passing parameters to a method

    I am passing objects to another method.
    I do some changes to them and expect the changed objects to be available in the calling method ( since they are supposedely passed by reference) when the execution is returned to it. However, I don't get the changed objects but rather the old ones, before the method execution.
    Can someone explain?
    Thanks,
    Boris.

    I do some changes to them and expect the changed
    objects to be available in the calling methodIf you modify an object passed to a method, then the changes made to that object will be visible as soon as they are made.
    If you change the parameter so that it references some other object, this will NOT be seen in the calling method.
    You can "fake" it by putting the object in question in an array and passing the array. Better though is to just not expect methods to be able to change references they are passed to point at some other object.

  • Passing information to a method

    Im going through the java tutorial about passing information to a method
    and i am presented with this code.
    class RGBColor {
        public int red, green, blue;
    class Pen {
        int redValue, greenValue, blueValue;
        void getRGBColor(RGBColor aColor) {// is aColor a reference for RGBColor ?
            aColor.red = redValue; //is aColor then used to access the variables of RGBColor ?
            aColor.green = greenValue;// Are these values being initialised here
            aColor.blue = blueValue;
    RGBColor penColor = new RGBColor();// we are creating an instance of RGBColor called penColor
    pen.getRGBColor(penColor);// this is the bit i dont understand where the heck did pen.getRGBColor come from, i cant see anywhere where pen has been declared ..... or instantiated
    System.out.println("red = " + penColor.red +
                       ", green = " + penColor.green +
                       ", blue = " + penColor.blue);The follwoing is what it says in the java tutorial about the code
    The modifications made to the RGBColor object within the getRGBColor method affect the object created in the calling sequence because the names penColor (in the calling sequence) and aColor (in the getRGBColor method) refer to the same object.
    any guidance would be great

    Directly above the code that you don't understand is
    o A definition for a class Pen.
    o something called "pen" is probably declared somewhere like this:
    Pen pen;
    or
    Pen pen = new Pen(....);
    or
    Pen pen = something.getPen();
    So pen is an instance of Pen, and you can invoke the methods defined in class Pen, thus
    pen.getRGBColor(....);

  • Filling empty java array in C method

    Hi everyone,
    I'm passing to a C method an empty byte array from the Java Side. I want the C method to fill the Java byte array and return it at the end of the method to the java side.
    in the Java side, I have my byte array :
    byte[] myArray = null;
    then I'm passing the array to the C method as
    myMethod(myArray)
    in the C method I'M trying to access the array as follow :
    myMethod(jbyteArray myArray)
    jbyte* tab = *env)->GetByteArrayElements(env, myArray, 0);
    I'm getting an error at runtime. Can somebody help me with that issue please ? Thanks
    Sebastien

    You are not passing a byte array, you are passing null.
    If you want to pass a byte array you first have to create it using the new operator:
    byte[] myArray = new byte[theSizeOfTheArray];
    myMethod(myArray);If you want the JNI code to create the array, that is fine also, but in that case the native method would probably have to return the array instead of void.

Maybe you are looking for

  • How do I move all files from one user account into another on my Mac?

    So I am a new Mac owner (MacBook Pro, OS X 10.9.4) so I don't know about a lot of the tricks and settings I can use yet. I just used the Migration Assistant last night to transfer files from my old laptop onto my Mac, but I've already been using the

  • Custom Field In User Registration Portal

    Hello, Is there a way I can add a custom field during user password registration in FIM 2010 R2? I want to have a field to set a User PIN where user can enter a value and it can be used in future by user or helpdesk when user is not able to answer ot

  • Lumia 900 bluetooth problem

    have had the 900 for almost a year works great until today , it pairs with anything my car kenwood dnx60 all of my ear bt but when i make or receive a call i cant hear it in my ear or through the car speakers when its paired to the car. Ive check all

  • The Open GL acceleration has stopped working

    Hi, I would really appreciate some guidance on this. The other day I ran updates to 10.0.5 adding a couple of bug fixers, nothing unusual. However when I opened After Effects CS6 and Premiere Pro CS6 it told me that the system had reverted back to us

  • Saving original and modified versions

    Hey all, Can someone tell me how to stop iphoto from saving both an original and modified version of my photos? It's very confusing when I try to access the photos to upload onto flickr, or to burn dvds etc. I can't believe how much time I've wasted