Class object in toString() form

Hi there folks!
Simple question...
How can I obtain sttring representation of this vending machine using the standard toString convention of Java?
Thanks a lot for any help! : )
import java.lang.*;
import java.util.*;
import type.lang.*;
public class VendingMachine
    //VendingMachine constructor.
     public VendingMachine()
  // Adds items into VendingMachine collection.
     public void addItemType(ItemType item)
     ItemType aitem = item;
     String price  = aitem.getPrice()+"";
     int index = price.length();
     char check = price.charAt(index-1);
     if (list.size() == MAX_PERM)
     throw new RuntimeException("Maximum permitted amount reached");
    else  if ( check == '5' || check == '0')
     list.add(aitem);
    else
     throw new IncompatibleItemException("Price not allowed!");
    } //END of addItemType()
    //Accepts only coins of denomination 200, 100, 10 & 5.
    public void depositCoin(int cents)
    int acents = cents;
    String scents = ""+acents;
    StringTokenizer st = new StringTokenizer(DENOMINATION, ",");
    for(;st.hasMoreTokens();)
     listin.add(st.nextToken());
     if(listin.contains(scents))
     { depositamount += acents;} else
          throw new IllegalArgumentException("Not valid coin");
    }   //END depositCoin()
     public int getDepositAmount()
    return depositamount;
   } //END getDepositAmount()
     public int getBankAmount()
   int finalbank = bankamount + collected ;
    return finalbank;
   }//END of getBankAmount()
   public int clearMoney()
     if(bankamount < BANKAMOUNT)
          collected = 0;
     }else{
    collected = bankamount - BANKAMOUNT;
    return collected;
   }//END of clearMoney()
   //re-stocks a particular item
     public void reStock(int which, int qty)
  ((ItemType)list.get(which)).addItems(qty);
  } //END restock()
      //dispenses selected item, checks for sufficient amount deposited
      //checks for valid choice, checks for current stock available.
    public int selectItem(int which)
    selecteditem = which;   
    if(((ItemType)list.get(selecteditem)).getQuantity() < ONE)
    throw new OutOfStockException("Item out of Stock!");
    else if (depositamount < ((ItemType)list.get(selecteditem)).getPrice())
    throw new InsufficientPaymentException("Not enough payment!");
    else
    ((ItemType)list.get(selecteditem)).getItem();
   int change = depositamount - ((ItemType)list.get(selecteditem)).getPrice();
    return change;
  } //END selectItem()
    public void removeItemType(int which)
   list.remove(which);
  } //END removeItemType()
  //return items in formatted string
  public String showItems()
   StringBuffer buf = new StringBuffer();
   buf.append("Vending Machine Selection"+"\n");
   buf.append("========================="+"\n");
   if (list.size() > 0)
   for (int i = 0; i < list.size(); i++)
    buf.append(i + " for " + ((ItemType) list.get(i)).getName() + "\n ");  
  } else
    buf.append("Machine not Stocked."+"\n");
    return  buf.toString();
  public String toString()
       //***How can I represent object of this class as toString()?***
   private static final int ONE = 1;
   public static final int BANKAMOUNT = 2000;
   private final int MAX_PERM = 200; // maximum capacity of vending machine.
   private static final String DENOMINATION = "200,100,25,10,5";
   public int depositamount;//amount added into vending machine
   public int selecteditem;//item selected for dispensing
   public int collected;
   public int bankamount;
   private ArrayList list = new ArrayList(); //Collection of ItemType object reference
   private ArrayList listin = new ArrayList();//Collection of coin denomination permitted

You can make toString() return any String you want. Whatever makes sense.
Usually, I do this.
public String toString() {
   StringBuffer sb = new StringBuffer("VendingMachine");
   sb.append("[attr1=").append(attr1);
   sb.append("attr2,=").append(attr2);
   return sb.append("]").toString();
}Cuz that is typical of the AWT/Swing classes, but it doesn't matter, except that it usually in some way identifies the state of the object.

