Dynamic addition of  JMenuItem in JMenu

I am trying to create a menu for my project. For that i have added the main menus and for each menu there will be menu item. But the problem is i will get the list of menu items for each menu , only at the runtime of my project. i.e. i wabt to add progrramatically add the menu items. Iam really confused with this. I will appriciate if any one help me on this.
And also i want to know ..is that possible to get the mouse listener for menu.
Thank in advance
Regards,
SAthish

You can add and remove menu items from the jmenu dynamically, the only thing you will have to take care of is invoking validate() after each insertion/deletion (it's a bit buggy there). All you have to do is create the items on demand and add (remove) them via the add(JMenuItem) (remove(JMenuItem)) method.
As for your second question, a JMenu is nothing but a JComponent, so you should be able to add a mouse listener like you would with any other component...

Similar Messages

  • Dynamic addition of a column to a table

    Hi All,
    I need to add one column dynamically to the existing table and also I have to populate the data dynamically. Can you help me out in this? Thanks in advance.
    Message was edited by:
            Bharath Akuthota

    Either create it a design-time invisible and make it visible if needed (probably more simply than by code), or use some code like this:
    wdDoModifyView(...)
      if (<table structure changed>)
        IWDTable table = (IWDTable) view.getElement("TableID");
        IWDTableColumn col = (IWDTableColumn) view.createElement(IWDTableColumn.class, null);
        table.addColumn(col); // NW04
        table.addGroupedColumn(col); // NW 7.0
        IWDInputField editor = (IWDInputField) view.createElement(IWDInputField.class, null);
        col.setTableCellEditor(editor);
        editor.bindValue(<attribute inside table data source that should be edited>);
    Armin

  • Dynamic addition of values in Popup

    Hi ,
      I have a requirement to display a pop-up with check boxes and labels for the check box.
    Pop-up has to contain 'n' rows , each row having a check box (with a label).
    I dont know how to dynamically add rows in the pop-up ?
    (I just meant rows to give a more clear picture , not that the pop-up would contain tables)
    When i add dynamically check boxes to the pop-up, i have to add events too.. for their functionality.
    Could anyone please help me ?
    Thanks !
    Karthik.

    Hi Karthik,
    You ned to create the UI elements dynamically as per the requirement.
    First you need to count howmany rows are for display. With help  of the For loop, you can put the condition as howmany rows and in the for loop code, write the code for displaying the checkbox and label whatever you want to create. Follow the below link for dynamic UI creation
    http://help.sap.com/erp2005_ehp_03/helpdata/EN/4f/07cf3dd28b5610e10000000a114084/frameset.htm
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/6fdae690-0201-0010-a580-d104b459cb44
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/74cda090-0201-0010-6b91-f85b2489f765
    Dynamic Creation of Checkboxes!
    http://help.sap.com/saphelp_nw04/helpdata/en/24/4e70c63574ec4284d0f47324ab2d0e/frameset.htm
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/74cda090-0201-0010-6b91-f85b2489f765
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/6fdae690-0201-0010-a580-d104b459cb44
    Dynamic UI element creation
    Thanks
    Suresh
    Edited by: Suresh Mandalapu on Aug 24, 2008 8:33 AM

  • Dynamic addition of tabs to tabstrip

    hi gurus ,
    can ne1 plz tell me how can we hav dynamic tabs on the tabstrip control .
    one of the way is to have max no of tabs n making them visible n invisible .
    but wat the problem is dat the text on the tabs is also dynamic i don knw its value in advance .
    if any1 knws how to do dis then plzzz reply asap . its urgent
    pts wil b rewarded for sure ....

    1. Create program in SE38 type module pool and Activated
    2. Go to SE51 give the program name and screen number then Layout Editor in drags tabstrip with wizard.
    3. Automacaly code is generated.
    4. Subscreen(101) add the two Check Boxs (CH1,CH2).
    5. Changed the Tab1 properties on Program in Click check box <b>OUTPUT Field only</b>
    then tab text also you give Dynamic
    PROGRAM ZTAB1 .
    FUNCTION CODES FOR TABSTRIP 'TAB2'
    CONSTANTS: BEGIN OF C_TAB2,
                 TAB1 LIKE SY-UCOMM VALUE 'TAB2_FC1',
                 TAB2 LIKE SY-UCOMM VALUE 'TAB2_FC2',
                 TAB3 LIKE SY-UCOMM VALUE 'TAB2_FC3',
               END OF C_TAB2.
    DATA FOR TABSTRIP 'TAB2'
    CONTROLS:  TAB2 TYPE TABSTRIP.
    DATA:      BEGIN OF G_TAB2,
                 SUBSCREEN   LIKE SY-DYNNR,
                 PROG        LIKE SY-REPID VALUE 'ZTAB1',
                 PRESSED_TAB LIKE SY-UCOMM VALUE C_TAB2-TAB1,
               END OF G_TAB2.
    DATA:      OK_CODE LIKE SY-UCOMM.
    DATA:A(1),B(1).
    OUTPUT MODULE FOR TABSTRIP 'TAB2': SETS ACTIVE TAB
    MODULE TAB2_ACTIVE_TAB_SET OUTPUT.
      TAB2-ACTIVETAB = G_TAB2-PRESSED_TAB.
      CASE G_TAB2-PRESSED_TAB.
        WHEN C_TAB2-TAB1.
          G_TAB2-SUBSCREEN = '0101'.
        WHEN C_TAB2-TAB2.
          G_TAB2-SUBSCREEN = '0102'.
        WHEN C_TAB2-TAB3.
          G_TAB2-SUBSCREEN = '0103'.
        WHEN OTHERS.
         DO NOTHING
      ENDCASE.
    ENDMODULE.
    INPUT MODULE FOR TABSTRIP 'TAB2': GETS ACTIVE TAB
    MODULE TAB2_ACTIVE_TAB_GET INPUT.
      CASE OK_CODE.
        WHEN C_TAB2-TAB1.
          G_TAB2-PRESSED_TAB = C_TAB2-TAB1.
        WHEN C_TAB2-TAB2.
          G_TAB2-PRESSED_TAB = C_TAB2-TAB2.
        WHEN C_TAB2-TAB3.
          G_TAB2-PRESSED_TAB = C_TAB2-TAB3.
        WHEN OTHERS.
         DO NOTHING
      ENDCASE.
    ENDMODULE.
    <b>MAIN SCREEN 100</b>
    MODULE STATUS_0100 OUTPUT.
    LOOP AT SCREEN.
    IF SCREEN-NAME = 'TAB2_TAB2'.
       IF A = 1.
          SCREEN-ACTIVE = 1.
       ELSEIF A = 0.
          SCREEN-ACTIVE = 0.
       ENDIF.
    ENDIF.
    IF SCREEN-NAME = 'TAB2_TAB3'.
        IF B = 1.
          SCREEN-ACTIVE = 1.
        ELSEIF B = 0.
          SCREEN-ACTIVE = 0.
        ENDIF.
    ENDIF.
    MODIFY  SCREEN.
    ENDLOOP.
    ENDMODULE.                 " STATUS_0100  OUTPUT
    <b>* SUBSCREEN 103</b>
    MODULE USER_COMMAND_0110 INPUT.
    CASE OK_CODE.
    WHEN 'CH1'.
        IF A = 0.
           A = 1.
        ELSEIF A = 1.
               A = 0.
        ENDIF.
    WHEN 'CH2'.
        IF B = 0.
           B = 1.
        ELSEIF B = 1.
               B = 0.
        ENDIF.
    WHEN 'EXIT'.
    LEAVE PROGRAM.
    ENDCASE.
    ENDMODULE.                 " USER_COMMAND_0110  INPUT
    Message was edited by:
            Durga Vinta

  • Dynamic addition of fields in a TAB - urgent....

    Hello all,
    I have added a tab to the existing BSP application and the following fields will be available for user input as shown below .
    start date  end date
    Presently we are able to give 10 rows for input. But the user might want more than 10 rows fro input.
    so he wants a table control kind of thing where in he can scroll and enter as many values as he can.
    or provide a button, if he clicks on the button some more empty rows will be available for input.
    Is this feasible if so how??
    Any pointers are highly appreciated..

    Its possible. refer below thread, similar issue discussed & resolved.
    Re: Add new row in Tableview
    <i>*Reward each useful answer</i>
    Raja T

  • Dynamic addition of  MXML Component

    Is it possible to add an MXML component through an ActionScript.
    I have a situation where I display multiple checkboxes and on click of each I show a subform. I am planning to make that subform as MXML component and add/remove it based on the user's checking/unchecking the checkbox..Is this possible?
    Thanks
    Dharmesh

    Hi Ben ..
         Appreciate your quick response. This is my first Flex app. In a nut sheel here is a sample similar to what I am trying to achieve.
    Consider my Mxml component as follows
    <?xml version="1.0" encoding="utf-8"?>
    <!-- myComponents/TempComponent.mxml -->
    <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300">
        <mx:Button label="Hey there from component"/>
    </mx:Canvas>
    Now here he my app mxml file
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
        xmlns:temp="mycomponents.*">
        <mx:Script>
            <![CDATA[
                import mx.controls.Alert;
                public function addRemove():void{
                    //How do i add that component to the Panel?
            ]]>
        </mx:Script>
         <mx:Checkbox id="cb" change="addRemove()" label="Check or Uncheck"/>
         <mx:Panel  id="testPanel" x="0" y="0" width="100%" height="200" layout="absolute" borderThickness="0" borderThicknessBottom="0"/>
    Can you guide me what should go in the listener to add the component to the panel?

  • Dynamic addition to JTree

    HI all.Im a little frustrated.im emulating the structure of an xml file in a jtree.but what im trying to do is add a node to another node, when a button is clicked.the only problem im having is retrieving a particular node, whether it be a child or sub-child etc.
    i have looked at the getIndexOfChild method of defaultTreeModel.but the problem is that when the user creates a child node (ive already created the root node) and wants to add it as a sub-child of another child node, it's here i have the prob.
    i have
    1 <-- root node
    | 2 <-- child of 1
    | | 3 <-- child of 2
    | | |
    1even though i created node 2 like so new DefaultMutableTreeNode("some name"); and i know the name i supplied to it in the constructor, how can i retrieve it again, so i can append another child onto this child.plz help (i dont want code)
    thanks

    So in the worst
    case you could look at all the nodes in the tree, and
    your problem is reduced to being able to recognize
    the node when you see it.
    That isn't a particularly good way, can i ask why this isnt a particularly good way?
    here is what i ended up doing,
    if(rowNumber == -1) {
                        //Create a new root node, for the very
                        //first entry.
                        rootNode = new DefaultMutableTreeNode(componentName);
                        dTreeModel = new DefaultTreeModel(rootNode);
                        dtm.addRow(new Object[] { componentName.trim(), new Boolean(false), new Boolean(false), new Boolean(false)});
                        rowNumber++;
                        v.add(rootNode);
                        drawTheHierarchy();
                   else {
                        //we check to see if this variable is
                        //an attribute or a child of another component
                        //by scanning down through all the rows of table.
                        for(int     i = 0; i < rowCount; i++) {
                             //If user has checked one of the "Element OF"
                             //checkboxes:
                             String nameOfParent = getParentNames(i);
                             if(!nameOfParent.equals("null")) {
                                  //get the index of the element with
                                  //the name of 'component name' in the vector.
                                  for(int j = 0; j < v.size(); j++) {
                                       //Get a string representation of the node
                                       //to allow comparison.
                                       String nodeStringRepresentation = v.get(j).toString();
                                       if(nameOfParent.equals(nodeStringRepresentation)) {
                                            //get the node from the vector
                                            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) v.get(j);
                                            //create a child node
                                            DefaultMutableTreeNode childNode =
                                                      new DefaultMutableTreeNode(componentName);
                                            //add a new node to this node.
                                            selectedNode.add(childNode);
                                            //and add to the vector.
                                            v.add(childNode);
                        }

  • Dynamic JMenuItem

    Hi,
    Does anybody has any idea about dynamic addition and removal of JMenuItems. I am trying to implement an exactly the same functionality as in MSWord, when you open multiple files, a single MenuItem is adding in Windows Menu.
    I want when user opens a new file, a JMenuItem is created with the name of that file in Windows Menu. And when user closes that file, that menu item be removed.
    Any ideas
    Thanks

    The JMenu is a container like all others, so just find the particular index from where you would want to start adding your JMenuItem and then add it using the add(Component, index) method of the container. I believe you are trying to implement the Window menu behavior of MSWord.
    Here's a general idea, you could also add seperators, above and below the menuitems and use their indexes as starting and ending points for the addition of the menuItems. So the idea is to get the index of the bottom seperator, remove the seperator, add the menuitem at that index and then re-add the seperator at the next index. Something like that, but I also think adding the component at the index of the seperator will move the seperator down to the index.
    I haven't tested this idea (as usual) but you can give it a try.
    All the best
    ICE

  • JMenu and JMenuItem - Images

    How to put an image in front of the JMenu text?
    JMenuItem has a constructor to insert the icon.
    Is their a reason why it not in the JMenu constructors?
    Sometimes I just want to put a 16 pixel gap in front of the JMenuItem or JMenu if it has no Image. Can one do that without inserting a blank
    Image?
    Thanks

    Have you tried just setting it via setIcon()? Since both JMenu and
    JMenuItem inherit from AbstractButton, this may work; I say may
    since more than likely it is up to the L&F UI to do the right thing.
    A quick browse shows that it ought to work for at least the basic
    L&Fs though.
    As far as the empty gap, looks like you might be out of luck by
    default, but this too is up to the L&F. For instance, some look and
    feels line up the text properly if an item doesn't have an icon.
    As a quick fix, though, you could probably just set the icon to
    something like
    menuItem.setIcon( new Icon() {
        public int getIconWidth() { return 16; }
        public int getIconHeight() { return 0; }
        public void paintIcon(Component c, Graphics g, int x, int y) {}
    });: jay

  • Jpopupmenu, jmenuitem, jmenu... transparent

    I have extended JPopupmenu, JMenuItem, and JMenu in order to obtain some behaivier (transparent menus). Im having this prob. that the JMenu creates a normal JPopupMenu, where I would like it to use my extended JPopupMenu. I thought about overriding the method in JMenu which creates the JPopupMenu, but the JPop is private in jmenu. How to do this? I could ofcourse copy all the code of the jmenu class and just change the creation of the jpopupmenu, but that is probably illegal or something. Any ideas?
    Stig.

    I have the same problem.
    I run my code in jdk1.3 and it works great. But in 1.4, the transparency is gone, and depeneding on the implementation, the repainting sometimes gets real crazy.

  • Help with loading dynamic classes ..need help please

    i'm trying to design a program where by i can load dynamic classes
    the problem i'm getting is that only one class is loading.
    classes are loaded by their names,and index numbers of public methods from a linklist
    .When the program runs only the first class is ever loaded and only the methods of that class ..
    help please
    //class loader
    import java.lang.reflect.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class Test2 extends Thread
         public Class c;
         public Class Ray;
         public Class[] x;
         public static Object object = null;
         public Method[] theMethods;
         public static Method[] method,usemethod;
         public int methodcount;
         public static int MethodCt;     
         public static JList list;
    public Method[] startClass(String SetMethodName)
         try
              c = Class.forName(SetMethodName);
              object = c.newInstance();
              theMethods = c.getDeclaredMethods();
              // number of methods
              //methodcount = theMethods.length;
         catch (Exception e)
              e.printStackTrace();
    // return the array then invoke the particular method later
    return theMethods ;
    public void RunMethod(Method[] SomeMethod, int methodcount)
         try
              SomeMethod[methodcount].invoke( object,null );
         catch (Exception e)
              e.printStackTrace();
    // end class loader
    //main calling program
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing .*;
    import java.lang.reflect.*;
    public class JFMenu extends JFrame
         public static JMenu pluginMenu;
         public static JMenuBar bar;
         public static final Test2 w = new Test2();
    public static Method[] setmethod;
    private static ClassLinkList startRef = null;
    private static ClassLinkList linkRef3 = null;
    private static ClassLinkList startRef2 = null;
    private String ClassName,ShortCut;
    private int MethodNumber;
    private JMenuItem PluginItem;
         JFMenu()
              super (" JFluro ");     
              JMenu fileMenu = new JMenu("File");
              fileMenu.setMnemonic('F');
              JMenuItem exitItem = new JMenuItem("Exit");
              exitItem.setMnemonic('X');
              fileMenu.add(exitItem);
              exitItem.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             System.exit(0);
              JMenu pluginMenu = new JMenu("Plugins");
              pluginMenu.setMnemonic('P');
              startRef = new ClassLinkList ("Hello","Hello ",2,1926,"Painter");
              addToList("Foo","Foo ",0,1930,"Author");
              while (startRef.linkRef5 != null)
                   //pluginMenu.addSeparator();
                   ClassName = startRef.linkRef5.className;
                   ShortCut = startRef.linkRef5.shortcutName;
    MethodNumber = startRef.linkRef5.methodNumber;
    AddMenuItem(pluginMenu,ShortCut,ClassName,MethodNumber);
                   startRef.linkRef5 = startRef.linkRef5.next;
              // create menu bar and add JFMenu window to it
              JMenuBar bar = new JMenuBar();
              setJMenuBar(bar);
              bar.add(fileMenu);
              bar.add(pluginMenu);
              //attributes for JFMenu frame
              setSize(500,200);
              setVisible(true);
         }// end JFMenu constructor
         public void AddMenuItem(JMenu MainMenu, String shortcut,String className, final int methodCount )
              if (MainMenu==null)
                   return;
              //JMenuItem item;
              JMenuItem item = new JMenuItem(shortcut);
              MainMenu.add(item);
              setmethod = w.startClass(className);
              item.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             w.RunMethod(setmethod,methodCount);
              //item.addActionListener(ij);
         public JMenuItem AddMenuItem2(JMenu MainMenu, String shortcut)
              //if (MainMenu==null)
              //     return Main;
              //JMenuItem item;
              JMenuItem item = new JMenuItem(shortcut);
              MainMenu.add(item);
              //setmethod = w.startClass(className);
              //item.addActionListener(this);
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             w.RunMethod(setmethod,methodCount);
              //item.addActionListener(ij);
         return item;
         public void ReloadMenu(JMenuBar Bar, JMenu PluginMenu)
              if (Bar==null)
                   return;
              //     setJMenuBar(Bar);
              Bar.add(PluginMenu);
              //item.addActionListener(ij);
    public static void main (String args[])
              JFMenu menapp = new JFMenu();
    public static void addToList(String clname, String shcutname, int metnumber, int year2,
                                  String description) {
         // Create instance of class ClassLinkList
    ClassLinkList newRef = new ClassLinkList(clname,shcutname,metnumber,year2,
                                       description);
    // Add to linked list;
         startRef = startRef.addRecordToLinkedList(newRef);
    // end main calling program
    class Hello extends Thread
    public int getNum()
    System.out.println("I can be ");
    return 5;
    public void rayshowName()
    System.out.println("anything i want ");
    public void rayshowName3()
    System.out.println("to be ");
    class Foo extends Thread
    public int getNum()
    System.out.println("IMHOFF");
    return 5;
    public void rayshowName()
    System.out.println("raYMOND");
    // FAMOUS PERSONS LINKED LIST EXAMPLE
    // Frans Coenen
    // Saturday 15 January 2000
    // Depaertment of Computer Science, University of Liverpool
    class ClassLinkList {
    /* FIELDS */
    public String className;
    public String shortcutName;
    public int methodNumber;
    public int yearOfDeath;
    public String occupation;
    public ClassLinkList next = null;
    public ClassLinkList linkRef5 = this;
    public ClassLinkList startRef = null;
    /* CONSTRUCTORS */
    /* FamousPerson constructor */
    public ClassLinkList(String classname, String shortcutname, int methodnumber, int year2,
                                  String description) {
         className = classname;
         shortcutName = shortcutname;
         methodNumber = methodnumber;
         yearOfDeath = year2;
         occupation = description;
         next = null;
    /* METHODS */
    /* Output famous person linked list */
    public void outputClassLinkedList()
         //public ClassLinkList outputClassLinkedList() {
         ClassLinkList linkRef = this;
         // Loop through linked list till end outputting each record in turn
    while (linkRef != null)
         //System.out.println(linkRef5);
         System.out.println(linkRef.className + ", " + linkRef.shortcutName +
                   " (" + linkRef.methodNumber + "-" + linkRef.methodNumber +
                   "): " + linkRef.occupation);
         linkRef = linkRef.next;     
    //return linkRef;
    //public String ShowCasname()
    //return String ;     
    /* Add a new record to the linked list */
    public ClassLinkList addRecordToLinkedList(ClassLinkList newRef) {
         ClassLinkList tempRef, linkRef;
         // Test if new person is to be added to start of list if so return
    if (newRef.testRecord(this) ) {
         newRef.next = this;
         return(newRef);
         // Loop through remainder of linked list
         tempRef = this;
         linkRef = this.next;
         while (linkRef != null) {
         if (newRef.testRecord(linkRef)) {
         tempRef.next = newRef;
              newRef.next = linkRef;
              return(this);
         tempRef = linkRef;
         linkRef = linkRef.next;
    // Add to end
    tempRef.next = newRef;
         return(this);
    /* Delete a record from the linked list given the first and last name. Four
    posibilities:
    1) Record to be deleted is at front of list
    2) Record to be deleted is at end of list
    3) Record to be deleted is in middle of list
    4) Record not found. */
    public ClassLinkList deleteRecord(String lName, String fName) {
    ClassLinkList tempRef, linkRef;
    // Record at start of list
    if ((this.className == lName) & (this.shortcutName == fName))
         return(this.next);
         // Loop through linked list to discover if record is in middle of list.
         tempRef = this;
    linkRef = this.next;
    while (linkRef != null) {
         if ((linkRef.className == lName) & (linkRef.shortcutName == fName)) {
    tempRef.next = linkRef.next;
    return(this);
    tempRef = linkRef;
    linkRef = linkRef.next;
    // Record at end of list, or not found
    if ((linkRef.className == lName) & (linkRef.shortcutName == fName))
                        linkRef = null;
         else System.out.println("Record: " + lName + " " + fName + " not found!");
         return(this);
    /* TEST METHODS */
    /* Test whether new record comes before existing record or not. If so return
    true, false otherwise. */
    private boolean testRecord(ClassLinkList existingRef) {
         int testResult = className.compareTo(existingRef.className);
         if (testResult < 0) return(true);
         else {
         if ((testResult == 0) & (shortcutName.compareTo(existingRef.shortcutName) < 0 ))
                             return(true);
         // Return false
         return(false);
         public void addToList(String clname, String shcutname, int metnumber, int year2,
                                  String description)
         // Create instance of class Famous Person
    ClassLinkList newRef = new ClassLinkList(clname,shcutname,metnumber,year2,
                                       description);
    // Add to linked list;
         startRef = startRef.addRecordToLinkedList(newRef);

    I have a similar problem. I am writing a program to read the class names from database and instantiate several classes which extends from ServiceThread (an abstract class extending from Thread).
    rs = pStmt.executeQuery();
    while(rs.next()) {
    String threadclassname = rs.getString("classname").trim();
    try{
    ServiceThread threadinstance = (ServiceThread)Class.forName(threadclassname).newInstance();
    }catch ...
    So far, only the first class is ever instantiated and runs fine. But subsequent classes do not even get pass the "... ... Class.forName(...).newInstance();" line.
    Funny thing is that there are also no exceptions. The JVM just seem to hang there.

  • Creation of table of table dynamically

    Hi everyone,
      i have created an alv grid with a dynamic number of columns. Now i need to edit specific rows in the alv table. In the BCALV_EDIT_02 you need to create in the data table a field CELLTAB (wich is also a table), how can i do this ?
    Xavier

    Hello Frederico
    The once again revised version of my sample report demonstrates how to store PBO and PAI data. Please note the following naming convention:
    - OUTTAB ==> itab for ALV list display with CELLTAB (i.e. a complex type)
    - ITAB      ==> flat itab without CELLTAB
    *& Report  ZUS_SDN_RTTI_CREATE_STRUCTUR_2
    *& NOTE: 1st revised version of ZUS_SDN_RTTI_CREATE_STRUCTUR_1
    REPORT  zus_sdn_rtti_create_structur_2.
    TYPE-POOLS: abap.
    DATA:
      celltab          TYPE lvc_t_styl.
    DATA:
      gd_tabnam        TYPE string,
      gd_tabfield      TYPE string,
      go_table         TYPE REF TO cl_salv_table,
      go_sdescr        TYPE REF TO cl_abap_structdescr,
      go_sdescr_new    TYPE REF TO cl_abap_structdescr,
      go_tdescr        TYPE REF TO cl_abap_tabledescr,
      go_typedescr     TYPE REF TO cl_abap_typedescr,
      gdo_data         TYPE REF TO data,
      gdo_handle       TYPE REF TO data,
      gs_component     TYPE abap_compdescr,
      gs_comp          TYPE abap_componentdescr,
      gt_components    TYPE abap_component_tab.
    *    name       TYPE string,
    *    type       TYPE REF TO cl_abap_datadescr,
    *    as_include TYPE abap_bool,
    *    suffix     TYPE string,
    FIELD-SYMBOLS:
      <gd_fld>            TYPE ANY,  " single field
      <gs_outtab>         TYPE ANY,  " structure with CELLTAB
      <gs_itab>           TYPE ANY,  " structure without CELLTAB
      <gt_itab_pbo>       TYPE STANDARD TABLE,  " without CELLTAB
      <gt_itab_pai>       TYPE STANDARD TABLE,  " without CELLTAB
      <gt_outtab_pbo>     TYPE STANDARD TABLE,  " with CELLTAB
      <gt_outtab_pai>     TYPE STANDARD TABLE.  " with CELLTAB
    PARAMETER:
      p_tabnam      TYPE tabname  DEFAULT 'KNB1'.
    PARAMETERS:
      p_skip        AS CHECKBOX  DEFAULT 'X'.  " skip simulation
    START-OF-SELECTION.
      " Describe structure
      go_sdescr ?= cl_abap_structdescr=>describe_by_name( p_tabnam ).
      gd_tabnam     = go_sdescr->get_relative_name( ).
    * Simulate dynamic addition of columns to ALV list
      DO 5 TIMES.
        READ TABLE go_sdescr->components INTO gs_component INDEX syst-index.
        "   Build fieldname
        CONCATENATE gd_tabnam gs_component-name INTO gd_tabfield
                                                SEPARATED BY '-'.
        CLEAR: gs_comp.
        gs_comp-type ?= cl_abap_datadescr=>describe_by_name( gd_tabfield ).
        gs_comp-name  = gs_component-name.
        APPEND gs_comp TO gt_components.
        go_sdescr_new  = cl_abap_structdescr=>create( gt_components ).
        go_tdescr      = cl_abap_tabledescr=>create( go_sdescr_new ).
        "   Create data refence followed by table creation
        CREATE DATA gdo_handle TYPE HANDLE go_tdescr.
        ASSIGN gdo_handle->* TO <gt_outtab_pbo>.
    *   Dynamic select
        SELECT        * FROM  (p_tabnam) UP TO 10 ROWS
          INTO CORRESPONDING FIELDS OF TABLE <gt_outtab_pbo>
               WHERE  bukrs  = '2000'.
        IF ( p_skip = abap_false ).
          TRY.
              CALL METHOD cl_salv_table=>factory
                IMPORTING
                  r_salv_table = go_table
                CHANGING
                  t_table      = <gt_outtab_pbo>.
              go_table->display( ).
            CATCH cx_salv_msg .
          ENDTRY.
        ENDIF.
      ENDDO.
      TRY.
          CALL METHOD cl_salv_table=>factory
            IMPORTING
              r_salv_table = go_table
            CHANGING
              t_table      = <gt_outtab_pbo>.
          go_table->display( ).
        CATCH cx_salv_msg .
      ENDTRY.
      " Display component list in order to prove that indeed the field names
      " are used (instead of the data element names)
      TRY.
          CALL METHOD cl_salv_table=>factory
            IMPORTING
              r_salv_table = go_table
            CHANGING
              t_table      = gt_components.
          go_table->display( ).
        CATCH cx_salv_msg .
      ENDTRY.
      " Create data reference for structure (without CELLTAB)!!!
      CREATE DATA gdo_handle TYPE HANDLE go_sdescr_new.
      REFRESH: gt_components.
      CLEAR: gs_comp.
      gs_comp-type ?=
            cl_abap_structdescr=>describe_by_data_ref( gdo_handle ).
      gs_comp-name       = 'DATA'.
      gs_comp-as_include = abap_true.
      APPEND gs_comp TO gt_components.
      " Add table type as field to structure ==> complex structure
      CLEAR: gs_comp.
      gs_comp-type ?= cl_abap_typedescr=>describe_by_data( celltab ).
      gs_comp-name  = 'CELLTAB'.
      APPEND gs_comp TO gt_components.
      go_sdescr  = cl_abap_structdescr=>create( gt_components ).
      go_tdescr  = cl_abap_tabledescr=>create( go_sdescr ).
      CREATE DATA gdo_handle TYPE HANDLE go_tdescr.
      ASSIGN gdo_handle->* TO <gt_outtab_pbo>.
    *   Dynamic select
      SELECT        * FROM  (p_tabnam) UP TO 10 ROWS
        INTO CORRESPONDING FIELDS OF TABLE <gt_outtab_pbo>
             WHERE  bukrs  = '2000'.
      PERFORM fill_celltab.
      " Create second itab (PAI data)
      CREATE DATA gdo_handle TYPE HANDLE go_tdescr.
      ASSIGN gdo_handle->* TO <gt_outtab_pai>.
      <gt_outtab_pai> = <gt_outtab_pbo>.  " PAI data = PBO data
      " Renumbering of customer makes it easier to spot the differences
      LOOP AT <gt_outtab_pai> ASSIGNING <gs_outtab>.
        ASSIGN COMPONENT 'KUNNR' OF STRUCTURE <gs_outtab> TO <gd_fld>.
        <gd_fld> = syst-tabix.  " new numbering of customers
      ENDLOOP.
      LOOP AT <gt_outtab_pbo> ASSIGNING <gs_outtab>.
        ASSIGN COMPONENT 'KUNNR' OF STRUCTURE <gs_outtab> TO <gd_fld>.
        <gd_fld> = syst-tabix.  " new numbering of customers
      ENDLOOP.
      DELETE <gt_outtab_pbo> INDEX 3.  " ==>  3rd row in PAI data is new
      DELETE <gt_outtab_pai> INDEX 7.  " ==>  7th row in PBO data is DELE
      " Shuffle data from outtab to corresponding itab (w/o CELLTAB)
      PERFORM shuffle_outtab_to_itab.
      " List output
      PERFORM write_list.
      EXIT.
      " Simplified version of table creation:
      CLEAR: gdo_data.
      UNASSIGN <gt_outtab_pbo>.
      CREATE DATA gdo_data TYPE STANDARD TABLE OF (p_tabnam).
      ASSIGN gdo_data->* TO <gt_outtab_pbo>.
    END-OF-SELECTION.
    *&      Form  FILL_CELLTAB
    *       text
    *  -->  p1        text
    *  <--  p2        text
    FORM fill_celltab .
    * define local data
      DATA:
        ls_cell       TYPE lvc_s_styl,
        lt_celltab    TYPE lvc_t_styl.
      FIELD-SYMBOLS:
        <gs_struc>    TYPE ANY,
        <lt_celltab>  TYPE lvc_t_styl.
      " Create dummy entry for local CELLTAB
      ls_cell-fieldname = 'BUKRS'.
      ls_cell-style     = cl_gui_alv_grid=>mc_style_enabled.
      INSERT ls_cell INTO TABLE lt_celltab.
      LOOP AT <gt_outtab_pbo> ASSIGNING <gs_struc>.
        ASSIGN COMPONENT 'CELLTAB' OF STRUCTURE <gs_struc> TO <lt_celltab>.
        <lt_celltab> = lt_celltab.
        "   No MODIFY required because we are working with the field symbol
      ENDLOOP.
    ENDFORM.                    " FILL_CELLTAB
    *&      Form  SHUFFLE_OUTTAB_TO_ITAB
    *       text
    *  -->  p1        text
    *  <--  p2        text
    FORM shuffle_outtab_to_itab .
      go_tdescr  = cl_abap_tabledescr=>create( go_sdescr_new ).
      CREATE DATA gdo_handle TYPE HANDLE go_tdescr.
      ASSIGN gdo_handle->* TO <gt_itab_pbo>.
      go_tdescr  = cl_abap_tabledescr=>create( go_sdescr_new ).
      CREATE DATA gdo_handle TYPE HANDLE go_tdescr.
      ASSIGN gdo_handle->* TO <gt_itab_pai>.
      LOOP AT <gt_outtab_pbo> ASSIGNING <gs_outtab>.
        ASSIGN COMPONENT 'DATA' OF STRUCTURE <gs_outtab> TO <gs_itab>.
        APPEND <gs_itab> TO <gt_itab_pbo>.
      ENDLOOP.
      LOOP AT <gt_outtab_pai> ASSIGNING <gs_outtab>.
        ASSIGN COMPONENT 'DATA' OF STRUCTURE <gs_outtab> TO <gs_itab>.
        APPEND <gs_itab> TO <gt_itab_pai>.
      ENDLOOP.
    ENDFORM.                    " SHUFFLE_OUTTAB_TO_ITAB
    *&      Form  WRITE_LIST
    *       text
    *  -->  p1        text
    *  <--  p2        text
    FORM write_list .
      WRITE: / 'PBO data:'.
      LOOP AT <gt_itab_pbo> ASSIGNING <gs_itab>.
        WRITE: / 'Record No.=', syst-tabix, '==>'.
        DO.
          ASSIGN COMPONENT syst-index OF STRUCTURE <gs_itab> TO <gd_fld>.
          IF ( syst-subrc NE 0 ).
            EXIT.
          ENDIF.
          WRITE: <gd_fld>.
        ENDDO.
      ENDLOOP.
      SKIP 2.
      WRITE: / 'PAI data:'.
      LOOP AT <gt_itab_pai> ASSIGNING <gs_itab>.
        WRITE: / 'Record No.=', syst-tabix, '==>'.
        DO.
          ASSIGN COMPONENT syst-index OF STRUCTURE <gs_itab> TO <gd_fld>.
          IF ( syst-subrc NE 0 ).
            EXIT.
          ENDIF.
          WRITE: <gd_fld>.
        ENDDO.
      ENDLOOP.
    ENDFORM.                    " WRITE_LIST
    Finally, if you want to know the <i>differences </i>between PAI and PBO data, that is which records have been deleted, updated or inserted have a look at my code sample
    <a href="https://wiki.sdn.sap.com/wiki/display/Snippets/ComparingTwoInternalTables-AGeneric+Approach">Comparing Two Internal Tables - A Generic Approach</a>
    Regards
      Uwe

  • Dynamic Programming - RTTC - Appending lines

    I give up! Maybe someone else can help me with this Dynamic Programming problem.
    I am using RTTC to create an itab. Now I want to append lines and for some reason can't seem to crack the syntax I need.
    My latest attempt looks like this...
                FIELD-SYMBOLS: <table> TYPE ANY TABLE,
                               <row> TYPE ANY.
                lo_sdescr      = cl_abap_structdescr=>create( lt_components ).
                lo_tdescr      = cl_abap_tabledescr=>create( lo_sdescr ).
                CREATE DATA lr_alloc->alloc_table TYPE HANDLE lo_tdescr.
                CREATE DATA lr_struct TYPE HANDLE lo_rdescr.
                ASSIGN lr_alloc->alloc_table->* TO <table>.
                APPEND INITIAL LINE TO <table> ASSIGNING <row>.
    The syntax check I get on the APPEND statement is "You cannot use explicit or implicit index operations on tables with type "ANY TABLE".
    All the doco and examples I can find use a simple "SELECT * ... INTO CORRESPONDING FIELDS OF TABLE <table>" syntax which it not what I need to do.
    Any help it appreciated.
    Thanks
    Graham Robbo

    Hello Graham
    The solution is quite simple (at least to overcome your syntax error):
    FIELD-SYMBOLS:
      <gt_itab>     TYPE STANDARD TABLE,  " use STANDARD instead of ANY
      <gs_struc>    TYPE ANY.
    *& Report  Z_RTTI_CREATE_COMPLEX_ITAB
    *& NOTE: revised version of ZUS_SDN_RTTI_CREATE_STRUCTURES
    *& Thread: Dynamic Programming - RTTC - Appending lines
    *& <a class="jive_macro jive_macro_thread" href="" __jive_macro_name="thread" modifiedtitle="true" __default_attr="980407"></a>
    REPORT  z_rtti_create_complex_itab.
    TYPE-POOLS: abap.
    DATA:
      celltab          TYPE lvc_t_styl.  " becomes field of complex itab
    DATA:
      gd_tabnam        TYPE string,
      gd_tabfield      TYPE string,
      go_table         TYPE REF TO cl_salv_table,
      go_sdescr        TYPE REF TO cl_abap_structdescr,
      go_sdescr_new    TYPE REF TO cl_abap_structdescr,
      go_tdescr        TYPE REF TO cl_abap_tabledescr,
      gdo_data         TYPE REF TO data,
      gdo_handle       TYPE REF TO data,
      gs_component     TYPE abap_compdescr,
      gs_comp          TYPE abap_componentdescr,
      gt_components    TYPE abap_component_tab.
    FIELD-SYMBOLS:
      <gt_itab>     TYPE STANDARD TABLE,
      <gs_struc>    TYPE ANY.
    PARAMETER:
      p_tabnam      TYPE tabname  DEFAULT 'KNB1'.
    START-OF-SELECTION.
      " Describe structure
      go_sdescr ?= cl_abap_structdescr=>describe_by_name( p_tabnam ).
      gd_tabnam     = go_sdescr->get_relative_name( ).
      " Simulate dynamic addition of columns
      LOOP AT go_sdescr->components INTO gs_component.
        "   Build fieldname
        CONCATENATE gd_tabnam gs_component-name INTO gd_tabfield
                                                SEPARATED BY '-'.
        CLEAR: gs_comp.
        gs_comp-type ?= cl_abap_datadescr=>describe_by_name( gd_tabfield ).
        gs_comp-name  = gs_component-name.
        APPEND gs_comp TO gt_components.
      ENDLOOP.
      "   Create instances of dynamic structure and dynamic internal table
      go_sdescr_new  = cl_abap_structdescr=>create( gt_components ).
      go_tdescr      = cl_abap_tabledescr=>create( go_sdescr_new ).
      "   Create data refence followed by table creation
      CREATE DATA gdo_handle TYPE HANDLE go_sdescr_new.
      ASSIGN gdo_handle->* TO <gs_struc>.
      CREATE DATA gdo_handle TYPE HANDLE go_tdescr.  " !!!
      ASSIGN gdo_handle->* TO <gt_itab>.
      APPEND INITIAL LINE TO <gt_itab> ASSIGNING <gs_struc>.
      TRY.
          CALL METHOD cl_salv_table=>factory
            IMPORTING
              r_salv_table = go_table
            CHANGING
              t_table      = <gt_itab>.
          go_table->display( ).
        CATCH cx_salv_msg .
      ENDTRY.
    END-OF-SELECTION.
    Regards
      Uwe

  • Is it possible to change the default border on a JMenu?

    Hello,
    I'm working on an application that has a simple menu system. Clicking a button opens a JPopupMenu, which contains JMenu and JMenuItem objects. I want to change the border on the JPopupMenu and its JMenu submenus to a simple line border. Calling setBorder on the JPopupMenu works just fine, but calling it on JMenu doesn't change the border. The following code illustrates my point.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class MenuTest {
       JFrame f;
       JPanel p;
       JPopupMenu popup;
       JMenu mainMenu;
       JMenu subMenu;
       JButton showPopupButton;
       public MenuTest()
          f = new JFrame("Popup Menu Test");
          p = new JPanel();
          popup = new JPopupMenu();
          subMenu = new JMenu("Submenu");
          mainMenu = new JMenu("Main Menu");
          JMenuItem m;
          for (int i=0; i < 3; i++) {
             m = new JMenuItem("Submenu item " + i);
             subMenu.add(m);
          // This doesn't work.  The border remains set to the default Windows bevel.
          subMenu.setBorder(BorderFactory.createLineBorder(Color.BLACK));
          popup.add(subMenu);
          for (int i=0; i < 5; i++) {
             m = new JMenuItem("Main menu item " + i);
             popup.add(m);
          showPopupButton = new JButton("Show Popup");
          showPopupButton.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e)
                Component c = (Component) e.getSource();
                popup.show(c, 0, c.getHeight());
          p.add(showPopupButton);
          // This works.  It sets the border of the popup menu to a black line border.
          popup.setBorder(BorderFactory.createLineBorder(Color.BLACK));
          f.getContentPane().add(p);
          f.setSize(400, 300);
          f.setVisible(true);
       public static void main(String[] args)
          try {
             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          catch (Exception e) { }
          new MenuTest();
    }Any ideas? Do I have to extend JMenu and do some custom painting to accomplish this? I'd also like to change the roll-over color on the menu items, but neither JMenu nor JPopupMenu seem to support that. It looks like borders and rollover colors are L&F dependent.
    Thanks in advance for any help.

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Example {
        public static void main(String[] args)  throws Exception {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            UIManager.put("MenuItem.selectionForeground", Color.GREEN);
            UIManager.put("MenuItem.selectionBackground", Color.BLACK);
            JMenuBar mb = new JMenuBar();
            Border border = BorderFactory.createRaisedBevelBorder();
            JMenu file = new BorderedMenu("File", border);
            file.add(new JMenuItem("New"));
            file.add(new JMenuItem("Open"));
            file.add(new JMenuItem("Close"));
            JMenu edit = new BorderedMenu("Edit", border);
            edit.add(new JMenuItem("Cut"));
            edit.add(new JMenuItem("Paste"));
            edit.add(new JMenuItem("Copy"));
            mb.add(file);
            mb.add(edit);
            JFrame f = new JFrame("Example");
            f.setJMenuBar(mb);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        static class BorderedMenu extends JMenu {
            private Border border;
            public BorderedMenu(String text, Border border) {
                super(text);
                this.border = border;
            public JPopupMenu getPopupMenu() {
                JPopupMenu p = super.getPopupMenu();
                p.setBorder(border);
                return p;
    }By the way, I find the following program handy when snooping around the UI defaults.
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    public class Listing {
        public static void main(String[] args) throws Exception {
            UIDefaults defs = UIManager.getLookAndFeelDefaults();
            ArrayList list = new ArrayList();
            for(Iterator i = defs.entrySet().iterator(); i.hasNext(); ) {
                Map.Entry entry = (Map.Entry) i.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                if (value instanceof Color)
                    list.add(key);
            Collections.sort(list);
            JPanel panel = new JPanel(new GridLayout(0,1));
            String lastCompName = "";
            for(int i=0; i<list.size(); ++i) {
                Object key = list.get(i);
                String text = key.toString();
                int dotIndex = text.indexOf('.');
                String compName = text.substring(0, dotIndex > 0 ? dotIndex : text.length());
                if (!compName.equals(lastCompName)) {
                    lastCompName = compName;
                    panel.add(new JLabel());
                Color color = defs.getColor(key);
                JLabel label = new JLabel(text, new ColorIcon(color), JLabel.LEFT);
                panel.add(label);
            JFrame f = new JFrame("Listing");
            f.getContentPane().add(new JScrollPane(panel));
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.pack();
            f.setSize(f.getWidth(), 600);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    class ColorIcon implements Icon {
        public static final int ICON_WIDTH = 20;
        public static final int ICON_HEIGHT = 16;
        private Color color;
        public ColorIcon(Color color) {
            this.color = color;
        public int getIconWidth() {
            return ICON_WIDTH;
        public int getIconHeight() {
            return ICON_HEIGHT;
        public void paintIcon(Component c, Graphics g, int x, int y) {
            if (color != null) {
                Color old = g.getColor();
                g.setColor(color);
                g.fillRect(x, y, ICON_WIDTH, ICON_HEIGHT);
                g.setColor(Color.BLACK);
                g.drawRect(x, y, ICON_WIDTH-1, ICON_HEIGHT-1);
                g.setColor(old);
    }

  • Error in Right-to-Left Jmenu movement

    Hi everybody,
    I started using Java 1.5 recently, I found that it does not behave correctly regarding arrow key movements in right-to-left orientation (up,down, left and right), as the following piece of code shows:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class test14 extends JFrame {
      JMenuBar  jmenubar = new JMenuBar();
      JMenu     Jmenu;
      JMenuItem mi;
      public test14() {
        super("Menu test..");
        setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        enableEvents(AWTEvent.KEY_EVENT_MASK);
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            Exit();
        setMenu();
        jmenubar.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        Dimension max_size = Toolkit.getDefaultToolkit().getScreenSize();
        this.setSize(max_size.width,max_size.height);
        this.setLocation(1,1);
        show();
      public void setMenu() {
        int       i,c;
        JMenu     Jmenu = null;
        JMenuItem mi;
        Jmenu = new JMenu("ABCDEF");
        Jmenu.setMnemonic(KeyEvent.VK_ALT);
        for (i=0; i < 5;i++) {
          Jmenu = new JMenu("ABCDEF");
          if (i == 0) Jmenu.setMnemonic(KeyEvent.VK_ALT);
          mi = new JMenuItem("abcdef");
          Jmenu.add(mi);
          jmenubar.add(Jmenu);
        setJMenuBar(jmenubar);
      private void Exit() {
        setVisible(false);
        //setEnabled(false);
        System.exit(0);
      //----- MAIN function ------------
      public static void  main(String args[]) {
        new test14();
    }Thanks

    Thank you for considering this issue!
    Yes, I think this solution is sufficient to resolve it.

Maybe you are looking for

  • Report builder and the AS

    When we run reports in the report builder, does it always use the application server? I have seen some posts where people have said yes and some that have said no, that the report builder is automatically setup to act as the AS. Does anyone have a de

  • Error while executing  view in Bex Analyzer

    Hi Gurus, When i am executing the view(0PY_MC02_Q0102_V02)  in analyzer i am getting the error : Error Group RFC_ERROR_SYSTEM_FAILURE Message Exception condition "NO_VALUE_FOR_SID" raised. I checked all the master data info objects and loaded the mas

  • What is the correct way to restore the catalog after a disk failure?

    I am running the latest Itunes on Vista. The disk failed on my old computer and I have a backup of the catalog file. The music files are on external storage (NAS). I've been searching for instructions on how to restore Itunes. The catalog is about 1

  • How to include jspx in a jspx??

    Hi All, I want to include jspx in another jspx, if i use the below syntax after the panelForm: <afh:rowLayout width="100%"> <jsp:include page="/jsps/admin/generalAdmin/editManProfAttr.jspx"/> </afh:rowLayout> It is throwing an below exception: javax.

  • Table component grid color option

    hello, i'm curious what this option is suppose to do. i have the show grid option checked, and change the color on the grid color option. when i view the grid, i don't see any difference, so i don't know what this option is suppose to change. any hel