Dynamic ActionListener

Hi guys,
had a small problem while associating dynamic ActionListeners to JPopupMenus.
Here is my code
ArrayList feedList = CityTVStartUp.getOperatorSession().getCameraFeeds();
CameraFeedDO cf;
    for (int f = 0; f < feedList.size(); f++) {
      cf = (CameraFeedDO) feedList.get(f);
      jPopupMenuItemFeeds = new JMenuItem();
      jPopupMenuItemFeeds.setText(cf.getTitle());
      jPopupMenuItemFeeds.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println(cf.getTitle() + cf.getIPAddress());
            System.out.println(jPopupMenuItemFeeds.getName());
      jPopupMenu1.add(jPopupMenuItemFeeds);What I am doing here is, creating a popup menus on the basis of number of records in a database and try to add ActionListener on that. But when I run it, it always prints the last record, any ideas how to fix it?

It compiles and works fine, The only problem is, whenever I clicked on PopUp Menu, it always access the last one, thats because its in FOR loop....
I dont have two variables with similar names.
private JMenuItem jPopupMenuItemFeeds; // This is my global variable
CameraFeedDO cf = null; // This is also my global variableI call initComponents() from constructor, and initComponents runs that routine above... I had done similar dynamic anonymous listerners with JButtons and that worked fine, anything special with JPopupMenuItems??

Similar Messages

  • Cannot dynamically add actionlistener to Tab or TabSet

    Hello,
    I have a custom component that must create a Tabbed look. I'm using the Studio Creator TabSet with Tabs. I cannot for the life of me get it to register and use an actionListener. I've done this with other components, but this plain doesn't work (for me). Has anyone been able to use it this way? I've tried numerous approaches and here is the one that's worked for me in other components....
    FacesContext context = FacesContext.getCurrentInstance();
    Application application = context.getApplication();
    ELContext elContext = FacesContext.getCurrentInstance().getELContext();
    ExpressionFactory expressionFactory = application.getExpressionFactory();
    MethodExpression myActionListener = expressionFactory.createMethodExpression(elContext, "#{SCTabsBean.tabClicked}", null, new Class[] {ActionEvent.class});
    And oh yes, I have used the example code for the Woodstock version and also the old fashioned SC version and neither of them worked in my local environment.
    It is not an option for me to use WoodStock at this time. The woodstock components have a new way of registering the themes and it is too risky for an interim build to do this.
    ..\wb

    Hi,
    I use forms in my tabNavigator:
                    <mx:TabNavigator id="tabNavigator"
                                      creationPolicy="all"
                                      styleName="myTabStyle"
                                      click="selectProfile()"
                                      >
                         <mx:Form id="A" label="A" name="very blue" hideEffect="{hideEffect}"  showEffect="{showEffect}" visible="false" >
                             <mx:Label text="Point" />
                             <mx:NumericStepper id="PointA" name="PointA"  minimum="0" maximum="120" styleName="numStepper" color="white" />   
                         </mx:Form>
                 </mx:TabNavigator>
    This is how I access the form and add values to my UI controls:
                            //find child controls dynamically
                            var formObj:Object = tabNavigator.getChildAt(i);
                            var formPoint:Object = formObj.getChildByName("Point" + "A");
                            formPoint.value = 55;
    I hope this can help put you towards the right direction. This was not easy and tabNavigator is not my friend.

  • How to handle dynamic JMenuItem's actionListener??

    I want to implement a function like "Recent File" in "File" menu.
    But I don't know how to handle their actionListener?
    for (int i=0; i<count; i++)
    JMenuItem miNode = new JMenuItem(fileName);
    mnuFile.add(miNode);
    miNode.addActionListener(...) ///// ----- ????????
    }

    for (int i = 0; i < count; i++) {
        final String fileName = ... // the i-th file name
        JMenuItem miNode = new JMenuItem(fileName);
        mnuFile.add(miNode);
        miNode.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // do whatever you want using "fileName" variable
                System.out.println("You have selected the '" + fileName + "' file.");
    }Alternatively you can create one ActionListener and add it to all menu items. When event is fired you can use ActionEvent.getActionCommand() - it will return the text of the JMenuItem (the file name on your case) that caused the event provided that you set only JMenuItem text (as you do in your example).

  • How to get values from dynamic component?

    Hi:
    I am displaying dynamic components based on user selection, where InputText and OutputText display properly. But now i want to read that component value on
    button click. Can any body help me in that?
    Source code is as follow,
    text.xhtml
    *<code>*
    <ui:composition xmlns="http://www.w3.org/1999/xhtml"
         xmlns:h="http://java.sun.com/jsf/html"
         xmlns:f="http://java.sun.com/jsf/core"
         xmlns:ui="http://java.sun.com/jsf/facelets"
         xmlns:p="http://primefaces.prime.com.tr/ui"
         xmlns:ice="http://www.icesoft.com/icefaces/component"
         template="/WEB-INF/includes/templates/page-template.xhtml">
         <ui:define name="page-content">
              <div class="exampleBox splashContainer"
                   style="background: url('./xmlhttp/css/rime/css-images/contentContainer_bg.gif') top repeat-x">
              <table>
                   <tr>
                        <td colspan="2">
                        <h2>Set Request Process Flow</h2>
                        </td>
                   </tr>
                   <tr>
                        <td colspan="2"><ice:messages style="color:red;" /></td>
                   </tr>
                   <tr>
                        <td><ice:outputText value="Request Type*"></ice:outputText></td>
                        <td><ice:selectOneMenu value="#{offlinereq.requestno}"
                             valueChangeListener="#{offlinereq.requestChange}"
                             partialSubmit="true">
                             <f:selectItem itemValue="" itemLabel="--Select--" />
                             <f:selectItems value="#{offlinereq.requests}" />
                        </ice:selectOneMenu></td>
                   </tr>
                   <tr>
                        <td>*<h:panelGroup binding="#{offlinereq.panelBind}">*
    *                    </h:panelGroup>*</td>
                   </tr>
                   <tr>
                        <td colspan="4"><ice:commandButton value="Add"
                             actionListener="#{offlinereq.add}" /> <ice:commandButton
                             value="Update" actionListener="#{offlinereq.update}" /> <ice:commandButton
                             value="Delete" actionListener="#{offlinereq.delete}" /> <ice:commandButton
                             value="Reset" actionListener="#{offlinereq.reset}" /></td>
                   </tr>
              </table>
              </div>
         </ui:define>
    </ui:composition>
    *</code>*
    bean.java
    *<code>*
    //ValuechangeListener
         public void requestChange(ValueChangeEvent e){
              System.out.println("Select Value is::"+e.getNewValue()+"::"+userid);
              Connection conn=null;
              try {
                        if(!panelBind.getChildren().isEmpty())
                             panelBind.getChildren().clear();
                   Class.forName ("oracle.jdbc.OracleDriver");
                   conn = JdbcUtil.getConnection();
                   Statement stmt = conn.createStatement();
                   String sql="select * from IB_CUSTOMER_REQUEST_PARAMETERS where IB_REQMAST_SRNO='"+e.getNewValue()+"'";
                   ResultSet rs = stmt.executeQuery(sql);     
                   String out="out";
                   int i=1;
                   String ii;
                   while(rs.next()) {          
                        FacesContext facesContext = FacesContext.getCurrentInstance();
              Application application = facesContext.getApplication();
              HtmlPanelGrid grid = (HtmlPanelGrid)application.createComponent(HtmlPanelGrid.COMPONENT_TYPE);
                   grid.setColumns(2);
              HtmlOutputText output = (HtmlOutputText)application.createComponent(HtmlOutputText.COMPONENT_TYPE);
                   output.setValue(rs.getString("IB_CUSTREQSTPARA_NAME"));
                   ii=Integer.toString(i);
                   output.setId("a"+ii.toString());
                   System.out.println("id"+ii);
                   HtmlInputText input = (HtmlInputText)application.createComponent(HtmlInputText.COMPONENT_TYPE);
                   //input.setValue(rs.getString(1));
                   grid.getChildren().add(output);
                   grid.getChildren().add(input);
                   panelBind.getChildren().add(grid);
                   i++;
              catch(Exception e1)
                   System.out.println(e1);
         //Action listeners
         public void add(ActionEvent e)
              System.out.println("ADD");
    *</code>*
    Thank You,
    Anup

    Where are you stuck? find the component (UIComponent.findComponent) in the JSF component tree by its ID and get the value from it. This article might help:
    http://illegalargumentexception.blogspot.com/2009/02/jsf-working-with-component-ids.html
    Note: the code tag is \                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to create dynamic View Object and Dynamic Table

    Dear ll
    I want to create a dynamic view object and display the output in a dynamic table on the page.
    I am using Jdeveloper 12c "Studio Edition Version 12.1.2.0.0"
    This what I did:
    1- I created a read only view object with this query "Select sysdate from dual"
    2- I added this View object to the application module
    3- I created a new method that change the query of this View object at runtime
        public void changeVoQuery(String dbViewName) {
            String sqlstm = "Select * From " + dbViewName;
            ViewObject dynamicVo = this.findViewObject("DynamicVo");
            if (dynamicVo != null) {
                dynamicVo.remove();
            dynamicVo = this.createViewObjectFromQueryStmt("DynamicVo", sqlstm);
            dynamicVo.executeQuery();
    4- I run the application module for testing the method and I passed "Scott.Emp" as a parameter and the result was Success
    5- Now I want to show the result of the view on the page, so I draged and dropped the method from the data control as a parameter form
    6- I dragged and dropped the view Object "DynamicVo" as a table and I choose "generate Column Dynamically at runtime". This is the page source
    <af:panelHeader text="#{viewcontrollerBundle.SELECT_DOCUMTN_TYPE}" id="ph1">
            <af:panelFormLayout id="pfl1">
                <af:inputText value="#{bindings.dbViewName.inputValue}" label="#{bindings.dbViewName.hints.label}"
                              required="#{bindings.dbViewName.hints.mandatory}"
                              columns="#{bindings.dbViewName.hints.displayWidth}"
                              maximumLength="#{bindings.dbViewName.hints.precision}"
                              shortDesc="#{bindings.dbViewName.hints.tooltip}" id="it1">
                    <f:validator binding="#{bindings.dbViewName.validator}"/>
                </af:inputText>
                <af:button actionListener="#{bindings.changeVoQuery.execute}" text="changeVoQuery"
                           disabled="#{!bindings.changeVoQuery.enabled}" id="b1"/>
            </af:panelFormLayout>
        </af:panelHeader>
        <af:table value="#{bindings.DynamicVo.collectionModel}" var="row" rows="#{bindings.DynamicVo.rangeSize}"
                  emptyText="#{bindings.DynamicVo.viewable ? 'No data to display.' : 'Access Denied.'}"
                  rowBandingInterval="0" selectedRowKeys="#{bindings.DynamicVo.collectionModel.selectedRow}"
                  selectionListener="#{bindings.DynamicVo.collectionModel.makeCurrent}" rowSelection="single"
                  fetchSize="#{bindings.DynamicVo.rangeSize}" filterModel="#{bindings.DynamicVoQuery.queryDescriptor}"
                  queryListener="#{bindings.DynamicVoQuery.processQuery}" filterVisible="true" varStatus="vs" id="t1"
                  partialTriggers="::b1">
            <af:iterator id="i1" value="#{bindings.DynamicVo.attributesModel.attributes}" var="column">
                <af:column headerText="#{column.label}" sortProperty="#{column.name}" sortable="true" filterable="true"
                           id="c1">
                    <af:dynamicComponent id="d1" attributeModel="#{column}"
                                         value="#{row.bindings[column.name].inputValue}"/>
                </af:column>
            </af:iterator>
        </af:table>
    when I run the page this error is occured
    <Nov 13, 2013 2:51:58 PM AST> <Error> <oracle.adfinternal.view.faces.webapp.rich.RegistrationFilter> <BEA-000000> <ADF_FACES-60096:Server Exception during PPR, #1
    javax.el.ELException: java.lang.NullPointerException
    Caused By: java.lang.NullPointerException
    Can any body help me please
    thanks

    Have you seen Shay's video https://blogs.oracle.com/shay/entry/adf_faces_dynamic_tags_-_for_a
    All you have to do is to use the dynamic table to get your result.
    Timo

  • How can I avoid running out of memory when creating components dynamically

    Hello everyone,
    Recently, I am planning to design a web application. It will be used by all middle school teachers in a region to make examination papers and it must contain the following main functions.
    1)Generate test questions dynamically. For instance, a teacher who logs on the web application will only see a select one menu and a Next Quiz button. The former is used for determining the number of options for the current multiple/single choice question. The later is dedicated to creating appropriate input text elements according to the selected option number. That is to say, if the teacher selects 4 in the menu and presses the Next Quiz button, 5 input text form elements will appear. The first one is for the question to be asked such as "1.What is the biggest planet in the solar system?", the others are optional answers like a)Uranus. b) Saturn. c)Jupiter. d)Earch. Each answer stands for an input text elements. When the teacher fills in the fourth answer, another select one menu and Next Quiz button will emerge on the fly just under this answer, allowing the teacher to make the second question. The same thing repeats for the following questions.
    2)Undo and Redo. Whenever a teacher wants to roll back or redo what he has done, just press the Undo or[i] Redo button. In the previous example, if the teacher selects the third answer and presses the Delete button to drop this answer, it will delete both the literal string content[i] and the input text element, changing the answer d to c automatically. After that, he decides to get back the original answer c, Jupiter, he can just click the Undo button as if he hadn�ft made the deleting operation.
    3)Save the unfinished working in the client side. If a teacher has done half of his work, he can choose to press the Save button to store what he has done in his computer. The reason for doing so is simply to alleviate the burden of the server. Although all finished test papers must be saved in a database on the server, sometimes the unfinished papers could be dropped forever or could form the ultimate testing papers after several months. So if these papers keep in the server, it will waste the server computer�fs room. Next time the teacher can press the Restore button on the page to get the previously stored part of the test paper from his own computer and continue to finish the whole paper.
    4)Allow at least 1,000 teachers to make test papers at the same time. The maximum question number per examination paper is 60.
    Here are my two rough solutions,
    A.Using JSF.
    B.Using JavaScript and plain JSP[b] without JSF.
    The comparison of the two solutions:
    1)Both schemas can implement the first and the second requirements. In JSF page I could add a standard panelGird tag and use its binding attribute. In the backing bean, the method specified by the binding attribute is responsible for generating HtmlInput objects and adding them to the HtmlPanelGird object on the fly. Every HtmlInput object is corresponding to a question subject or an optional answer. The method is called by an actionListener, which is registered in the Next Quiz commandButton, triggering by the clicking on this button in the client side. Using JSF can also be prone to managing the HtmlInput objects, e.g. panelGird.getChildren().add(HtmlInput) and panelGird.getChildren().remove(HtmlInput) respond to the undoing operation of deleting an optional answer and the redoing operation of the deleting action respectively. I know JavaScript can also achieve these goals. It could be more complex since I don�ft know well about JavaScript.
    2)I can not find a way to meet the third demand right now. I am eager to know your suggestion.
    3)Using JSF, I think, can�ft allow 1,000 teachers to do their own papers at the same time. Because in this scenario, suppose each questionnaire having 60 questions and 4 answers per question, there will be approximately 300,000 HtmlInput objects (1,000X60X(4+1)) creating on the server side. The server must run out of memory undoubtedly. To make things better, we can use a custom component which can be rendered as a whole question including its all optional answers. That is to say, a new custom component on the server side stands for a whole question on the client side. Even so, about 60,000(1,000X60) this type of custom components will be created progressively and dynamically, plus other UISelectOne and UICommand objects, it also can�ft afford for most servers. Do I have to use JavaScript to avoid occupying the server's memory in this way? If so, I have to go back and use JavaScript and plain JSP without JSF.
    Thank you in advance!
    Best Regards, Ailsa
    2007/5/4

    Thank you for your quick response, BalusC. I really appreciate your answer.
    Yes, you are right. If I manually code the same amount of those components in the JSF pages instead of generating them dynamically, the server will still run out of memory. That is to say, JSF pages might not accommodate a great deal of concurrent visiting. If I upgrade the server to just allow 1,000 teachers making their own test papers at the same time, but when over 2,000 students take the same questionnaire simultaneously, the server will need another upgrading. So I have to do what you have told me, using JS+DOM instead of upgrading the server endlessly.
    Best Regards, Ailsa

  • Dynamic cast at runtime (Here we go again! )

    Hy folks,
    today I read so many entries about dynamic casting. But no one maps to my problem. For a lot of them individual alternatives were found. And so I hope...
    Ok, what's my problem?
    here simplified:
    I have a HashMap with couples of SwingComponents and StringArray[3].
    The SwingComponents are stored as Objects (they are all JComponents).
    The StringArray comprised "the exact ClassName" (like "JButton" or "JPanel"),
    "the method, who would be called" (like "addItemListener")
    and "the ListenerName" (like "MouseMotionListener" or "ActionListener")
    At compiletime I don't know, what JCommponent gets which Listener.
    So a JPanel could add an ItemListener, another JPanel could add
    a MouseListener and an ActionListener.
    I get the description of the GUI not until runtime.
    The 'instanceof'-resolution is not acceptable, because there are above 50 listener. If I write such a class, I would write weeks for it, and it will be enormous.
    Now, my question
    I get the class of the Listenertype by
    Class c=Class.forName(stringArray[2]);
    and the method I'll call
    java.lang.reflect.Method method=component.getClass().getDeclaredMethod(s[1],classArrayOfTheParameter[]); //the parameter is not important here
    And I have a class, who implements all required ListenerInterfaces: EHP
    Now I wish something like this
    method.invoke((JPanel)jcomponent,(c)EHP);
    Is there anybode, who can give me an alternative resolution
    without instanceof or switch-case ?
    Greatings egosum

    I see, your right. Thanks. This problem is been solved.
    But a second problem is, that jcomponent can be every Swing-Object.
    I get the swing-component as Object from the HashMap . And I know
    what it is exactly by a String.
    What I need here is
    method.invoke(("SwingType")swingcomponentObject,Object[] args);
    I know, that this doesn't exist. Here my next question
    Can I take an other structure than HashMap, where the return value
    is a safety type (and not an Object). Or there are some other hints
    about similar problems and there resolutions?
    I don't like to write 50 (or even more than 50) "instanceOf"-instructions or "equal"-queries. And I'm not really interested in the whole set of java swing elements existing.
    I appreciate all the help I can get.
    With regards egosum

  • Dynamic jmenu bar

    i have a dynamic JMenu on a jframe. The menu is populated by looking up database entries and ptting them into the right place. This is done by a method 'menus()'.
    I also have an addingredients class which adds new ingredient entries into the database, problem is when it does this, the JMenu has to be repopulated. The following code shows the main frame
    // Recipe Creation GUI
    // Written by Michael Emett
    // Monday 15th Decemeber 2003
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JFrame.*;
    import java.sql.*;
    import java.util.*;
    public class TextAreaDemo extends JFrame     {
    private static JTextArea part1;
    private JButton Browse, Enter, Preview, Remove;
    public static JList printList, newList;
    private JCheckBox pic;
    private JLabel namePrompt, title1, title2, title3;
    private static JTextField nameInput;
    private JPanel jp, jp1, jp2, jp3, jp4, jp5;
    private Connection con;
    private Statement stmt;
    public static JMenu fileMenu;
    private static JMenuBar bar;
    // additions /////////////////////////////////////////////////////////////////////////
    //set up GUI
    public TextAreaDemo()     {
    super( "Recipe Entry Sheet" );
    // set up File menu and its menu items
    // Menu and button Initialization ////////////////////////////////////////////////////
    //myMouse = new MyMouseAdapter();
    //final JMenu
    fileMenu = new JMenu( "Ingredients");
             fileMenu.setMnemonic( 'I' );
    fileMenu.add(menus());
    bar = new JMenuBar();
    setJMenuBar( bar );
    JMenu file = new JMenu( "File");
    file.setMnemonic( 'F' );
        bar.add(file);
              JMenuItem Adder = new JMenuItem( "New Ingredient");
             Adder.setMnemonic( 'N' );
    JMenuItem Subber = new JMenuItem( "New subMenu");
             Subber.setMnemonic( 'S' );
             // set up About... menu item
             JMenuItem aboutItem = new JMenuItem( "About..." );
             aboutItem.setMnemonic( 'A' );
    namePrompt = new JLabel( "Recipe Name " );
    nameInput = new JTextField( 20 );
    title1 = new JLabel( "Selected ingredients" );
    title3 = new JLabel( "Please enter the Recipe Instructions" );
    title2 = new JLabel( "Enter The SubMenu Name " );
    pic = new JCheckBox("Add Picture", false);
    file.add( Adder );
         Adder.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
                        getList f = new getList();
    // Add Ingredient menu item //////////////////////////////////////////////////////////
    file.add( Subber );
         Subber.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
                        AddSubMenu f = new AddSubMenu();
    // About menu item ///////////////////////////////////////////////////////////////////
    file.add( aboutItem );
          aboutItem.addActionListener(
             new ActionListener() {  // anonymous inner class
                // display message dialog when user selects About...
                public void actionPerformed( ActionEvent event )
                   JOptionPane.showMessageDialog( TextAreaDemo.this,
                      "Developed by Michael Emett, 2004",
                      "About", JOptionPane.PLAIN_MESSAGE );
              }     // end anonymous inner class
         );  // end call to addActionListener
    // Exit menu item ////////////////////////////////////////////////////////////////////
         JMenuItem exitItem = new JMenuItem( "Exit" );
         exitItem.setMnemonic( 'x' );
         file.add( exitItem );
          exitItem.addActionListener(
             new ActionListener() {  // anonymous inner class
                // terminate application when user clicks exitItem
                public void actionPerformed( ActionEvent event )
                   System.exit( 0 );
             }  // end anonymous inner class
          ); // end call to addActionListener
    //create Button Enter
    Enter = new JButton("Enter");
    Enter.addActionListener(
              new ActionListener()     {
                              public void actionPerformed( ActionEvent event )
                        StringBuffer a = new StringBuffer();
                        StringBuffer b = new StringBuffer();
                        StringBuffer c = new StringBuffer();
                        for(int i= 0; i< victor.size(); i++){
                        b.append(victor.elementAt(i));
                        b.append("; ");
                        a.append(nameInput.getText());
                        c.append(part1.getText());
                        //System.out.println(a);
                        //System.out.println(b);
                        //System.out.println(c);
                        InsertRecipe f = new InsertRecipe(a,b,c);
                        //invalidate();
                //fileMenu.updateUI();
               // fileMenu.revalidate();
    //create Button Remove
    Remove = new JButton("Remove");
    //add Actionlistener
    Remove.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
    int[] arr;
    arr = printList.getSelectedIndices();
    int counter = 0;
         for (int i= 0; i< arr.length; i++){
              int n=arr;
              victor.remove(n-counter);
              counter++;
    printList.setListData(victor);
    //create Button Remove
    Browse = new JButton("Browse");
    //create Button Preview
    Preview = new JButton("Clear");
    Preview.addActionListener(
    new ActionListener() {  // anonymous inner class
    // display message dialog when user selects Preview...
    public void actionPerformed( ActionEvent event )
    int result = JOptionPane.showConfirmDialog
                             (null,      "Are you sure to want to clear this form", "Clear?",      JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
                             if(result == JOptionPane.YES_OPTION)
                             {TextAreaDemo.clear();
                                  //System.out.println("Recipe Entered");
              }//end of joptionpane
    printList = new JList();
    printList.setVisibleRowCount(9);
    printList.setFixedCellWidth(150);
    printList.setFixedCellHeight(15);
    printList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
    newList = new JList();
    newList.setVisibleRowCount(9);
    newList.setFixedCellWidth(150);
    newList.setFixedCellHeight(15);
    newList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION );
    // Initialise Text Areas //
    part1 = new JTextArea( 25, 50);
    part1.setFont(new Font("Courier", Font.BOLD, 12));
    part1.setLineWrap(true);
    part1.setWrapStyleWord(true);
    // JPanels for Layout //
    jp = new JPanel();
    jp1 = new JPanel();
    jp2 = new JPanel();
    jp3 = new JPanel();
    jp4 = new JPanel();
    jp5 = new JPanel();
    final Container c = getContentPane();
    GridBagLayout gbl = new GridBagLayout();
    GridBagConstraints gbc = new GridBagConstraints();
         c.setLayout(gbl);
         gbc.weightx = 0.1;
         gbc.weighty = 0.5;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    add(jp1, gbc, 0, 0, 1, 1);
    gbc.fill = GridBagConstraints.NONE;
    add(jp2, gbc, 0, 1, 1, 1);
    add(jp3, gbc, 1, 0, 2, 2);
    jp1.add(jp4, BorderLayout.CENTER);
    jp2.add(jp, BorderLayout.CENTER);
    bar.add( namePrompt );
    bar.add( nameInput);
    bar.add( fileMenu );
    jp4.setLayout(new BorderLayout());
    jp4.add(title1, BorderLayout.NORTH);
    jp4.add(new JScrollPane( printList), BorderLayout.CENTER);
    jp4.add(Remove, BorderLayout.SOUTH);
    jp.setLayout(new BorderLayout());
    jp.add(pic, BorderLayout.NORTH);
    jp.add(new JScrollPane (newList), BorderLayout.CENTER);
    jp.add(Browse, BorderLayout.SOUTH);
    jp3.setLayout(new BorderLayout());
    jp3.add (title3, BorderLayout.NORTH);
    jp3.add (new JScrollPane(part1), BorderLayout.CENTER);
    //c.addMouseListener(myMouse);
    gbc.anchor = GridBagConstraints.LAST_LINE_END;
    add(jp5, gbc, 2, 3, 1, 1);
    jp5.setLayout(new FlowLayout());
    jp5.add(Preview);
    jp5.add(Enter);
    setSize(770, 620);
         pack();
         setVisible(true);
         setResizable(false);
    private static Vector victor = new Vector();
    public static void printListset(String t) {
         victor.add(t);
    for(int i = 0; i<victor.size(); i++)
    printList.setListData(victor);
    public void add(Component ce, GridBagConstraints constraints, int x, int y, int w, int h) {
                   constraints.gridx = x;
                   constraints.gridy = y;
                   constraints.gridwidth = w;
                   constraints.gridheight = h;
                   getContentPane().add(ce, constraints);
    public static JMenu menus()     {
         // Map Created to Handle JMenuItem Addition //
              Map labelToMenu = new HashMap();
              Map labelToMenu2 = new HashMap();
              Map labelToMenu3 = new HashMap();
              String url = "jdbc:odbc:database";
              Connection con;
              Statement stmt;
                        try     {
                             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        catch(ClassNotFoundException e)     {
                        System.err.print("Class Not found");
                        String query = "select baseIngred.IngredientType, baseIngred.PrimaryKey FROM baseIngred";
                        String query2 = "select baseIngred.IngredientType, baseIngred.PrimaryKey,"
                        + "subMenu.menuNumber, subMenu.subMenu FROM baseIngred, "
                        + "subMenu WHERE baseIngred.PrimaryKey = subMenu.menuNumber ORDER BY submenu";
                                  String query3 = "select subMenu.subMenu, subMenu.PrimaryNumber,"
                                       + "Ingredient.Ingredient, Ingredient.MenuNumber FROM subMenu, Ingredient"
                        + " WHERE Ingredient.MenuNumber = subMenu.PrimaryNumber ORDER BY PrimaryNumber";
         String query4 = "select Ingredient.Ingredient, Ingredient.MenuNumber FROM Ingredient";
                             try     {
                                       con = DriverManager.getConnection(url, "myLogin", "myPassword");
                                       stmt = con.createStatement();
         // Initial Jmenu added ///////////////////////////////////////////////////////////////
                   ResultSet rs = stmt.executeQuery(query);
                   String[] arr = new String[100];
                   int[] num = new int[200];
                   int[] num2 = new int[200];
                   int counter = 0;
                   int counter2 = 0;
                   while     (rs.next())     {
                                  //String t is set to the value contained in ingredient type
                                  String t = rs.getString("IngredientType");
                                  //map labelToMenu has String t and a new JMenu with the menu
                                  //name contained in t stored in it
                                  labelToMenu.put(t, fileMenu.add(new JMenu(t)));
                                  //an array containing values of the priamry key is produced
                                  num[counter] = rs.getInt("PrimaryKey");
                                  //a counter is incremeted so that upon further
                                  //interations it is stored in a new array field
                                  counter++;
         // Second Jmenu added ////////////////////////////////////////////////////////////////
                   ResultSet rs2 = stmt.executeQuery(query2);
                   while     (rs2.next()) {
                                  //String first is set to the value contained in ingredient type
                                  String first = rs2.getString("IngredientType");
                                  //String second is set to the value contained in subMenu
                                  String second = rs2.getString("subMenu");
                                  //firstlevel looks up item t in the map, and creates a jmenu name as it.
                                  JMenu firstLevel = (JMenu)labelToMenu.get(first);
                                  //handles menu placement by comparing PrimaryKeys with MenuNumbers
                                  // f = rs2.getInt("menuNumber");
                                  num2[counter2] = rs2.getInt("menuNumber");
         for (int nm = 0; nm<num.length; nm++){
                   if (num[nm] == num2[counter2]
                                            //adds the second value to the jmenu with th name stored in t.
                                            labelToMenu2.put(second, (firstLevel.add(new JMenu (second))));
                                       }counter2++;
         // Third JMenu added /////////////////////////////////////////////////////////////////
         ResultSet rs3 = stmt.executeQuery(query3);
              while     (rs3.next()) {
                                  //String next is set to the value contained in subMenu
                                  String next = rs3.getString("subMenu");
                                  //String third is set to the value contained in ingredient
                                  String third = rs3.getString("Ingredient");
                                  JMenu secondLevel = (JMenu)labelToMenu2.get(next);
                                  int f2 = rs3.getInt("MenuNumber");
                                  //System.out.println(f2);
                                  int f3 = rs3.getInt("PrimaryNumber");
                   if (f3 == f2){
                             labelToMenu3.put(third, secondLevel.add(new JMenuItem(third)));
         // Add AtionListeners ////////////////////////////////////////////////////////////////
         ResultSet rs4 = stmt.executeQuery(query4);
              while     (rs4.next()) {
                   String third2 = rs4.getString("Ingredient");
         JMenuItem thirdLevel = (JMenuItem)labelToMenu3.get(third2);
         thirdLevel.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   JMenuItem source = (JMenuItem)(e.getSource());
                   String actionText = source.getText();
                   PopUp pop = new PopUp(actionText);
                        stmt.close();
                        con.close();
                             }catch(SQLException ex)     {
                        System.err.println(ex);
    return (fileMenu);
         //                                        End Of Connection                                             //
         // Add subMenu menu item /////////////////////////////////////////////////////////////
    public static void clear()     {
    nameInput.setText("");
    victor.removeAllElements();
    printList.setListData(victor);
    part1.setText("");
    public static void rebuild()     {
    fileMenu.removeAll();
    fileMenu.add(menus());
    bar.add( fileMenu );
    public static void main(String args[])     {
         TextAreaDemo t = new TextAreaDemo();
         t.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
    the code inside the method 'rebuild()' will work from inside the main JFrame body if assigned to a button (such as the example position denoted by HERE in the code), but that is undesirable as it requires the user to refresh manually every time they add a new ingredient. what i need is a method that can be called from another class/method/whatever.
    thankyou for any help you can offer, it is much appreciated

    The code you offered did not solve my problem. I have since entered the followinginto the actionlistener of a button on the JFrame,
    refreshMenu = new JButton("Refresh Menu");
    refreshMenu.addActionListener(
             new ActionListener() { 
                // display message dialog when user selects Preview...
                public void actionPerformed( ActionEvent event )
    fileMenu.removeAll();
    fileMenu.add(menus());
    bar.add( fileMenu );          
    );This does what i need, but i need these statements to be made from an external class, not a JButton,

  • Help needed, Createing Dynamic User input

    Hello,
    I am attempting to create some dynamic user input by "predicting" what the user requires in a text box.
    For example if the user enters "Smi" I have a select list pop up which gives the user all options that begin with "Smi".
    I am able to achieve the popups but the interface is quite jerky and not terribly responsive I am trying to solve this by using a thread which starts and stops when new input is received but it is still not quite right.
    The program uses a Sorted TreeSet to hold the data (I thought this would give me a quick search time) and a simple interface at this stage.
    Any help would be fantastic
    Thanks in advance :P
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.text.*;
    import java.util.*;
       /** This program represents part of a larger user interface for allowing the
       user to select data from a file or database.
       <p>
       When the program starts up, it will read in data from a given file, and hold
       it in some type of container allowing rapid access.
       <p>
       The user may then type in the first few letters of the surname of a person,
       and this program should immediately present in a popup dialog the names which
       match.  The user will be able to click on one of the names in the popup and
       that will cause all data about that person to be displayed in the JTextArea
       at the bottom of the window.
       <p>
       This program requires the FormLayout.class, FormLayout$Placement.class, and
       FormLayout$Constraint.class files in the same directory
       (folder) or in its classpath.  These is provided separately.
    class PartMatch extends JFrame implements Runnable
                        /** Close down the program. */
       JButton quitbtn;
                        /** Field for the surname. */
       JTextField namefld;
                        /** Full details of the person(s). */
       JTextArea  results;
                        /** Popup dialog to display the names and addresses which
                        match the leading characters given in namefld. */
       Chooser matches;
                      /** Default background color for a window. */
       final static  Color            defBackground = new Color(0xD0C0C0);
                      /** Default foreground color for a window. */
       final static  Color            defForeground = new Color(0x000000);
                      /** Default background color for a field */
       final static  Color            fldBackground = new Color(0xFFFFFF);
                      /** Default background color for a button */
       final static  Color            btnBackground = new Color(0xF0E0E0);
       final static  Color            dkBackground = new Color(0xB0A0A0);
                      /** Larger font */
       final static  Font bold = new Font("Helvetica", Font.BOLD, 30);
       TreeSet members;
       String input;
       String[] found;
       public static void main(String arg[])
          UIManager.put("TextField.background",fldBackground);
          UIManager.put("TextField.foreground",defForeground);
          UIManager.put("TextField.selectionBackground",btnBackground);
          UIManager.put("TextArea.background",fldBackground);
          UIManager.put("TextArea.foreground",defForeground);
          UIManager.put("TextArea.selectionBackground",btnBackground);
          UIManager.put("Panel.background",defBackground);
          UIManager.put("Label.background",defBackground);
          UIManager.put("Label.foreground",defForeground);
          UIManager.put("Button.background",btnBackground);
          UIManager.put("Button.foreground",defForeground);
          UIManager.put("CheckBox.background",defBackground);
          UIManager.put("ScrollBar.background",defBackground);
          UIManager.put("ScrollBar.thumb",btnBackground);
          UIManager.put("ComboBox.background",btnBackground);
          UIManager.put("ComboBox.selectionBackground",dkBackground);
          PartMatch trial = new PartMatch(arg);
       public PartMatch( String [] arg )
          super("Part Match");
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          Container cpane = getContentPane();
          FormLayout form = new FormLayout(cpane);
          JLabel lab1 = new JLabel("Fetch details") ;
          lab1.setFont( bold );
          form.setTopAnchor( lab1, 4 );
          form.setLeftAnchor( lab1, 4 );
          JLabel lab2 = new JLabel("Surname: ") ;
          form.setTopRelative( lab2, lab1, 4 );
          form.setLeftAlign( lab2, lab1 );
          namefld = new JTextField( 30 );
          form.setBottomAlign( namefld, lab2 );
          form.setLeftRelative( namefld, lab2, 4 );
          namefld.addCaretListener( new CaretListener()
             public void caretUpdate(CaretEvent e)
                 showMatches();
          quitbtn = new JButton( "Quit" );
          quitbtn.addActionListener( new ActionListener()
             public void actionPerformed(ActionEvent e)
                quitProcessing();
          form.setBottomAlign( quitbtn, namefld );
          form.setLeftRelative( quitbtn, namefld, 15 );
          results = new JTextArea( 10,50 );
          results.setEditable(false);
          JScrollPane jsp = new JScrollPane( results,
                                     JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                     JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
          form.setTopRelative( jsp, lab2, 6 );
          form.setLeftAlign( jsp, lab2 );
          form.setBottomAnchor( jsp, 5 );
          form.setRightAnchor( jsp, 5 );
          form.setRightAnchor( quitbtn, 5 );
          matches = new Chooser( this );
          //matches.setUndecorated(true);
          pack();
          setVisible(true);
          namefld.requestFocus();
          if (arg.length > 0) init(arg[0]);
          else init("triathlon.txt"); //<<<<<<<<<<<<<<<< Place the default filename here
          /** Called once only, at the end of the constructor, to read the data
            * from the membership file.
       public void init( String fname )
          members = new TreeSet();
           try {
               FileReader fr = new FileReader(new File (fname));
               Scanner scan = new Scanner(fr);
               trimember cmem;
               String cLine, eTag, memberNo, first, last, gender, yob, tel ,addr,
                       club;
               while(scan.hasNextLine())
                   cLine = scan.nextLine();
                   Scanner scan2 = new Scanner(cLine);
                   scan2.useDelimiter(";");
                   eTag = scan2.next().trim();
                   memberNo = scan2.next().trim();
                   first = scan2.next().trim();
                   last = scan2.next().trim();
                   gender = scan2.next().trim();
                   yob = scan2.next().trim();
                   tel = scan2.next().trim();
                   addr = scan2.next().trim();
                   club = scan2.next().trim();
                   cmem = new trimember(eTag, memberNo, first, last, gender, yob,
                           tel, addr, club);
                   members.add(cmem);
           catch (FileNotFoundException ex)
               results.append("Sorry can't find the input file\n");
               results.append("Please check file name and location and try again");
               ex.printStackTrace();
          /** Called every time there is a change in the contents of the text field
            * namefld.  It will first clear the text area.  It then needs to search
            * through the container of data to find all records where the surname
            * starts with the characters that have been typed.  The names and
            * addresses need to be set up as strings and placed in
            * an array of Strings.  This can be placed in the "matches" window and
            * displayed for the user, inviting one to be selected.
            * <p>
            * The performance of this is very important.  If necessary, it may be
            * necessary to run as a separate thread so that the user interface is
            * not delayed.  It is essential that the user be able to type letters at a
            * reasonable speed and not have the keystroke processing held up by
            * previous text.
       public void showMatches( )
           run();
                // First clear the text area
          //results.setText("");
                // Determine the leading characters of the surname that is wanted
                input = namefld.getText();
                // Locate the data for this name, and display each matching item
                //  in the JTextArea ...
                // Example of how to set the data in the popup dialog
          matches.list.setListData(found);
          matches.pack();   // resize the popup
                // set the location of the popup if it is not currently visible
          if ( ! matches.isVisible())
             Dimension sz = matches.getSize();
             Point mouse = getMousePosition();
             Point framepos = getLocation();
             int x=0, y=0;
             if (mouse == null)
                Point pt = results.getLocation();
                x = pt.x + 20 + framepos.x;
                y = pt.y + 20 + framepos.y;
             else
                x = mouse.x - 2 + framepos.x;
                y = mouse.y - 2 + framepos.y;
             matches.setLocation(x,y);
          matches.setVisible(true);
          namefld.requestFocus();
          /** Perform any final processing before closing down.
       public void quitProcessing( )
          // Any closing work.  Then
          System.exit(0);
        public void run()
            ArrayList<String> foundit = new ArrayList<String>();
            System.out.println(input);
            if(input != null)
            Iterator it = members.iterator();
            while(it.hasNext())
               trimember test = (trimember) it.next();
               if (test.last.startsWith(input))
                   foundit.add(test.last +", "+ test.first);
            found = new String[foundit.size()];
            for(int i=0; i<foundit.size();i++)
                found[i] = foundit.get(i);
         /** A window for displaying names and addresses from the data set which
          match the leading characters in namefld.
          <p>
          This will automatically pop down if the user moves the mouse out of the
          window.
          <p>
          It needs code added to it to respond to the user clicking on an item in
          the displayed list. */
       class Chooser extends JWindow
                /** To display a set of names and addresses that match the leading
                characters of the namefld text field. */
          public JList list = new JList();
          Chooser( JFrame parent )
             super( parent );
             Container cpane = getContentPane();
             cpane.addMouseListener( new MouseAdapter()
                public void mouseExited(MouseEvent e)
                   Chooser.this.setVisible(false);
             cpane.add("Center",list);
             list.addListSelectionListener( new ListSelectionListener()
                public void valueChanged(ListSelectionEvent e)
                   Chooser.this.setVisible(false);
                   System.out.println("ValueChanged");
                   // First clear the text area
                   results.setText("");
                   String in = (String) list.getSelectedValue();
                   System.out.println("Selected Value was : "+in);
                   String[] inlf = in.split(", ");
                   System.out.println("inlf[0]:"+inlf[0]+" inlf[1]:"+inlf[1]);
                   results.append("Surname \tFirst \teTag \tMemberNo \tSex \tYOB " +
                           "\tTel \tAddress \t\t\tClub\n");
                   Iterator it = members.iterator();
                   while(it.hasNext())
                       trimember test = (trimember) it.next();
                       if (test.last.equals(inlf[0])&&test.first.equals(inlf[1]))
                           results.append(test.toString()+"\n");
                   namefld.requestFocus();
          public class trimember implements Comparable
           String eTag;
           public String memberNo;
           public String first;
           public String last;
           String gender;
           String yob;
           String tel;
           String addr;
           String club;
           public trimember(String eT, String me, String fi, String la,
                   String ge, String yo, String te, String ad, String cl)
               eTag = eT;
               memberNo = me;
               first = fi;
               last = la;
               gender = ge;
               yob = yo;
               tel = te;
               addr = ad;
               club = cl;         
           //To String method to output string of details
           public String toString()
               return last + "\t" + first + "\t" + eTag + "\t" +
                       memberNo + "\t" + gender + "\t" + yob + "\t"+ tel + "\t" +
                       addr + "\t" + club;
           //Compare and sort on Last name
           public int compareTo(Object o)
               trimember com = (trimember) o;
               int lastCmp = last.compareTo(com.last);
               int firstCmp = first.compareTo(com.first);
               int memCmp = memberNo.compareTo(com.memberNo);
               if (lastCmp == 0 && firstCmp !=0)return firstCmp;
               else if (lastCmp==0&&firstCmp==0)return memCmp;
               else return lastCmp;
    }

    Please don't cross-post. It is considered very rude to do that here:
    http://forum.java.sun.com/thread.jspa?messageID=9953193

  • Help needed, Providing Dynamic User input

    Hello,
    I am attempting to create some dynamic user input by "predicting" what the user requires in a text box.
    For example if the user enters "Smi" I have a select list pop up which gives the user all options that begin with "Smi".
    I am able to achieve the popups but the interface is quite jerky and not terribly responsive I am trying to solve this by using a thread which starts and stops when new input is received but it is still not quite right.
    The program uses a Sorted TreeSet to hold the data (I thought this would give me a quick search time) and a simple interface at this stage.
    Any help would be fantastic
    Thanks in advance :P
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.text.*;
    import java.util.*;
       /** This program represents part of a larger user interface for allowing the
       user to select data from a file or database.
       <p>
       When the program starts up, it will read in data from a given file, and hold
       it in some type of container allowing rapid access.
       <p>
       The user may then type in the first few letters of the surname of a person,
       and this program should immediately present in a popup dialog the names which
       match.  The user will be able to click on one of the names in the popup and
       that will cause all data about that person to be displayed in the JTextArea
       at the bottom of the window.
       <p>
       This program requires the FormLayout.class, FormLayout$Placement.class, and
       FormLayout$Constraint.class files in the same directory
       (folder) or in its classpath.  These is provided separately.
    class PartMatch extends JFrame implements Runnable
                        /** Close down the program. */
       JButton quitbtn;
                        /** Field for the surname. */
       JTextField namefld;
                        /** Full details of the person(s). */
       JTextArea  results;
                        /** Popup dialog to display the names and addresses which
                        match the leading characters given in namefld. */
       Chooser matches;
                      /** Default background color for a window. */
       final static  Color            defBackground = new Color(0xD0C0C0);
                      /** Default foreground color for a window. */
       final static  Color            defForeground = new Color(0x000000);
                      /** Default background color for a field */
       final static  Color            fldBackground = new Color(0xFFFFFF);
                      /** Default background color for a button */
       final static  Color            btnBackground = new Color(0xF0E0E0);
       final static  Color            dkBackground = new Color(0xB0A0A0);
                      /** Larger font */
       final static  Font bold = new Font("Helvetica", Font.BOLD, 30);
       TreeSet members;
       String input;
       String[] found;
       public static void main(String arg[])
          UIManager.put("TextField.background",fldBackground);
          UIManager.put("TextField.foreground",defForeground);
          UIManager.put("TextField.selectionBackground",btnBackground);
          UIManager.put("TextArea.background",fldBackground);
          UIManager.put("TextArea.foreground",defForeground);
          UIManager.put("TextArea.selectionBackground",btnBackground);
          UIManager.put("Panel.background",defBackground);
          UIManager.put("Label.background",defBackground);
          UIManager.put("Label.foreground",defForeground);
          UIManager.put("Button.background",btnBackground);
          UIManager.put("Button.foreground",defForeground);
          UIManager.put("CheckBox.background",defBackground);
          UIManager.put("ScrollBar.background",defBackground);
          UIManager.put("ScrollBar.thumb",btnBackground);
          UIManager.put("ComboBox.background",btnBackground);
          UIManager.put("ComboBox.selectionBackground",dkBackground);
          PartMatch trial = new PartMatch(arg);
       public PartMatch( String [] arg )
          super("Part Match");
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          Container cpane = getContentPane();
          FormLayout form = new FormLayout(cpane);
          JLabel lab1 = new JLabel("Fetch details") ;
          lab1.setFont( bold );
          form.setTopAnchor( lab1, 4 );
          form.setLeftAnchor( lab1, 4 );
          JLabel lab2 = new JLabel("Surname: ") ;
          form.setTopRelative( lab2, lab1, 4 );
          form.setLeftAlign( lab2, lab1 );
          namefld = new JTextField( 30 );
          form.setBottomAlign( namefld, lab2 );
          form.setLeftRelative( namefld, lab2, 4 );
          namefld.addCaretListener( new CaretListener()
             public void caretUpdate(CaretEvent e)
                 showMatches();
          quitbtn = new JButton( "Quit" );
          quitbtn.addActionListener( new ActionListener()
             public void actionPerformed(ActionEvent e)
                quitProcessing();
          form.setBottomAlign( quitbtn, namefld );
          form.setLeftRelative( quitbtn, namefld, 15 );
          results = new JTextArea( 10,50 );
          results.setEditable(false);
          JScrollPane jsp = new JScrollPane( results,
                                     JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                     JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
          form.setTopRelative( jsp, lab2, 6 );
          form.setLeftAlign( jsp, lab2 );
          form.setBottomAnchor( jsp, 5 );
          form.setRightAnchor( jsp, 5 );
          form.setRightAnchor( quitbtn, 5 );
          matches = new Chooser( this );
          //matches.setUndecorated(true);
          pack();
          setVisible(true);
          namefld.requestFocus();
          if (arg.length > 0) init(arg[0]);
          else init("triathlon.txt"); //<<<<<<<<<<<<<<<< Place the default filename here
          /** Called once only, at the end of the constructor, to read the data
            * from the membership file.
       public void init( String fname )
          members = new TreeSet();
           try {
               FileReader fr = new FileReader(new File (fname));
               Scanner scan = new Scanner(fr);
               trimember cmem;
               String cLine, eTag, memberNo, first, last, gender, yob, tel ,addr,
                       club;
               while(scan.hasNextLine())
                   cLine = scan.nextLine();
                   Scanner scan2 = new Scanner(cLine);
                   scan2.useDelimiter(";");
                   eTag = scan2.next().trim();
                   memberNo = scan2.next().trim();
                   first = scan2.next().trim();
                   last = scan2.next().trim();
                   gender = scan2.next().trim();
                   yob = scan2.next().trim();
                   tel = scan2.next().trim();
                   addr = scan2.next().trim();
                   club = scan2.next().trim();
                   cmem = new trimember(eTag, memberNo, first, last, gender, yob,
                           tel, addr, club);
                   members.add(cmem);
           catch (FileNotFoundException ex)
               results.append("Sorry can't find the input file\n");
               results.append("Please check file name and location and try again");
               ex.printStackTrace();
          /** Called every time there is a change in the contents of the text field
            * namefld.  It will first clear the text area.  It then needs to search
            * through the container of data to find all records where the surname
            * starts with the characters that have been typed.  The names and
            * addresses need to be set up as strings and placed in
            * an array of Strings.  This can be placed in the "matches" window and
            * displayed for the user, inviting one to be selected.
            * <p>
            * The performance of this is very important.  If necessary, it may be
            * necessary to run as a separate thread so that the user interface is
            * not delayed.  It is essential that the user be able to type letters at a
            * reasonable speed and not have the keystroke processing held up by
            * previous text.
       public void showMatches( )
           run();
                // First clear the text area
          //results.setText("");
                // Determine the leading characters of the surname that is wanted
                input = namefld.getText();
                // Locate the data for this name, and display each matching item
                //  in the JTextArea ...
                // Example of how to set the data in the popup dialog
          matches.list.setListData(found);
          matches.pack();   // resize the popup
                // set the location of the popup if it is not currently visible
          if ( ! matches.isVisible())
             Dimension sz = matches.getSize();
             Point mouse = getMousePosition();
             Point framepos = getLocation();
             int x=0, y=0;
             if (mouse == null)
                Point pt = results.getLocation();
                x = pt.x + 20 + framepos.x;
                y = pt.y + 20 + framepos.y;
             else
                x = mouse.x - 2 + framepos.x;
                y = mouse.y - 2 + framepos.y;
             matches.setLocation(x,y);
          matches.setVisible(true);
          namefld.requestFocus();
          /** Perform any final processing before closing down.
       public void quitProcessing( )
          // Any closing work.  Then
          System.exit(0);
        public void run()
            ArrayList<String> foundit = new ArrayList<String>();
            System.out.println(input);
            if(input != null)
            Iterator it = members.iterator();
            while(it.hasNext())
               trimember test = (trimember) it.next();
               if (test.last.startsWith(input))
                   foundit.add(test.last +", "+ test.first);
            found = new String[foundit.size()];
            for(int i=0; i<foundit.size();i++)
                found[i] = foundit.get(i);
         /** A window for displaying names and addresses from the data set which
          match the leading characters in namefld.
          <p>
          This will automatically pop down if the user moves the mouse out of the
          window.
          <p>
          It needs code added to it to respond to the user clicking on an item in
          the displayed list. */
       class Chooser extends JWindow
                /** To display a set of names and addresses that match the leading
                characters of the namefld text field. */
          public JList list = new JList();
          Chooser( JFrame parent )
             super( parent );
             Container cpane = getContentPane();
             cpane.addMouseListener( new MouseAdapter()
                public void mouseExited(MouseEvent e)
                   Chooser.this.setVisible(false);
             cpane.add("Center",list);
             list.addListSelectionListener( new ListSelectionListener()
                public void valueChanged(ListSelectionEvent e)
                   Chooser.this.setVisible(false);
                   System.out.println("ValueChanged");
                   // First clear the text area
                   results.setText("");
                   String in = (String) list.getSelectedValue();
                   System.out.println("Selected Value was : "+in);
                   String[] inlf = in.split(", ");
                   System.out.println("inlf[0]:"+inlf[0]+" inlf[1]:"+inlf[1]);
                   results.append("Surname \tFirst \teTag \tMemberNo \tSex \tYOB " +
                           "\tTel \tAddress \t\t\tClub\n");
                   Iterator it = members.iterator();
                   while(it.hasNext())
                       trimember test = (trimember) it.next();
                       if (test.last.equals(inlf[0])&&test.first.equals(inlf[1]))
                           results.append(test.toString()+"\n");
                   namefld.requestFocus();
          public class trimember implements Comparable
           String eTag;
           public String memberNo;
           public String first;
           public String last;
           String gender;
           String yob;
           String tel;
           String addr;
           String club;
           public trimember(String eT, String me, String fi, String la,
                   String ge, String yo, String te, String ad, String cl)
               eTag = eT;
               memberNo = me;
               first = fi;
               last = la;
               gender = ge;
               yob = yo;
               tel = te;
               addr = ad;
               club = cl;         
           //To String method to output string of details
           public String toString()
               return last + "\t" + first + "\t" + eTag + "\t" +
                       memberNo + "\t" + gender + "\t" + yob + "\t"+ tel + "\t" +
                       addr + "\t" + club;
           //Compare and sort on Last name
           public int compareTo(Object o)
               trimember com = (trimember) o;
               int lastCmp = last.compareTo(com.last);
               int firstCmp = first.compareTo(com.first);
               int memCmp = memberNo.compareTo(com.memberNo);
               if (lastCmp == 0 && firstCmp !=0)return firstCmp;
               else if (lastCmp==0&&firstCmp==0)return memCmp;
               else return lastCmp;
    }Edited by: Roger on Nov 3, 2007 11:50 AM

    Please don't cross-post. It is considered very rude to do that here:
    http://forum.java.sun.com/thread.jspa?threadID=5233033&messageID=9953169#9953169

  • Iterator in dynamic region located in a popup does not refreshed on cancel

    Hi All,
    i have the following scenario:
    I have jsff made as a taskflow and added into a page on the following way:
    <af:popup id="address" partialTriggers="saveAddressButton cancelAddressButton">
    <af:dialog type="none" title="Create/Edit Address" modal="true" closeIconVisible="false" >
    <f:facet name="buttonBar" >
    <af:group>
    <af:commandButton id="saveAddressButton" actionListener="#{AgentsBean.saveAddress}" partialSubmit="true" text="Save"/>
    <af:commandButton id="cancelAddressButton" immediate="true" actionListener="#{AgentsBean.cancelAddress}" text="Cancel"/>
    </af:group>
    </f:facet>
    <af:region value="#{bindings.dynamicRegion12.regionModel}"
    id="dynamicRegion12"/>
    </af:dialog>
    I use this jsff, opened in a popup to create/edit rows. I create the new row into the main page backing bean method and when calling fragment it's iterator is get synch. with the created row. When i pass the row for edit , it is also synch with a fragment iterator.
    The problem comes if i using the cancel button in a popup , then the iterator doesn't refresh anymore when i open again the popup. It stays on the last row where it was before pressing the cancel. I try to execute setCurrentRowWithKey with passing th key as param to the taskflow but method is also didn't executed.
    I removed my logic from the cancel button and it's also the same.
    I tried with built-in cancel on af:dialog - again the same.
    It looks that submition with immediate =true and closing popup is enough to causing this.
    I have Refresh="ifNeeded" on a taskFlow but this causes only refresh of input taskflow parameters.
    <taskFlow id="dynamicRegion12" taskFlowId="${AgentsBean.addressTaskFlowId}"
    Refresh="ifNeeded"
    Any ideas how to refresh iterator?

    Hi Frank,
    I have followed the same approach. However in my case its a dynamic af:region which is causing the issue.
    Any other pointers is much apprecitaed.
    Thanks,
    Vikranth

  • Dynamically changing the functions in a menu based on the user (in SSHR)

    Dear All,
    I have a requirement to change the functions in a menu dynamically.
    For Ex: An employee is allowed to apply Advance only in the first one month of his/her joining. I created it as an EIT and attached the function, to the menu. Now, i want to remove it automatically from the menu if his/her term in the company crossed one month.
    Can any one tell me how to automatically disable it after one month.
    Thanks and Regards
    Raj
    Edited by: SuperStar_Krishna on Jul 5, 2010 12:22 AM

    The following code should do it. In this example, MyCellRenderer is the renderer class implementing TableCellRenderer, used for displaying combo box.
    TableCellRenderer renderer= new MyCellRenderer();
    (JComboBox)renderer.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            //Your event handling goes here
    });

  • Dynamic objects in component

    I be trying insert dynamic objects in my JSF component by JavaScript,
    but it don't see this objects in the Servlet.
    for e.g., i have a datatable with 3 rows(from Database), each row with a
    input text(HTML), and insert a dynamic input text(HTML) in my structure(4 rows),
    after execute submit to a ActionListener, the input text included in the
    fourth row dont exists in the Collection return by JSF.
    How can i get the fourth object value?

    Simply you can't.
    JavaScript can't affect the structure of the JSF component tree.

  • Open popup in dynamic region once region changes flows

    I need to open a popup in a flow if boolean is set to true in the pageFlowScope bean of the dynamic flow bean used in a dynamic region. The parent page/flow is configured in the adfc-config.xml and is controlled by a session bean.
    So the scenario is the main page has links to several different pages, each of which has a mean of editing a widget. The Widget edit page has a Tree object that lists the items by user defined categories. Double the tree widget opens a popup with the editor section for that particular widget. These widgets rely on each other and if there is a problem in a contained widget, then I provide a clickable link to go to that object. I'm able to get the main page to change regions to the correct widget flow.
    Once I get to the new widget control flow, the tree is displayed as usual and in the pageFlowScope bean I've set a boolean and populated the widget definition for display. Unfortuately, I have found a way to open the popup.
    I've tried a phase listener calling a method in the parent page. However, I'm not able to find the pageFlowScope bean by any means. I've set the pageFlowScope bean into the session and get it in the phaseListener method, but all attempts to show the popup seem to go into the great void. I've even added a button with the actionListener to pageFlowScope.myBean.showPopup, but can trigger the action event for that either.
    Using: JDeveloper 11g. Not using BC. Any help would be greatly appreciated.

    Thank you. That worked.
    I have one more question. How can I change the task flow in the dynamicRegion from another taskFlow. For example: I have taskFlow1 loaded into the dynamic region and I want on a button click from taskFlow1 to load taskFlow2 into the dynamicRegion. Is it possible?

  • How to change the text in JTextField Dynamically

    i am trying to change the contents of JTextField dynamically like this
    textfield.setText();but it is giving error...........how can i do it....

    here is the code .....it is showing error in line 18 and 20 as identifier expected
    their i am trying to make JTextField editable....
    plz have a look
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    import javax.swing.SwingUtilities.*;
    import javax.swing.filechooser.FileFilter;
    //import javax.swing.JEditorPane;
    import java.net.URL;
    public class tm extends JFrame implements ActionListener
    public JTextField[] programtext = new JTextField[30];
    public JTextField[] tapetext = new JTextField[30];
    tapetext.setEditable(true);
    public JTextField[] statetext = new JTextField[30];
    statetext.setEditable(true);
    int count =0;
    public static void main (String arg[]){
    tm m=new tm();
    m.setSize(1000,500);
    m.show();
    JButton loadp, run, step,loadi,loads;
    public tm()
    Container c ;
    c = getContentPane();
    c.setLayout(new FlowLayout());
    loadi = new JButton("LOAD INPUT STRING");
    c.add(loadi);
    loadi.addActionListener(this);
    loadi.setBounds(200,25,100,50);
    loadp = new JButton("LOAD PROGRAM");
    c.add(loadp);
    loadp.addActionListener(this);
    loadp.setBounds(300,25,100,50);
    run = new JButton("RUN");
    c.add(run);
    run.addActionListener (this);
    run.setBounds(400,25,100,50);
    step = new JButton("STEP");
    c.add(step);
    step.addActionListener(this);
    step.setBounds(500,25,100,50);
    loads = new JButton("LOAD STATES");
    c.add(loads);
    loads.addActionListener(this);
    loads.setBounds(600,25,100,50);
    JPanel prog = new JPanel();
    prog.setLayout(new GridLayout(30,1));
    for(int i=0;i<programtext.length;i++)
    programtext= new JTextField(10);
    prog.add(programtext[i]);
    JPanel tape = new JPanel();
    tape.setLayout(new GridLayout(30,1));
    for(int i=0;i<tapetext.length;i++)
    tapetext[i]= new JTextField(10);
    tape.add(tapetext[i]);
    JPanel state = new JPanel();
    state.setLayout(new GridLayout(30,1));
    for(int i=0;i<statetext.length;i++)
    statetext[i]= new JTextField(10);
    state.add(statetext[i]);
    JPanel contentPane3 = new JPanel();
    contentPane3.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
    contentPane3.setLayout(new BorderLayout());
    contentPane3.add(state, BorderLayout.CENTER);
    contentPane3.add(c, BorderLayout.NORTH);
    contentPane3.add(prog, BorderLayout.WEST);
    contentPane3.add(tape, BorderLayout.EAST);
    setContentPane(contentPane3);
    public void actionPerformed(ActionEvent e)
    try{
    if(e.getSource ()==loadp)
    JFileChooser chooser=new JFileChooser();
    int r= chooser.showOpenDialog(this);
    if(r==JFileChooser.APPROVE_OPTION )
    String name=chooser.getSelectedFile().getName();
    File f=chooser.getSelectedFile();
    FileInputStream filestream = new FileInputStream(f);
    BufferedInputStream bufferstream = new BufferedInputStream(filestream);
    DataInputStream datastream = new DataInputStream(bufferstream);
    String record = null;
    programtext[0].setText("");
    try { 
    int i = 0;
    while (true)
    record=datastream.readLine();
    if(record == null){
    break;
    programtext[i].setText(record);
    i++;
    count = count + 1;
    System.out.println ("the no of lines of the program are"+ count);
    catch (Exception p)
    System.out.println(p);
    else if(e.getSource()==loads)
    JFileChooser chooser3=new JFileChooser();
    int r3= chooser3.showOpenDialog(this);
    if(r3==JFileChooser.APPROVE_OPTION)
    String name=chooser3.getSelectedFile ().getName();
    File f3=chooser3.getSelectedFile();
    FileInputStream filestream3 = new FileInputStream(f3);
    BufferedInputStream bufferstream3 = new BufferedInputStream(filestream3);
    DataInputStream datastream3 = new DataInputStream(bufferstream3);
    String record3 = null;
    statetext[0].setText("");
    try { 
    int i = 0;
    while (true)
    record3=datastream3.readLine();
    if(record3 == null){
    break;
    statetext[i].setText(record3);
    i++;
    catch (Exception p3)
    System.out.println(p3);
    else if(e.getSource()==loadi)
    JFileChooser chooser2=new JFileChooser();
    int r2= chooser2.showOpenDialog(this);
    if(r2==JFileChooser.APPROVE_OPTION )
    String name=chooser2.getSelectedFile().getName();
    File f2=chooser2.getSelectedFile();
    FileInputStream filestream2 = new FileInputStream(f2);
    BufferedInputStream bufferstream2 = new BufferedInputStream(filestream2);
    DataInputStream datastream2 = new DataInputStream(bufferstream2);
    String record2 = null;
    tapetext[0].setText("");
    try { 
    int i = 0;
    while (true)
    record2=datastream2.readLine();
    if(record2 == null){
    break;
    tapetext[i].setText(record2);
    i++;
    catch (Exception p2)
    System.out.println(p2);
    else if(e.getSource ()==run)
    String temp="";
    String statetemp=" ";
    String tapetemp=" ";
    int l=0;
    int tp=0;
    String pars[][] = new String[50][5];
         for(int m=0;m<count;m++){
    temp = programtext[m].getText();
    String str[]=temp.split(" ");
    for(int k=0;k<5;k++){
    pars[m][k] =str[k];
    System.out.println(pars[m][k]);
    statetemp = statetext[0].getText();
    tapetemp = tapetext[l].getText();
    while(pars[tp][0]==statetemp && pars[tp][1]==tapetemp && tp><count)
         statetemp = pars[tp][2];
         tapetemp = pars[tp][3];
         statetext[0].setText() = statetemp;
         tapetext[tp].setText() = tapetemp;
         if(pars[tp][4]=="R")
         l=l+1;
         else{
         l=l-1;
         tp++;      
    else if(e.getSource()==step)
    catch(Exception t)
    System.out.println(t);

Maybe you are looking for