Similar Messages

  • Problem with Dynamically accessing EJB Class objects in WL 7.0 SP1

    I am trying to build a component which has the ability to instantiate and execute
    an known EJB method on the fly.
    I have managed to build the component but when I try and execute it I get a ClassNotFoundException.
    I know that the EJB I am trying to invoke is deployed and available on the server,
    as I can see it in the console, I also seen to have been able to get the remote
    interface of the object, my problem occurs when I try and access the class object
    so I can perform a create on the object and then execute my method
    The code I have written is below:
    private Object getRemoteObject(Context pCtx, String pJNDIName, String pHomeBean)
    throws Exception {
         String homeCreate = "create";
         Class []homeCreateParam = { };
         Object []homeCreateParamValues = {};           
    try {  
    //This call seems to work and doesn't throw an exception     
    Object home = pCtx.lookup(pJNDIName);
    //However this call throws a java.lang.ClassNotFoundException
    Class homeBean = Class.forName(pHomeBean);
    Method homeCreateMethod = homeBean.getMethod(homeCreate,homeCreateParam);
    return homeCreateMethod.invoke(home, homeCreateParamValues);
    } catch (NamingException ne) {             
    logStandardErrorMessage("The client was unable to lookup the EJBHome.
    Please make sure ");
    logStandardErrorMessage("that you have deployed the ejb with the JNDI
    name "+pJNDIName+" on the WebLogic server ");
    throw ne;
    } catch (Exception e) {
    logStandardErrorMessage(e.toString());
    throw e;     
    Any advice would be really appreciated, I'm fast running out of ideas, I suspect
    it has something to do with the class loader but I'm not sure how to resolve it
    Regards
    Jo Corless

    Hello Joanne,
    Congratulations! I'm very happy that you've managed to fix your problem. It's
    always essential to understand how to package applications when deploying on BEA
    WebLogic. Usually, by throwing everything into an EAR file solves just about all
    the class loader problems. :-) Let us know if you have any further problems that
    we can assist you with.
    Best regards,
    Ryan LeCompte
    [email protected]
    http://www.louisiana.edu/~rml7669
    "Joanne Corless" <[email protected]> wrote:
    >
    >
    I've fixed it!!!!!!!!
    Thanks to everyone who gave me help!!!!
    The class loader was the culprit which is what I suspected all along.
    As soon
    as I put the 2 jar files I was using into an EAR file the problem went
    away!!!!!
    Thanks again
    Jo Corless
    "Ryan LeCompte" <[email protected]> wrote:
    Hello Joanne,
    As Mr. Woollen mentioned, I also believe it's a problem with the class
    loader.
    You need to be careful how you arrange your EJBs, because WebLogic has
    a specific
    method in which it loads classes in an EAR, JAR, and WAR file(s). Please
    refer
    to http://dev2dev.bea.com/articles/musser.jsp for more information about
    BEA WebLogic
    class loading mechanisms and caveats. Also, try printing out the various
    methods
    that are available on the object that was returned to you via reflection.
    For
    example, use the getMethods() method, which returns an array of Method
    objects
    that you can subsequently cycle through and print out the various method
    names.
    This way you can discover if the class found/returned to you is indeed
    the one
    you intend to locate.
    Hope this helps,
    Ryan LeCompte
    [email protected]
    http://www.louisiana.edu/~rml7669
    Rob Woollen <[email protected]> wrote:
    I believe the issue is the home interface class for this EJB is not
    available in the class loader which is doing the reflection.
    If you do:
    getClass().getClassLoader().loadClass(homeInterfaceClassName)
    I suspect it will fail. Reflection still requires that the class be
    loadable.
    -- Rob
    Joanne Corless wrote:
    Hi Slava,
    If I make my code look like you describe below I get a compliationerror telling
    me that
    home.getMethod() is not recognised (no such method)
    If I change it slightly and use
    Method homeCreateMethod =
    home.getClass().getMethod(homeCreate,homeCreateParam);
    The code will compile OK but when executed it still throws a NoSuchMethodException
    Any ideas ?
    Thanks for your help so far
    Regards
    Jo Corless
    Your code should look like
    Object home = pCtx.lookup(pJNDIName);
    Method homeCreateMethod =
    home.getMethod(homeCreate,homeCreateParam);
    return homeCreateMethod.invoke(home, homeCreateParamValues);
    Regards,
    Slava Imeshev
    "Joanne Corless" <[email protected]> wrote in message
    news:[email protected]...
    Hi Ryan,
    I also wanted to mention that if you do a "header search" in this
    particular
    newsgroup
    with the search query as "reflection", you will see many previousmessages
    regarding
    reflection and EJBs. I believe you could learn a lot from thedifficulties
    that
    others have faced and solved.I tried that and although there was a number of similar cases noneof them
    actually
    seem to fix my issue. Thanks for the suggestion though
    Are the EJBs that you are trying to access accessible via your
    system
    classpath?
    Try to avoid having them accessible via the main system classpath,and
    only bundle
    them in your appropriate EJB jar files (contained in an EAR file,for
    example).Maybe I should have laid the problem out a little clearer.
    I have a number of EJB's bundled up in a JAR file which is hot deployedto
    the
    server. Within this first JAR file is an EJB (SSB) component that
    needs
    to
    be
    able to invoke a known method on another EJB. This second EJB may
    or
    may
    not be
    within the first JAR file but it also will be hot deployed.
    The component trying to invoke the method on the 2nd EJB has to
    be
    able to
    create
    an instance of the 2nd EJB without actually knowing anything bar
    a
    JNDI
    Name which
    is passed in at runtime.
    I can get as far as doing the
    Object home = pCtx.lookup(pJNDIName);
    This returned a class with the name
    "com.csc.edc.projects.allders.httppostoffice.postman.PostmanBean_mp8qy2_Home
    Impl_WLStub"
    My problem seems to occur when I try and invoke the create method
    Method homeCreate = home.getClass().getMethod("create", new Class[0]);
    My code throws a java.lang.NoSuchMethodException at this point so
    I
    am
    unable
    to progress to the next step of :
    Object bean = homeCreate.invoke(home, null);
    So I can return the instantiated bean back to the calling client.
    Why am I getting the NoSuchMethodException, is is because I am gettinga
    stub
    back rather than the home interface and if so how do I get the truehome
    interface
    from the bean
    Thanks in advance
    Jo Corless

  • How to automate the creation of Function Module & Class Object (SE24)

    Experts,
    I have the requirement to automate the creation of any type of programs: ie function module (like how we normally create in SE37 together with the parameters), class object (like how we normally create in SE24 together with attribute & method), normal report (like how we did in SE38), module pool and so on.
    For example. I backuped my program into a flat file (the entire source code in txt formal or HTML) through a download program and I need to upload back this flat file into another installation of SAP.
    Does SAP provide any predefined FM to cater for the above cases or better still, does anyone know of any upload program which I can use for the above requirement.
    Thanks in advance.

    Hi Kris, I can't use the transport system as these are 2 separate SAP installation in a different place. The requirement came in the form of creation of program to be able to generate FM/Class/Report on the go.

  • Class object from XML.

    Hi.
    I want to create DataGrid with itemReneder for each column.
    This is inline generated itemRenderer:
    DataGridColumn.itemRenderer = new
    ClassFactory(MyCustomClass);
    // MyCustomClass - it manually generated class which contains
    some form items(TextInput, Combox..e.t.c.)
    I want to consturct ItemRenderer dynamicly. For this i need
    to create Class object and send it to itemRenderer:
    var component:DynamicFormClass = new DynamicFormClass();
    var newComponent:Class =
    component.someMethodWhichWillCreateForm(configData); // - this will
    return Class which will generate form items that described in
    configData
    DatagridColumn.itemRenderer = new ClassFactory(newComponent);
    This code is how i see solvetion of this problem, but this
    doesnt work.
    I really don't know how it to create and will be very
    thankful for any dicision and answers how to make it.
    Thank you.

    "Dmitry Sergeev" <[email protected]> wrote
    in message
    news:g8eghj$881$[email protected]..
    > Hi.
    > I want to create DataGrid with itemReneder for each
    column.
    >
    > This is inline generated itemRenderer:
    > DataGridColumn.itemRenderer = new
    ClassFactory(MyCustomClass);
    > // MyCustomClass - it manually generated class which
    contains some form
    > items(TextInput, Combox..e.t.c.)
    >
    > I want to consturct ItemRenderer dynamicly. For this i
    need to create
    > Class
    > object and send it to itemRenderer:
    > var component:DynamicFormClass = new DynamicFormClass();
    > var newComponent:Class =
    > component.someMethodWhichWillCreateForm(configData);
    > // - this will return Class which will generate form
    items that described
    > in
    > configData
    > DatagridColumn.itemRenderer = new
    ClassFactory(newComponent);
    Use getDefinitionByName and ClassFactory to dynamically
    create your class.
    Just be sure that you actually have at least one "hard"
    reference to each
    class you intend to use, or the class might not get compiled
    into your swf.
    Here's a full write-up of how to do that:
    http://www.paulofierro.com/archives/520/
    HTH;
    Amy

  • Forms 9i - Compilation on Linux - property class,VA from base form

    Hi all,
    We have got around 400 forms converted from forms 6i to forms 9i.
    We have subclassed property classes and visual attributes to most of the forms from the base form (say std.fmb).
    Now , we need them to be compiled on Unix / Linux for the first time.
    While compiling, we get message "FRM-18108: Failed to load the following objects." but the .fmx file is created.
    We understand that this is due to the reference of the source form as STD and not as std. How to correct this problem but without renaming the form std to STD or having one more copy of that as STD.fmb.
    Please suggest

    Hugo,
    the Forms module can be compiled without having to compile oracle.forms.demos.ProgressBarPJC. Just have the implementation class reference in teh Forms module and use the same jar file.
    Frank

  • Class object path?

    Hi
    I have created my own class. Lets say I called it
    vector
    I need refference to object this class, but after refering to
    this object it retuns
    [object Object] insted of full path
    I want my class object acting execty as MC class objects.
    What should I add to my class?
    I need this, becouse I want keep reference to object in array
    to loop through then, delete objects and knew witch objest is
    "active" at the moment
    example:

    micahkoga,
    > If you would like your class to behave like a movie clip
    > then your class must extend the movieclip class:
    As I understand it, the panell is only looking for an
    understanding of
    object references; I hear no intention (or need) to extend
    MovieClip.
    panell,
    The reason your trace shows [object Object] is because that
    string --
    "[object Object]" -- is the default toString() output of all
    objects. If
    you want your object's trace() output to be something else,
    you'll have to
    give it a toString() method.
    Out of curiosity, why do you need the object to return its
    reference
    path? If you already know the path (which, of course, you do
    -- because you
    traced the object), then you already know it.
    David
    stiller (at) quip (dot) net
    Dev essays:
    http://www.quip.net/blog/
    "Luck is the residue of good design."

  • Can't create object types in forms 10

    Hello,
    I am trying to use object types in forms 10.
    I have already created successfully two object types and also corresponding object views.
    With one object type A everything works fine in form. But with the other object type B it doesn't.
    I am calling the constructor of object B and after the constructor finshed, forms says that there is a numeric or value error.
    Well, by nbow I have reduced attributes from object B so that they are identical to object A (which works). But still get the same error or if I use a different constructor I get NULL as a return value. I tested the constructors with test script in the database directly and viola - the constructor are working fine.
    Only if I use the constructors in forms environment they fail.
    Any ideas why this might happen?
    Thank you
    Matthias
    Well, I fear to use the object types in my next project cause if I run into trouble if the object types are so easy with less code, what else might happen if they are filled up with much more code?

    Hello again,
    I have tried again and still get the exception.
    Now I provide the code. Perhaps someone can see, why this exceptioon occurs.
    In the database I coded the following:
    create or replace type GenericObject as object
    -- Attributes
    iVersion VARCHAR2(8),
    -- Member functions and procedures
    MEMBER FUNCTION toString(SELF IN OUT NOCOPY GenericObject) RETURN VARCHAR2,
    FINAL MEMBER FUNCTION toString001(SELF IN OUT NOCOPY GenericObject) RETURN VARCHAR2,
    NOT INSTANTIABLE MEMBER PROCEDURE log(pLogger IN OUT MyLogger)
    ) NOT INSTANTIABLE NOT FINAL
    create or replace type body GenericObject is
    -- Member procedures and functions
    MEMBER FUNCTION toString(SELF IN OUT NOCOPY GenericObject) RETURN VARCHAR2 IS
    BEGIN
    RETURN SELF.toString001();
    END;
    FINAL MEMBER FUNCTION toString001(SELF IN OUT NOCOPY GenericObject) RETURN VARCHAR2 IS
    BEGIN
    RETURN 'GenericObject(' || SELF.iVersion || ')';
    END;
    end;
    create or replace type MyTestA UNDER GenericObject
    -- Attributes
    iPk VARCHAR2(16),
    iName VARCHAR2(100),
    iDCN NUMBER,
    -- constructor
    CONSTRUCTOR FUNCTION MyTestA(pName VARCHAR2, pDummy INTEGER) RETURN SELF AS RESULT,
    CONSTRUCTOR FUNCTION MyTestA(pPk VARCHAR2) RETURN SELF AS RESULT,
    STATIC FUNCTION mycreate(pName VARCHAR2) RETURN MyTestA,
    -- Member functions and procedures
    OVERRIDING MEMBER FUNCTION toString(SELF IN OUT NOCOPY MyTestA) RETURN VARCHAR2,
    FINAL MEMBER FUNCTION toString002(SELF IN OUT NOCOPY MyTestA) RETURN VARCHAR2,
    OVERRIDING MEMBER PROCEDURE log(SELF IN OUT NOCOPY MyTestA, pLogger IN OUT MyLogger)
    ) NOT FINAL
    create or replace type body MyTestA is
    -- constructors
    CONSTRUCTOR FUNCTION MyTestA(pName VARCHAR2, pDummy INTEGER) RETURN SELF AS RESULT IS
    BEGIN
    SELF.iVersion := '1.1';
    SELF.iPk := 1;
    SELF.iName := pName;
    SELF.iDCN := 1;
    RETURN;
    END;
    CONSTRUCTOR FUNCTION MyTestA(pPk VARCHAR2) RETURN SELF AS RESULT IS
    BEGIN
    SELECT VALUE(o) INTO SELF FROM v_testa o WHERE o.ipk = pPk;
    RETURN;
    END;
    STATIC FUNCTION mycreate(pName VARCHAR2) RETURN MyTestA IS
    BEGIN
    RETURN MyTestA(pName, 1);
    END;
    -- Member procedures and functions
    OVERRIDING MEMBER FUNCTION toString(SELF IN OUT NOCOPY MyTestA) RETURN VARCHAR2 IS
    BEGIN
    RETURN toString002();
    END;
    FINAL MEMBER FUNCTION toString002(SELF IN OUT NOCOPY MyTestA) RETURN VARCHAR2 IS
    lvText VARCHAR2(1000);
    BEGIN
    lvText := SELF.toString001();
    RETURN 'MyTestA(' || iPk || ', ' || iName || ', ' || 'lvHersteller.toString()' || ', ' || lvText || ')';
    END;
    OVERRIDING MEMBER PROCEDURE log(SELF IN OUT NOCOPY MyTestA, pLogger IN OUT MyLogger) IS
    BEGIN
    pLogger.log(toString());
    END;
    end;
    CREATE OR REPLACE VIEW v_testa OF MyTesta
    WITH OBJECT IDENTIFIER (iPk) AS
    SELECT
    '1.0' iVersion
    ,g.pk iPk, g.NAME iName, g.ora_rowscn iDCN FROM o_geraete g
    DROP TABLE o_geraete;
    CREATE TABLE
    o_geraete
    pk VARCHAR2(16)
    , name VARCHAR2(100)
    , hersteller_FK VARCHAR2(16)
    , zaehlernummer VARCHAR2(20)
    , dummy VARCHAR2(10)
    INSERT INTO o_geraete
    VALUES(
    '100', 'Stromzähler', '1', 'AB-56', 'dumb'
    INSERT INTO o_geraete
    VALUES(
    '200', 'Wasserzähler', '2', 'WS-09', 'dumb'
    In forms I created a form from the view and coded into the on-insert-trigger:
    declare
         lvtest mytesta;
    begin
         message('1');
         lvtest := new mytesta(:blk_testa.iname, 1);
         message('2');
         message('3' || lvtest.tostring());
    exception
         when others then
              message('Exception: ' || sqlerrm);
    end;
    And in that forms block I got the exception.
    Perhaps someone has ANY idea...
    Thanx a lot
    Matthias
    Message was edited by:
    user522343
    Message was edited by:
    user522343

  • Putting a Class Object into a Vector

    HI all
    I need to put a class object into another classes vector, then be able to read it and retrieve data.
    I can put the object into the vector but all i seem to be able to retrieve is data like Account@2343c2.
    Is this some sort of tag? How do i get to the data?
    thankz
    joey

    That's what you get when you print an object which does not have its own toString() method to do anything different - it picks up the Object class's toString method instead. For example:
    System.out.println(new Object());It sounds like you're doing something like this:
    Vector v = new Vector();
    v.add(new Account(42));If you were to do the following, you would see that sort of output:
    System.out.println(v.get(0));The appropriate way to do this would be something like the following:
       // Use a List reference instead of a Vector reference, and create
       // an ArrayList object in preference to a Vector object
       List list = new ArrayList();
       list.add(new Account(42));
       // Iterate through the list of accounts - use an
       // iterator because this prevents off-by-one errors
       // that arise with direct indexing.
       Iterator i = list.iterator();
       while(i.hasNext()) {
          // Cast the reference returned by the iterator from
          // Object to Account so that we can call account-specific
          // methods.
          Account current = (Account)i.next();
          // Call the method specific to the Account class (getBalance
          // is just an example that I made up).
          System.out.println(current.getBalance());
       }

  • Regarding persistent classes  & objects

    Hi all,
    I am new to abap objects, please  give me some simple links of persistent classes & object.
    Let me know the difference between persistent classes & other simple classes..
    I ensure you for points!
    cheers.

    Hi,
    Transient and persistent data
    In principle, ABAP programs work with local program data, which resides in the program’s internal session. This data lives only as long as its context – that is, as long as its associated procedure (for local procedure data); its object (for attributes of classes); or its program (for global program data). This data is known as transient. Data that can be preserved beyond the runtime of the program is known as persistent. In SAP Systems, persistent data usually occurs as the content of database tables, but also as the content of files on application and presentation servers.
    To work with persistent data, the system has to load it into transient data objects belonging to the ABAP program while that program is being executed. Then, after processing has been completed, it stores the data in a persistent form again. During this time, the content of the data exists twice: once in the ABAP program (transiently), and once in the appropriate storage medium (persistently). A typical process would be reading data from a database table using the SELECT statement into a transient work area; modifying the work area; and then updating the database table (using UPDATE). In such cases, the contents of transient and persistent data are different in the interim during this process.
    Data in object-oriented programming
    In an ideal object-oriented application, data occurs only as the attributes of objects (if we ignore the local data in methods for the time being). Objects are an aggregation of functions (in methods) and data (in attributes). The description of an object – that is, the class – occurs persistently as a piece of source code, but its attributes exist only as long as the object. However, an object in ABAP Objects is transient in principle. It exists in the internal program session only from the time it is generated (using CREATE OBJECT) until it is deleted by the Garbage Collector. Therefore, to work with persistent data in objects, you must program access to where those objects are stored within the methods of the class.
    However, in completely object-oriented business application programming, then it is pointless simply to transfer the classical separation of data and functions to the methods – that is, to work with objects, but use procedural programming within the objects themselves. Ideally you could save the encapsulation of data and functions persistently within the object instead. A program could then leave an object in a certain state and a second program could continue working on the object in that state. Classes of objects are already persistent anyway, but you need some way of saving the attributes of an object persistently and then make reference to the appropriate class. The Persistence Service allows you to do exactly that.
    Persistent Classes
    To use the Persistence Service for objects, the classes of these objects must be created as persistent classes in the Class Builder. The term persistent class does not imply that a class is persistent. (As a template for objects, every class is persistent). Rather, it means that the objects of that class and their state are managed by the Persistence Service. For example, the objects of these classes are instantiated in the ABAP program with a method of the Persistence Service, which ensures that the initialization is correct (not with the usual CREATE OBJECT statement). When the Class Builder creates a persistent class, it automatically generates an associated class, known as the class actor or class agent, whose methods manage the objects of persistent classes. As well as their identity, persistent classes can contain key attributes, which allow the Persistence Service to ensure that the content of each persistent object is unique.
    Managed Objects
    The objects of persistent classes are managed by the Persistence Service. This means, among other things, that these objects are instantiated with a method of the class actor, not with the CREATE OBJECT statement. These objects are known as managed objects. Objects managed by the Persistence Service can be either persistent or transient.
    Persistent objects must be managed by the Persistence Service. The Persistence Service connects the object and the database.
    Transient objects of persistent classes are also managed by the Persistence Service. For example, the Persistence Service ensures that the object is unique within a program (by checking its key attributes), but not for a connection to the database.
    Plz refer to this link:
    http://help.sap.com/saphelp_nw70/helpdata/en/f5/a3682ebc6911d4b2e80050dadfb92b/content.htm
    Thanks,
    Samantak.
    Rewards points for useful answers.

  • Pass callback function to class object

    There is a FORM in program.
    I need to pass FORM's name to class object, and this object to run FORM.
    Like it done in ALV:
    CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
    EXPORTING
        I_CALLBACK_PROGRAM = SY-CPROG
        I_CALLBACK_USER_COMMAND = 'MY_FROM'

    here every thing will be done using the Event handling(local classes based on event definition) check this program 
    BCALV_TEST_GRID_EVENTS

  • Making middle teir accessible to all gui class objects.

    I'm designing a user interface at the moment for a
    3 tier application. I've got a good knowledge of Java
    but have never written a complicated gui with Swing.....
    User Interface (GUI) --> Business Logic (JDBC classes) --> MYSQL DB
    As the diagram shows, I want to keep the business logic separate
    from the user interface.
    My problem is that I'm not sure the best way to give all the GUI's action listeners
    access to the business logic object's methods which will call and return information
    from the database to the UI.
    Had there just been one UI class it would be easy to create an instance of the
    business logic class from the UI class, but
    the GUI is made up of many class objects with larger componets being made
    up of several smaller component classes and so on. What I guess I'm unsure of
    is what the standard practice is in this situation. Is a case of getting the GUI creation class
    to create an instance of the business logic object and then pass it down through the many
    GUI class constructors so that each GUI class object can reference it?
    You thoughts are appreciated, many thanks,
    Andrew.

    The commom practice here is to use some design patterns.
    The ones you need are Proxy and DTO (Data Transfer Object).
    The reasons behind using a proxy patters are that your DB could
    change location, and you could have multiple GUI's using the
    same DB
    You will have several DTO's which will contain the data from your
    database. These DTO's are used to group data common to one use
    case, so that in order to complete the use case, you only need to
    remotely access the DB once. These Dto's are regular Java objects
    with just getter and setter methods.
    Your GUI uses a Proxy object to request a DTO.
    someting like... you need some data to fill a form or a table?
    GUIProxy proxy = ProxyServices.getGUIProxy();
    FormDataDto dto = proxy.getFormData();
    JTexField nameField = new JTextField();
    nameField.setText(dto.getCustomerName());
    etc...
    Notice how your GUI has no idea where the data lives,
    how its stored, etc. It just knows how to request it.

  • Attach a form objects to another form

    Hi, excuse me if my question is evident for you, i am a little new with oracle form,
    i want to know if it is possible to attach a form objects to another form and how to do that. Thanks for your help.
    Edited by: Tabit7 on Apr 1, 2011 11:37 AM

    You cannot attatch a whole form (.fmb) to you form but you can subclass blocks canvas for example.
    open your form A and B
    in your reference form A select the block you want to have in form B (subclassed) and select and drag it to B.
    You will have a popup saying "do you want to copy the object ir subclass it ?" choose sublass and you are ready...
    Do the same with canvas.
    but PAY ATTENTION !!!! this method seems very useful if you have let say a identical master block for different forms.
    but you have to handle it with precautions as every changes made in form A will be reflected to all your sub-classed forms B, B1, B2 .... and could cause you designs problems
    if for example you master form A width change to something larger than one of you B forms.
    Hope this helps
    JeanYves

  • How to call a Derived call fucntion with a base class object ?

    Hi all
    i am working on a JNI interface to Java, and in the process of simulating a C++ behaviour in java
    so i need some help form you people, in this regard.
    here is a c++ code, i need a equivalent fucntionality in java , to put it one word, the question is
    how to implement the dynamic_cast functionality in java, as java also has virtual fucntions, i think
    this should be possible, if it is not, what is the alternative
    class Base
    public:
         Base()
         ~Base()
         virtual void F1()
              cout<<"The BASE::F1() is called"<<endl;
         virtual void F2()
              cout<<"The BASE::F2() is called"<<endl;
    class Derived : public Base
    public:
         Derived()
         ~Derived()
         virtual  void F3()
              cout<<"The Derived::F3() is called"<<endl;
         virtual void F4()
              cout<<"The Derived::F4() is called"<<endl;
    Base * GetDerived()
         return new Derived();
    int _tmain(int argc, _TCHAR* argv[])
         Base *ptr = NULL;
                    ptr  = GetDerived();
         Derived *dPtr = dynamic_cast<Derived *>(ptr);
                    dPtr->F3();
    }regards
    pradish

    Just to clarify a point that I consider important--the distinction between references and objects:
    Your subject is: How to call a Derived call fucntion with a base class object ? The answer to that is: You cannot. It is completely impossible in Java. If you have a base class object, the derivced class' methods are not present. On the other hand, if you have a compile-time reference of the parent type, but at runtime it happens to point to an instance of the derived class, then, as pointed out, you can cast the reference. (Note that casting does not apply to objects.)

  • Calling an action from a different controller class with an input form

    I have a Controller class declared as follows...
    public class Controller extends PageFlowController
    This class is not in a package. Inside this Controller class, I have a form class that is used as input for an Action method.
    public static class OrderDetailsForm extends FormData
    I also have another Controller class that exists in a subdirectory (and consequently has a package name)..
    package createOrder;
    class CreateOrderController extends PageFlowController
    From an Action within this Controller class, I want to forward to an Action in the first Controller class. I need to get access to the OrderDetailsForm class to do this, but I don't know how to declare a variable of the OrderDetailsForm class. I tried to do this...
    Controller.OrderDetailsForm myForm;
    But the compiler doesn't accept this. My question is what is the class name that I should be specifying to create an instance of OrderDetailsForm that lives in the Controller class that doesn't live inside a package?

    Do you know how to create an object of a class in some other class? The code you wrote seems you dont have basic sense of what is a object and class. Where did you create the object of your People class in your animal class? Create the object of people class within the animal class like:
    public class Animals {
        People people;
        public Televoting() {
        public void showAnimals() {
            people = new People(); // This is called the object creation by calling the constructor of the People 
                                              // class. Now you can access all the methods and variables of your people
                                              // class through the people object.
            System.out.println(people.peoples[0] + " is not an animal, but a person.") // Notice the difference.
    }I am sorry to say that you are not a good student and learner.
    Shan.

  • Save tree the lists of which is class' object

    Hi, my question :
    how can i save tree the lists of which is class' object?
    i save tree with the help of ObjectOutputStream class, but when i read tree object from file i have leaf without name(clean leaf)
    how read and save tree in file for normal with it?
    Code of my function for save tree:
    import javax.swing.JTree;
    import java.io.*;
    import java.util.*;
    public class SaveTree {
        public SaveTree(){
        public void saveTree(JTree tree){
            try{
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tree.info"));
            out.writeObject(tree);
            out.close();
            catch(Exception e){
                e.printStackTrace();
        public JTree loadTree(){
            JTree tree = new JTree();
            try{
                ObjectInputStream in = new ObjectInputStream(new FileInputStream("tree.info"));
                tree = (JTree)in.readObject();
                in.close();
            catch(Exception e){
                e.printStackTrace();
            return tree;
    }the code where i create new node as class' object
    public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();
            if (ADD_COMMAND.equals(command)) {
                //Add button clicked
                book = new DefaultMutableTreeNode(new BookInfo
                (name.getText(),
                "file:///"+ System.getProperty("user.dir") + "/" + ID.getText() + ".html", Integer.parseInt(ID.getText())));           
                treePanel.addObject(book);
                name.setText("");
                ID.setText("");
    }my class BookInfo
    public class BookInfo {
            public String bookName;
            public String bookURL;
            private int bookID;
            public BookInfo(String book, String filename, int ID) {
                bookID = ID;
                bookName = book;
                bookURL = filename;
                System.out.println(bookURL);
                if (bookURL == null) {
                    System.err.println("Couldn't find file: "
                                       + filename);
            public String toString() {
                return bookName;
            public int getID(){
                return bookID;
            public void setID(int ID){
                bookID = ID;
        }thanks for attention ! :)

    Jos, thanks for answer :)
    Erm, get the TreeModel from the JTree, serialize it and later deserialize it and set it as the TreeModel for your JTree again?
    kind regards,
    JosHm, i save treeModel the same way, but when i (de)serialize treeModel from file i get clean tree
    my function to save treeModel
    class Save{
    public Save(){}
    public DefaultTreeModel loadModel(DefaultTreeModel model){
            try{
                ObjectInputStream in = new ObjectInputStream(new FileInputStream("tree.info"));
                model = (DefaultTreeModel)in.readObject();
                in.close();
            catch(Exception e){
                e.printStackTrace();
            return model;
            public DefaultTreeModel saveModel(DefaultTreeModel model){
            try{
                ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tree.info"));
                out.writeObject(model);
                out.close();
            catch(Exception e){
                e.printStackTrace();
            //return model;
    }and here i init tree with treeModel
    Save save = new Save();
    DefaultMutableTreeNode root = new DefaultMutableTreeNode(myObject);
    DefaultTreeModel model = new DefaultTreeModel(root);
    JTree tree = new JTree(save.saveModel(model));
    JPanel panel  = new JPanel();
    panel.add(new JScrollPane(tree));
    this.add(panel);Edited by: Tmrs on May 18, 2008 6:00 AM

Maybe you are looking for