Hmm... Array of functions?

Hello. Just curious if something like this is possible at all.
I have a bunch of buttons, which, when clicked, should give their index. Say I wanted to bind an action to that button. Would I have to do a set of if statements or a case statement? Or could I have some sort of array of functions? Mostly wondering for future reference, though it would my code a bit more manageable because I wouldn't have to update my if / case setup each time I added a button..
Can't seem to find anything on google, but if you have some way of doing this without too much hassle, I'd be interested in knowing how.
Thanks much,
Adam

You could make a Map:
Map theMap = new HashMap();
theMap.put(new JButton("5"), new MyActionClass());In actionPerformed of the buttons' ActionListener, do this:
MyActionClass action = (MyActionClass)theMap.get(e.getSource())
action.doAction();
public class MyActionClass
   public void doAction()
       // do whatever processing you like
}MyActionClass can be an inner class of the class where you put the map. Or, you can define an interface that contains doAction, and make sure all values in the Map implement that interface.
There is a name for this "design pattern", but I don't know what it is. If you google "design patterns" or "design patterns java", you might be able to figure it out from there.

Similar Messages

  • How can i declare 2 or more dimension array as function parameter???

    I am new to Objective-C and Cocoa. and now I have a problem.
    I want to send 2 dimension array to function but it cannot compile the error is "array type has incomplete element type" Please help me
    This is my Interface
    + (void) reValueInArray: (int[][] ) labelValue replaceValue: (int) oldValue withValue: (int) newValue;
    and one more question
    How can i get length of array
    1. array that declare as array at first (int a[5] for example)
    2. array that declare as pointer at first (int a* for example)
    Thank you Very much

    Satake wrote:
    a 2 dimension array is just an array of arrays correct?
    No. It isn't.
    so it'd be something like
    - (void)arrayManipulator:(NSArray *)aTwoDimensionArray;
    You're mixing metaphors. The original poster isn't using NSArray, but, rather, C arrays.
    + (void) reValueInArray: (int[][] ) labelValue replaceValue: (int) oldValue withValue: (int) newValue;
    In C, a multi-dimensional array is just one big, single-dimensioned array that uses fixed sizes for all but one of the component arrays to find a particular element. That means that you can't ever do something like:
    There are several workarounds.
    1) Use NSArray, as suggested in the first reply. That will solve this problem and lots more. With NSArray, you really an have arrays inside of arrays.
    2) Treat the array as just a plain old pointer in the function signature, then cast it back to the properly dimensioned array.
    3) Create a true array of arrays in C, using dynamic allocation. More trouble than it's worth.
    4...N) Other options that are probably more trouble than they're worth.

  • Problem in adding "TableLayoutPanel" control array type functionality on windows form dynamically using drag and drop

    Environment: -
     (Application Machine)
    OS Name             : -
    Microsoft Windows 7 Professional/XP SP2/SP3            
    OS Bit Version      : -
    32 Bit                     
    Application Name: - Designer.exe                                  
    IDE                  
        : - Visual Studio 2008                        
    EXE Application development: -
    VB. Net
    Application Type: -
    Application “Designer.exe” was designed in vb6.0 and now, it has been upgraded to Visual Studio 2008 and it works properly.
    Product Description: -
                 We have an application Designer.exe, which is used for designing “Forms”.
    It has menu option with following option like Panel, Text Box, Combo Box, Button etc. We drag any of this menu items and place it to form.
    Requirement: -
    We have
    critical requirement in product. In Designer.exe, we need to align form margin, while we increase or decrease window. And for that we have searched that 
     “TableLayoutPanel” components can be helpful.
    Problem description: -
    Earlier code was in vb6.0, now it has upgraded to Visual Studio 2008. In vb6.0, we have used control array for memory utilization with Combo Box, Group Box, and Text
    Box etc.
    But, for alignment we have to use “TableLayoutPanel”
    control array type functionality on form.
    Code Snippet: - For earlier designing component e.g. Frame
    'Required by the Windows Form Designer
    Public WithEvents Frame1 As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
    Me.components = New System.ComponentModel.Container
    Me.Frame1 = New Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray(Me.components)
    CType(Me.Frame1, System.ComponentModel.ISupportInitialize).BeginInit()
    . Kindly suggest approach for implementing requirement.
    Kindly help us to complete the requirement. I will be really
    thankful for any assistance.

    Hi S.P Singh,
    Welcome to MSDN.
    I am afraid that as Renee Culver said, these forums donot support VB6, you could refer to this thread:
    Where to post your VB 6 questions
    You could consider posting this issue in these forums below:
    These forums do not support Visual Basic 6, however there are many third-party support sites that do. If you have a VB6-related question please visit these popular forums:
    VB Forums
    VB City
    Thanks for your understanding.
    Best Regards,
    Youjun Tang
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to create an array of functions

    normally I use
    repository.getFunctionTemplate(functionName);
    to get a function object.
    Is there a way to get an array of function objects for a function name.
    I am trying to execute multiple functions in the same connection to reduce calls for logging on and off for each call.
    Thanks,
    Aditya Pandit

    Hi Aditya,
    From
    <a href="https://media.sdn.sap.com/javadocs/NW04s/SPS7/jc/com/sap/mw/jco/IFunctionTemplate.html">JavaDoc</a>:
    <i>getFunction
    public JCO.Function getFunction()
    <b>Creates</b> a function object from the template and returns it
    Returns:
    the function created from the template
    </i>
    So, you can reuse function template to create multiple fuctions.
    Best regards, Maksim Rashchynski.

  • Using the Array SetElements function

    Hi All,
    I'm trying to use the Array SetElements function to set a value to specific indices within an initialized array but I cannot figure out what the syntax is for the optional parameter 2. I've tried a whole bunch that seem to make sense but always get an error. Has anyone used this function before who can let me know what the syntax to use is?
    Thanks,
    Nick
    Solved!
    Go to Solution.

    Nick,
    So the syntax for setting all of the elements to a value can simply be written:
    SetElements( myArray,valueToSet )
    To add in the optional parameter 2 and define a range is something like this:
    SetElements( myArray,valueToSet, "[3..6]" )
    The .. operator is analagous to a : in Matlab.
    Good luck,
    Chris

  • Returning arrays from function

    Hi all,
    Can u please guide me in how to return an array from function .
    Is it possible or not ??
    If it is possible please tell me how to declare the function(prototype) that returns string array
    and how to return the string array..
    Thanks in Advance

    Hi all,
    Can u please guide me in how to return an array from
    function .
    Is it possible or not ??
    If it is possible please tell me how to declare the
    function(prototype) that returns string array
    and how to return the string array..
    Thanks in Advance
    public String [] methodReturnsAnArray()
    }

  • Calling array in function

    on frame 1 of root:
    //declare and fill array "mcPopups" with movie clip instance
    names
    var mcPopups = [ "mcAlta1", "mcAlta2", "mcAlta3", "mcAlta4",
    "mcAlta5" ];
    //declare function which goes to hidden label in all movie
    clips from array "mcPopups"
    function turnOff() {
    _root.mcPopups.gotoAndStop("hidden");
    then on the frame for a button in my movie clip mcAlta1 I
    have the code:
    stop();
    //call function "turnOff();"
    close_btn.onRelease = function() {
    _root.turnOff();
    Am I doing something wrong here as it doesn't work ie the
    movie clips should all go to "hidden" when I click my "close_btn"

    >> //declare and fill array "mcPopups" with movie clip
    instance names
    var mcPopups = [ "mcAlta1", "mcAlta2", "mcAlta3", "mcAlta4",
    "mcAlta5" ];
    //declare function which goes to hidden label in all movie
    clips from array
    "mcPopups"
    function turnOff() {
    _root.mcPopups.gotoAndStop("hidden");
    First, you are putting strings in the array, and you probably
    want your
    actual instances. So change the first part to:
    var mcPopups = [mcAlta1, mcAlta2, mcAlta3, mcAlta4, mcAlta5];
    Next, you need to actually iterate through the array, one
    item at a time.
    The array contains MC references - which you can tell to
    gotoAndStop - an
    array does not have a gotoAndStop method so
    array.gotoAndStop() makes no
    sense. Change your function to:
    function turnOff(){
    for(var i = 0; i < mcPopups.length; i++){
    mcPopups
    .gotoAndStop("hidden");
    Lastly, it's recommended to not use _root references as root
    can change.
    Better to do things like this._parent if you need to, but in
    your code just
    removing all _root should be fine.
    Dave -
    Head Developer
    http://www.blurredistinction.com
    Adobe Community Expert
    http://www.adobe.com/communities/experts/

  • Passing pl/sql array to function

    Hi,
    I have a function which takes an array:
    create or replace
    FUNCTION execute_tests(
    leg_keys IN type_leg_key_array)
    RETURN BOOLEAN
    IS
    BEGIN
    leg_key_array is this:
    create or replace
    TYPE type_leg_key_array AS TABLE OF NUMBER(6, 3);
    I would like to test this funtion by passing it some array:
    DECLARE
    LEG_KEYS DEV_SWA30PRE.TYPE_LEG_KEY_ARRAY;
    V_RETURN BOOLEAN;
    BEGIN
    -- LEG_KEYS := NULL;
    v_Return := EXECUTE_TESTS(LEG_KEYS);
    END;
    What is wrong with the snippet above?
    Thanks

    Hi,
    user610868 wrote:
    Hi,
    I have a function which takes an array:
    create or replace
    FUNCTION execute_tests(
    leg_keys IN type_leg_key_array)
    RETURN BOOLEAN
    IS
    BEGIN
    leg_key_array is this:
    create or replace
    TYPE type_leg_key_array AS TABLE OF NUMBER(6, 3);
    I would like to test this funtion by passing it some array:
    DECLARE
    LEG_KEYS DEV_SWA30PRE.TYPE_LEG_KEY_ARRAY;
    V_RETURN BOOLEAN;
    BEGIN
    -- LEG_KEYS := NULL;
    v_Return := EXECUTE_TESTS(LEG_KEYS);
    END;
    What is wrong with the snippet above?Why do you think anything is wrong? Are you getting an error message? Post the complete error message, including line numbers. Does the error occur when you create the type, when you create the function, when you call the function, or someplace else?
    The only errors I see are probably due to how you chose to post it. For example, there is no RETURN or END statement in execute_tests.
    Did you create the type before trying to use it in the function?
    What is DEV_SWA30PRE? Is that a schema? Does that schema also contain the fucntion? Is that who is running the anonymous block? If there are other schemas involved, what are they? What are they doing? What privileges do they have on the type or the function?
    Post a complete test script that people can run to re-create the problem and test their ideas.

  • Passing split array to function

    Anyone know how to pass an array to a function as seperate
    parameters i.e
    _array = [param1,param2,param3]
    functionToCall(param1,param2,param3)
    instead of: functionToCall(_array[0],_array[1],_array[2]);
    of having to go
    var1 = _array[0];
    var2 = _array[1];
    var3= _array[2];
    functionToCall(var1,var2,var3)
    Cheers, burnside

    DCIBurnside,
    > Marco Mind wrote:
    > Can't you just pass the array and indexs as a second
    array?
    That would only work if the desired function is written to
    accept two
    parameters formatted as arrays. DCIBurnside could certainly
    write an
    intermediary function, I suppose; but for that effort, it
    would be just as
    easy to pass in the parameters as already shown:
    functionToCall(_array[0],_array[1],_array[2]);
    Check out the methods of the Fuction class -- in particular
    Function.apply() -- which might be exactly what DCIBurnside
    is looking for.
    David Stiller
    Co-author, ActionScript 3.0 Quick Reference Guide
    http://tinyurl.com/dpsAS3QuickReferenceGuide
    "Luck is the residue of good design."

  • Passing array to function

    I'm trying to use the code below to convert an array of numbers in scientific notation to standard notation. The conversion code itself works, but when trying to pass an array of numbers to the function, it's not receiving anything. Returning the "theArray" array gives me an empty array. What am I doing wrong?
    Here's the applicable code:
    set convertedArray to my deScience(myArray)
    on deScience(theArray)
    set s to 1
    set deScienceArray to {}
    repeat length of theArray times
    set testNumber to my round_truncate(item s of theArray, 6)
    if testNumber contains ".-" then
    set x to the offset of "." in testNumber
    set partOne to characters 1 thru (x) of testNumber as string
    set partTwo to characters (x + 2) thru length of testNumber as string
    set the combinedNumber to partOne & partTwo
    set s to s + 1
    set end of the deScienceArray to testNumber
    end if
    end repeat
    return the deScienceArray
    end deScience

    It would help if you included an example of the input values you're passing in (e.g. are you passing in text objects or real numbers?
    For example, unless your round_truncate() handler takes care of the coercion, the following would likely return different results:
    set myArray to {"1.23456E+5"} -- text object
    set myArray to {1.23456E+5} -- scientific notation
    set myArray to {123456.0} -- real number

  • Passing collection or array to function: shallow copy or not?

    Hello all,
    When passing a collection or an array to a function, what is most used practice to store the given collection in some class member field: reference-copy or a shallow copy?
    I believe it's frustrating to see that there is no real 'standard' about this: some developers copy the whole collection/array, others prefer to simply copy the reference. I tend to agree with the latter group:
    - it's the user's responsibility if he wants the class to use a copied version instead of the 'original' version of the collection/array.
    - most of the times, a copy is not needed, and therefor a shallow copy is pure waste of resources.
    - when nothing is known about the given collection, and there are also no restrictions on the collection to be given, it could be everything: ArrayList? HashSet? SortedSet? AnUnknownImplementation?
    reference copy:
    class ComeClass
        private ArrayList list;
        public SomeClass(ArrayList list) { this.list = list; }
    }shallow copy:
    class ComeClass
        private List list;
        public SomeClass(List list) { this.list = new ArrayList(list); }
    }What are your thoughts about this?

    basically, it's how much access you want to provides.
    public SomeClass(ArrayList list) { this.list = list; }to me, if some other class has a reference to the list object and start modifying it..Someclass internal data (the list) is also modified...thus breaking encapsulation.
    yes, in multithread enviroment, sharing the list(by reference can lead to some hard bug to debug), so it;s much safer to copy (clone) the list. Java does this and provides you the MultiCaster class to make thing easier for you.
    even with synchronization, there are issues you have to look at (such as deadlock)..you can synchronize the list, but can still run into a dead lock
    list is synchronized in class A
    class B have object (that's in list and call the list (wait due to class A synchronization)
    list tries to invoke method of class B, but wait (class B is lock)..thus..deadlock.
    it's a crued exapmle..but i think you get the point.
    the saying is that to make a safer application..declare all you object immutable or restrict access to your private data. Of course, performance wise, we have to comprise sometime.
    example..a list with over 500,000 objects..you might not want to to clone the reference.

  • A normal question regarding array threhold function

    Hi, i try to use the array threshold vi function but faced some problems. Pls see my VI. I can only a threshold result but can't get the other. Hope anyone could help me. Thanks
    Attachments:
    Test1.vi ‏37 KB

    The Threshold 1D Array function is looking for a rising edge across your threshold. Since your first array only contains falling data points the threshold function never finds a valid transition.
    See the LabVIEW help file for more detailed information about the threshold function.
    Christian L
    NI Consulting Services
    Christian Loew, CLA
    Principal Systems Engineer, National Instruments
    Please tip your answer providers with kudos.
    Any attached Code is provided As Is. It has not been tested or validated as a product, for use in a deployed application or system,
    or for use in hazardous environments. You assume all risks for use of the Code and use of the Code is subject
    to the Sample Code License Terms which can be found at: http://ni.com/samplecodelicense

  • Passing Arrays to function

    In my main function, I have created a class array of Players[3]. In the function I pass this array of Players to another class function that may or may not change the size of this array (which I may be doing incorrectly). This is console game of Blackjack hardcoded to 3 players for now, but when one goes out, I would like to reset the amount of Players. Currently in another ckass function, I check to see if they have any money left. If they don't, I create a new Players array with one less than the original then do a System.arraycopy(newArray, 0, originalArray, 0, newSize), then I set newArray back equal to originalArray. Oddly, though, when I leave this function and go back to main, the contents of the original array have changed, but the size is still 3. I would expect it to be one less now.
    Eric

    There is no pass-by-reference in Java. All parameters are passed by value.
    It's just that for object types, what you're passing are references.
    So if you do this:
    public void someMethod(String s) {
      s = "Fred";
    // and in some other method:
    String test = "Barney";
    someMethod(test);
    System.out.println(test);it will print "Barney". You passed a reference in someMethod, then you changed the reference to something else. But all you changed was the local value of that reference. The caller's reference variable value (the variable "test", which has a reference value) is unchanged.

  • Passing 3d arrays to functions in C

    So.. I have a certain char array[8][3][30], declared as ***array, and allocated as the program progresses. I'd like to pass that to an external function, but GCC pukes out warnings that the type case isn't right, and anytime I access it in the function, it segfaults (basically, it doesn't pass properly).
    my function prototype:
    int parse_table(char ***table);
    and code to pass it:
    parse_table(table);
    anyone knowledgable on this?

    tardo wrote:main()
    char ***table;
    parse_table(table);
    use_table(table);
    parse_table(char ***table)
    // read one value from file
    // determine other two values from file input
    // allocate memory depending on values (varies with file input)
    use_table(char ***table)
    // programming homework (probably a tree)
    AHEM, so, I actually bothered to read this properly this time . If this is actually how you have your code structured, this is definitely a problem. Think about this: "table" is of type "char ***", correct? parse_table takes a type "char ***"... you have pass-by-value semantics here. So, essentially, parse_table will receive a COPY of an unitialized memory location. You will then set this local copy to the return of malloc (e.g. something lik table = malloc(/*stuff*/)). However, this is not affecting the table seen in main()! Essentially, you should have something like:
    int main() {
    char ***table = parse_table();
    /* rest of main */
    char *** parse_table() {
    /* Stuff that mallocs into local_table pointer */
    return local_table;
    Where, you malloc the stuff in parse_table, and return that pointer. Alternatively (and painfully), you could do something weird like:
    int main() {
    char ***table;
    parse_table(&table);
    /* rest of main */
    void parse_table(char ****table) { /* Note: four "asterisks", not three! */
    /* malloc evilness in here, with something like (*table) = malloc(/* stuff */) */
    (Don't do this, it's ugly and unnecessary)
    Just to be completely pendantic, check it this sample code I whipped up:
    #include <stdlib>
    #include <stdio>
    void evil_and_wrong(char *f) {
    printf("Memory location we'd allocate to (evil_and_wrong): %un", &f);
    f = (char*)malloc(5*sizeof(char));
    f[0]='p';
    void my_alloc_f(char **f) {
    printf("Memory location we'd allocate to (my_alloc_f): %un", f);
    (*f) = (char*)malloc(5*sizeof(char));
    (*f)[0]='p';
    char * nicer_my_alloc_f() {
    char *local_f = (char*) malloc(5*sizeof(char));
    local_f[0]='p';
    return local_f;
    int main() {
    char *f;
    printf("ACTUAL Memory location: %un", &f);
    evil_and_wrong(f);
    // We won't try anything with "f" here, since it'll segault...
    my_alloc_f(&f);
    printf("Should see: %un", 'p');
    printf("See: %un", f[0]);
    free(f);
    f = nicer_my_alloc_f();
    printf("See: %un", f[0]);
    free(f);
    return 0;
    Look at the outputted memory locations, and think about the fact you're trying to store the address of the allocated memory...

  • Return array in function

    is it possibel to return an array through a function?
    CREATE OR REPLACE function test_bro return varray is...some thing like this!!!!
    Thanx

    ======================================================
    HOW YOU MAKE RECORD SET IN PL/SQL
    ======================================================
    CREATE OR REPLACE PACKAGE dummy AS
    TYPE emprecords IS REF CURSOR;
    PROCEDURE send_records
    (resultset OUT emprecords);
    END dummy;
    CREATE OR REPLACE PACKAGE BODY dummy AS
    PROCEDURE send_records (resultset OUT emprecords) IS
    BEGIN
    OPEN resultset
    FOR
    SELECT *
    FROM emp;
    END send_records;
    END dummy;
    CREATE OR REPLACE PROCEDURE receive_records IS
    emprecs dummy.emprecords;
    v_emp emp%ROWTYPE;
    BEGIN
    dummy.send_records (emprecs);
    LOOP
    EXIT WHEN emprecs%NOTFOUND;
    FETCH emprecs INTO v_emp;
    DBMS_OUTPUT.PUT_LINE (v_emp.empno
    &#0124; &#0124; ' '
    &#0124; &#0124; v_emp.ename
    &#0124; &#0124; ' '
    &#0124; &#0124; v_emp.job
    &#0124; &#0124; ' '
    &#0124; &#0124; v_emp.mgr
    &#0124; &#0124; ' '
    &#0124; &#0124; v_emp.hiredate
    &#0124; &#0124; ' '
    &#0124; &#0124; v_emp.sal
    &#0124; &#0124; ' '
    &#0124; &#0124; v_emp.comm
    &#0124; &#0124; ' '
    &#0124; &#0124; v_emp.deptno);
    END LOOP;
    END receive_records;
    SQL> START receive_records
    Procedure created.
    SQL> SET SERVEROUTPUT ON
    SQL> EXECUTE receive_records
    7369 SMITH CLERK 7902 17-DEC-80 800 20
    7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
    7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
    7566 JONES MANAGER 7839 02-APR-81 2975 20
    7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
    7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
    7782 CLARK MANAGER 7839 09-JUN-81 2450 10
    7788 SCOTT ANALYST 7566 19-APR-87 3000 20
    7839 KING PRESIDENT 17-NOV-81 5000 10
    7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
    7876 ADAMS CLERK 7788 23-MAY-87 1100 20
    7900 JAMES CLERK 7698 03-DEC-81 950 30
    7902 FORD ANALYST 7566 03-DEC-81 3000 20
    7934 MILLER CLERK 7782 23-JAN-82 1300 10
    7934 MILLER CLERK 7782 23-JAN-82 1300 10
    PL/SQL procedure successfully completed.
    null

Maybe you are looking for

  • Distiller 9 issue after a new update to Adobe Acrobat Pro (version 9.3)

    After installing the update, I was asked to reboot my HP Pavilion dv9617nr Notebook Computer (Windows Vista Home Edition). After the reboot, I was given an error message which explained that the ICC Color profiles in Adobe Distiller 9 could not be fo

  • Using a function module i want to create another function module

    Hi all,         My requirement is by using a function module i want to create another function module(if needs modify action should also be done if i need this is for the created function module) and the main thing is that the function module which w

  • Installation old version Photoshop Elements 4.0 Windows 7, IE 4.0 required, what if you have IE 11.0

    I have an old Version of Photoshop Elements 4.0 on CD and used it long time on Win XP, now i use Win 7.1 and need a new installation. Worked till i was asked after Internetexplorer 4.0 was required, and i have IE 11.0 - that is higher - and the Insta

  • Model 3555 and loudspeaker

    On my 2nd bluetooth in 2 weeks, with both of them I have encountered the same problem.  With nearly all incoming or outgoing calls the loudspeaker on the phone comes on whenever I answer (or in the case of outgoing calls, whenever the other person an

  • OM Account Assignment - Inheritance Principle

    Hi We are all ware that the Switch PPOM INHS when off, turns off the account assignemnt inhertitance from Org Unit to Position. But... How can we turn off the Org Unit to Org Unit account assignment inheritance in ECC 6.0 To put it in simpler terms,