JMenuBar Event Handling

I am customizing my own menu bar, I would like to create some event handling, for the top most level, it is not a problem, but when I try to implement some event handling for the drop-down list/menu, nothing happens.
The following is the whole class:
package diagramillustrator;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DIM extends JMenuBar implements MouseListener
     * Creates a new instance of DIM
    public DIM()
        configFileMenu();
        configOptionsMenu();
        configAllItems();
        configMenuBar();
    //Creation and Initialization of objects
    //<editor-fold>    
    //file and options menus to be added to the menubar
    JMenu fileMenu =  new JMenu("File");
    JMenu optionsMenu = new JMenu("Options");
    //file items
    JMenuItem newItem = new JMenuItem("New");
    JMenuItem openItem = new JMenuItem("Open");
    JMenuItem saveItem = new JMenuItem("Save");
    JMenuItem printItem = new JMenuItem("Print");
    JMenuItem exitItem = new JMenuItem("Exit");
    //options items
    JMenuItem createFileItem = new JMenuItem("Create properties file");
    JMenuItem propertiesItem = new JMenuItem("Properties");
    //</editor-fold>
    //adds mouse listener to every item
    private void configAllItems()
        this.addMouseListener(this);
        fileMenu.addMouseListener(this);
        optionsMenu.addMouseListener(this);
        newItem.addMouseListener(this);
        openItem.addMouseListener(this);
        saveItem.addMouseListener(this);
        printItem.addMouseListener(this);
        exitItem.addMouseListener(this);
        createFileItem.addMouseListener(this);
        propertiesItem.addMouseListener(this);
    //creats the file menu
    private void configFileMenu()
        fileMenu.add(newItem);
        fileMenu.addSeparator();
        fileMenu.add(saveItem);
        fileMenu.add(openItem);
        fileMenu.add(printItem);
        fileMenu.addSeparator();
        fileMenu.add(exitItem);
    //creats the options menu
    private void configOptionsMenu()
        optionsMenu.add(createFileItem);
        optionsMenu.add(propertiesItem);
    //configures the menubar, adds all items to it etc
    private void configMenuBar()
        this.setLayout(new FlowLayout(FlowLayout.LEFT));
        this.add(fileMenu);
        this.add(new JSeparator(SwingConstants.VERTICAL));
        this.add(new JSeparator(SwingConstants.VERTICAL));
        this.add(optionsMenu);
        this.setToolTipText("Menu Bar");
    //event handling
    //<editor-fold>
    public void mouseClicked(MouseEvent e)
        //works
        //if(e.getSource().equals(fileMenu))this.setBackground(Color.yellow);
        //else this.setBackground(Color.black);
        //dowsn't work
        if(e.getSource().equals(newItem))this.setBackground(Color.yellow);
    public void mousePressed(MouseEvent e)
    public void mouseReleased(MouseEvent e)
    public void mouseEntered(MouseEvent e)
    public void mouseExited(MouseEvent e)
    //</editor-fold>
    //main method to test class
    public static void main(String[] args)
        JFrame f= new JFrame("Testing menu");
        f.setSize(400,400);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setJMenuBar(new DIM());
        f.show();
} This is the troubling part:
public void mouseClicked(MouseEvent e)
        //works
        //if(e.getSource().equals(fileMenu))this.setBackground(Color.yellow);
        //else this.setBackground(Color.black);
        //dowsn't work
        if(e.getSource().equals(newItem))this.setBackground(Color.yellow);
    } The first two lines work perfectly fine as they apply to the top most level, the rest doesn't do anything at all.
Can anyone help me to handle events for the drop-down please?
AndXer

Sorry posted the prvious by mistake.
Oh, I usually used MouseListener for buttons...I tried using ActionListener and it worked great, the only flaw is that any mouse button clicked triggers an event, I want the event to be triggered only when BUTTON_1 is clicked (like in MouseListener).
Can that be done as I found nothing in the API. If yes, a code sample would be greatly appreciated.
The current code for handling it is:
    if(e.getSource().equals(newItem))
         this.setBackground(Color.green);
}Thanks,
AndXer

Similar Messages

  • How to add event handling for a menu?

    hi,
    I have created a menu and few mneu items.
    for eachmenu itme , i did event handling and it is workign fine.
    it was like this
    menuItem = new JMenuItem("Exit",KeyEvent.VK_X);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK));
    menuItem.addActionListener(this);
    menu.add(menuItem);
         public void actionPerformed(ActionEvent e)
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Action event detected. Event source: " + source.getText();
    System.out.println(s);     
    public void itemStateChanged(ItemEvent e)
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Item event detected. Event source: " + source.getText();
    System.out.println(s);
    now int he second menu i don't have any menu item and i want to do the event handling for the menu itself. any ideas how to do it. following is the code for the menu
    //Build the second menu.
    menu2 = new JMenu("Options");
    menu2.setMnemonic(KeyEvent.VK_O);
    menuBar.add(menu2);
    menu2.addActionListener(this);     //this does nto work

    You were on the right track. However, selecting a menu is different from selecting a menu item. MenuItem chucks an ActionEvent and Menu will send an ItemEvent.
    If you pile all action output to one actionPerformed method then be careful of your assumptions on what the source type will be. If by any chance the Menu has sent an ActinoEvent then your code will have caused a ClassCastException.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MenuTest implements ActionListener, ItemListener {
        JMenuItem menuItem;
        JMenu menu1, menu2;
        JMenuBar menubar;
        JFrame frame;
        public MenuTest() {
            frame = new JFrame("MenuTest");
            frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
            menubar = new JMenuBar();
            frame.setJMenuBar(menubar);
            menu1 = new JMenu("File");
            menu1.setMnemonic(KeyEvent.VK_F);
            menuItem = new JMenuItem("Exit",KeyEvent.VK_X);
            menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK));
            menuItem.addActionListener(this);
            menu1.addItemListener(this);
            menu1.add(menuItem);
            menubar.add(menu1);
            //Build the second menu.
            menu2 = new JMenu("Options");
            menu2.setMnemonic(KeyEvent.VK_O);
            menu2.addActionListener(this); //this does not work
            menu2.addItemListener(this); // use this instead
            menubar.add(menu2);
            JPanel panel = new JPanel();
            panel.setPreferredSize(new Dimension(100,100));
            frame.getContentPane().add(panel);
            frame.pack();
            frame.show();
        public void actionPerformed(ActionEvent e)
            String s = "Action event detected. Event source: " + e.getSource();
            System.out.println(s);
        public void itemStateChanged(ItemEvent e)
            String s = "Item event detected. Event source: " + e.getSource();
            System.out.println(s);
        public static void main(String[] args) {
            new MenuTest();
    }

  • The reflection answer to event handling?

    I have been playing with reflection answers to the question of how to handle ActionEvent events in Swing... like using a single instance of one member class as a reflection switch:
    private class Listener implements ActionListener {
         public void actionPerformed (ActionEvent action) {
              try {this.getClass().getMethod(action.getActionCommand(), new Class[0]).invoke(this, new Object[0]);}
              catch(Exception exception) {/* error handling code */}
         public void one() {/* do something */}
         public void two() {/* do something */}
    }No more hideous if/then structures and only one inner class. Just match the method names to the action commands and the two line switch handles everything. Much cleaner code and directories.
    I wrote a small example program that you can get the source for here:
    http://www.immortalcoil.org/drake/SmartFrameExample.java
    I can think of only two reasons not to do this right now:
    1) Event / listener mismatches you would have caught at compile time before (if using inner classes) become runtime errors, or if you improve upon the above with Class.getMethods() then dead actions (as with a classic switch).
    2) Inability to look yourself in the mirror or partake of Jesus's love.
    Still, the result is much prettier code and as long as you code it right it will work flawlessly. I am honestly considering using this.
    Thoughts?

    For simple GUIs with very few actions, your approach is obviously overkill. You want to preserve simplicity whenever possible without affecting performance.
    For mildly complex GUIs, I think your approach is good, but still doesn't solve the bigger problem of managing multiple components that use the same action. If you've got so many actions that you need reflection to reduce code, you probably have a GUI with menubars, toolbars, popup menus, and buttons that all perform the same set of actions. Now you have to register an ActionListener with each component, not to mention disabling an action, which involves finding every menu item and button corresponding to this action and disabling/enabling it. I realize this is a different problem than you were trying to solve, but it's worth considering.
    Well, Swing provides javax.swing.Action to handle just this problem, which more or less alleviates the need for your approach because you have an Action subclass for each action. But maybe the best solution for very complex GUIs is a combination of your approach with the Action approach by providing an ActionSet class, which centralizes event handling for all components. The ActionSet class would define for each action:
    1) a static String for the action command
    2) a static String for the tooltip
    3) a static Icon for the icon
    Now, when a new ActionSet is created, it uses reflection to read each of it's fields, creating a new Action subclass for that action and storing it in a HashMap using the action command for the key. The Action subclass just handles the event by forwarding it to a registered ActionListener on the ActionSet class. The ActionListener would implement your approach for reflection event-handling, thereby eliminating if/else/switch clauses.
    The GUI code can call a method "getAction(String actionCommand)" on the ActionSet to retrieve the Action subclass when creating the JMenuBar, JButton, JToolBar, JPopupMenu, etc. Then at any time in the application, you can call ActionSet.getAction(...).setEnabled(...) to enable/disable all components using that action.

  • How can I execute an external program from within a button's event handler?

    I am using Tomcat ApacheTomcat 6.0.16 with Netbeans 6.1 (with the latest JDK/J2EE)
    I need to execute external programs from an event handler for a button on a JSF page (the program is compiled, and extremely fast compared both to plain java and especially stored procedures written in SQL).
    I tried what I'd do in a standalone program (as shown in the appended code), but it didn't work. Instead I received text saying the program couldn't be found. This error message comes even if I try the Windows command "dir". I thought with 'dir' I'd at least get the contents of the current working directory. :-(
    I can probably get by with cgi on Apache's httpd server (or, I understand tomcat supports cgi, but I have yet to get that to work either), but whatever I do I need to be able to do it from within the button's event handler. And if I resort to cgi, I must be able to maintain session jumping from one server to the other and back.
    So, then, how can I do this?
    Thanks
    Ted
    NB: The programs that I need to run do NOT take input from the user. Rather, my code in the web application processes user selections from selection controls, and a couple field controls, sanitizes the inoputs and places clean, safe data in a MySQL database, and then the external program I need to run gets safe data from the database, does some heavy duty number crunching, and puts the output data into the database. They are well insulated from mischeif.
    NB: In the following array_function_test.pl was placed in the same folder as the web application's jsp pages, (and I'd tried WEB-INF - with the same result), and I DID see the file in the application's war file.
            try {
                java.lang.ProcessBuilder pn = new java.lang.ProcessBuilder("array_function_test.pl");
                //pn.directory(new java.io.File("K:\\work"));
                java.lang.Process pr = pn.start();
                java.io.BufferedInputStream bis = (java.io.BufferedInputStream)pr.getInputStream();
                String tmp = new String("");
                byte b[] = new byte[1000];
                int i = 0;
                while (i != -1) {
                    bis.read(b);
                    tmp += new String(b);
                getSelectionsDisplayTextArea().setText(getSelectionsDisplayTextArea().getText() + "\n\n" + tmp);
            } catch (java.io.IOException ex) {
                getSelectionsDisplayTextArea().setText(getSelectionsDisplayTextArea().getText() + "\n\n" + ex.getMessage());
            }

    Hi Fonsi!
    One way to execute an external program is to use the System Exec.vi. You find it in the functions pallet under Communication.
    /Thomas

  • Copying text to the clipboard in AVDocDidOpen event handler causes Acrobat 9 to crash

    I'm trying to copy the filename of a document to the clipboard in a plugin with my AVDocDidOpen event handler.  It works for the first file opened; however when a second file is opened, Acrobat crashes.  The description in the application event log is: "Faulting application acrobat.exe, version 9.1.0.163, faulting module gdi32.dll, version 5.1.2600.5698, fault address 0x000074cc."
    I've confirmed that the specific WIN32 function that causes this to happen is SetClipboardData(CF_TEXT, hText);  When that line is commented out and remaining code is left unchanged, Adobe doesn't crash.
    Is there an SDK function that I should be using instead of WIN32's SetClipboardData()?  Alternately, are there other SDK functions that I need to call be before or after I call SetClipboardData()
    Bill Erickson

    Leonard,
    I tried it with both "DURING, HANDLER, END_HANDLER" and "try catch," as shown below.  However, it doesn't crash in the event handler; it crashes later, so the HANDLER/catch block is never hit.
    The string that's passed to SetClipboardData() is good, because I'm able to paste it into the filename text box of the print dialog when I try to create the "connector line" PDF.  I also got rid of all the string manipulation and tried to pass a zero-length string to the clipboard but it still crashes.
    Here's the code:
    ACCB1 void ACCB2 CFkDisposition::myAVDocDidOpenCallback(AVDoc doc, Int32 error, void *clientData)
        PDDoc pdDoc = AVDocGetPDDoc(doc);
        char* pURL = ASFileGetURL(PDDocGetFile(annotDataRec->thePDDoc));
        if (pURL)    {
            if (strstr(pURL, "file://") && strstr(pURL, "Reviewed.pdf")) {
                // Opened from file system so copy filename to clipboard for connector line report
                char myURL[1000];
                strcpy(myURL, pURL);
                ASfree(pURL);    // Do this before we allocate a Windows handle just in case Windows messes with this pointer
                pURL = NULL;
                HGLOBAL hText = GlobalAlloc(GMEM_MOVEABLE, 1000);
                if (hText)    {
                    try
                        // Skip path info and go right to filename
                        char *pText = (char *)GlobalLock(hText);
                        char *pWork = strrchr(myURL,'/');
                        if (pWork)    {
                            strcpy(pText, pWork+1);
                        } else {
                            strcpy(pText, myURL);
                        char *pEnd = pText + strlen(pText);    // Get null terminator address
                        // Replace "%20" in filename with " "
                        pWork = strstr(pText, "%20");
                        while (pWork)    {
                            *pWork = ' ';
                            memmove(pWork+1, pWork+3, (pEnd - (pWork+2)));
                            pWork = strstr(pText, "%20");
                        // Append a new file extension
                        pWork = strstr(pText, ".pdf");
                        *pWork = 0;    // truncate the string before ".pdf"
                        strcat(pWork,".Connectors.pdf");
                        GlobalUnlock(hText);     // Must do this BEFORE SetClipboardData()
                        // Write it to the clipboard
                        OpenClipboard(NULL);
                        EmptyClipboard();
                        SetClipboardData(CF_TEXT, hText);     // Here's the culprit
                        CloseClipboard();
                        GlobalFree(hText);
                    } catch (char * str) {
                        AVAlertNote(str);
            if (pURL)
                ASfree(pURL);

  • Unable to get automatic event handling for OK button.

    Hello,
    I have created a form using creatobject. This form contains an edit control and Search, Cancel buttons. I have set the Search buttons UID to "1" so it can handle the Enter key hit event. Instead its caption changes to Update when i start typing in the edit control and it does not respond to the Enter key hit. Cancel happens when Esc is hit.
    My code looks like this -
    Dim oCreationParams As SAPbouiCOM.FormCreationParams
            oCreationParams = SBO_Application.CreateObject(SAPbouiCOM.BoCreatableObjectType.cot_FormCreationParams)
            oCreationParams.UniqueID = "MySearchForm"
            oCreationParams.BorderStyle = SAPbouiCOM.BoFormBorderStyle.fbs_Sizable
                    Dim oForm As SAPbouiCOM.Form = SBO_Application.Forms.AddEx(oCreationParams)
    oForm.Visible = True
    '// set the form properties
            oForm.Title = "Search Form"
            oForm.Left = 300
            oForm.ClientWidth = 500
            oForm.Top = 100
            oForm.ClientHeight = 240
            '// Adding Items to the form
            '// and setting their properties
            '// Adding an Ok button
            '// We get automatic event handling for
            '// the Ok and Cancel Buttons by setting
            '// their UIDs to 1 and 2 respectively
            oItem = oForm.Items.Add("1", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
            oItem.Left = 5
            oItem.Width = 65
            oItem.Top = oForm.ClientHeight - 30
            oItem.Height = 19
            oButton = oItem.Specific
            oButton.Caption = "Search"
            '// Adding a Cancel button
            oItem = oForm.Items.Add("2", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
            oItem.Left = 75
            oItem.Width = 65
            oItem.Top = oForm.ClientHeight - 30
            oItem.Height = 19
            oButton = oItem.Specific
            oButton.Caption = "Cancel"
    oItem = oForm.Items.Add("NUM", SAPbouiCOM.BoFormItemTypes.it_EDIT)
            oItem.Left = 105
            oItem.Width = 140
            oItem.Top = 20
            oItem.Height = 16
            Dim oEditText As SAPbouiCOM.EditText = oItem.Specific
    What changes do i have to make to get the enter key to work?
    Thanks for your help.
    Regards,
    Sheetal

    Hello Felipe,
    Thanks for pointing me to the correct direction.
    So on refering to the documentation i tried out a few things. But I am still missing something here.
    I made the following changes to my code -
    oForm.AutoManaged = True
    oForm.SupportedModes = 1 ' afm_Ok
    oItem = oForm.Items.Add("1", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
            oItem.Left = 5
            oItem.Width = 65
            oItem.Top = oForm.ClientHeight - 30
            oItem.Height = 19
    oItem.SetAutoManagedAttribute(SAPbouiCOM.BoAutoManagedAttr.ama_Visible, 1, SAPbouiCOM.BoModeVisualBehavior.mvb_Default)
            oButton = oItem.Specific
            oButton.Caption = "OK"
    AND
    oForm.Mode = SAPbouiCOM.BoFormMode.fm_OK_MODE
    oItem = oForm.Items.Add("1", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
            oItem.Left = 5
            oItem.Width = 65
            oItem.Top = oForm.ClientHeight - 30
            oItem.Height = 19
    oItem.AffectsFormMode = False
    I get the same behaviour OK button changes to update and enter key does not work.
    Could you please tell me find what is it that i am doing wrong?
    Regards,
    Sheetal

  • Dropdown box - which event handler to use ?

    I am having trouble with setting the readonly property (via Javascript) of the adjacent textbox to my dropdown box when the index value is a certain number.
    I tried using MouseUp, MouseDown, and even OnBlur....but the readonly does not seem to be getting set to true or false consistently.
    Could this be a timing issue ? The textbox that I am trying to control is the next tab-order control in the list of controls for this page.
    This same logic is working fine in the MouseUp event handler for check boxes. So I am just wondering if this is a bug or must my implementation change to accomodate dropdown boxes ? For instance, should I move the logic to the Enter event handler of the textbox instead ? Can a control's own eventhandler set itself to readonly when it is the active form field ?

    After tons and tons of testing time, I've come to the conclusion that dropdowns are totally buggy in 11.0.07 release of Acrobat Pro.
    Even if you set the "commit values immediately", you get the PRIOR selected item's value as the event value, not the CURRENT one.
    This occurs in a Validate event handler script. I have not been able to use any other event handlers for a dropdown except the OnBlur....and then, for my purposes, IT'S TOO LATE !!!
    This is totally worthless as I need to setFocus() and set fields to readonly based on the immediate dropdown offset or face value.

  • Input value given on web page is not getting pickedup in event handler

    Hi friends,
    I have created one simple page in SE80 with program with flow logic option, in which I would like to show business partner details from BUT000 table with the input of partner number. But the thing is the input value(partner no.)which I am giving on web page is not getting picked up in selection in event handler though I am giving input value it is becoming initial while selecting. What could be the reason?
    Below I am mentioning the code which I have written in even handler for OnInputProcessing event.
    CASE EVENT_ID.
    WHEN 'select'.
    NAVIGATION->SET_PARAMETER( 'partner' ).
    SELECT * FROM but000 INTO TABLE I_but000 WHERE partner BETWEEN partner AND partner1.
    WHEN OTHERS.
    ENDCASE.
    Thanks in advance,
    Steve

    Hi Abhinav,
    I tried with the one you posted. But it is giving run time error as shown below.
    Note
    The following error text was processed in the system CRD : Access via 'NULL' object reference not possible.
    The error occurred on the application server crmdev_CRD_00 and in the work process 0 .
    The termination type was: RABAX_STATE
    The ABAP call stack was:
    Method: ONINPUTPROCESSING of program CLO24DDFJW575HVAQVJ89KWHEHC9OCP
    Method: %_ONINPUTPROCESSING of program CL_O24DDFJW575HVAQVJ89KWHEHC9OCP
    Method: DO_REQUEST of program CL_BSP_PAGE===================CP
    Method: ON_REQUEST of program CL_BSP_RUNTIME================CP
    Method: IF_HTTP_EXTENSION~HANDLE_REQUEST of program CL_HTTP_EXT_BSP===============CP
    Method: EXECUTE_REQUEST_FROM_MEMORY of program CL_HTTP_SERVER================CP
    Function: HTTP_DISPATCH_REQUEST of program SAPLHTTP_RUNTIME
    Module: %_HTTP_START of program SAPMHTTP
    Regards,
    Steve

  • How do I create an Event Handler for an Execute SQL Task in SSIS if its result set is empty

    So the precedence on my entire package executing is based on my first SELECT of my Table and an updatable column. If that SELECT results in an empty result set, how do I create an Event Handler to handle an empty result set?
    A Newbie to SSIS.
    I appreciate your review and am hopeful for a reply.
    PSULionRP

    Depends upon what you want to do in the eventhandler. this is what you can do
    Store the result set from the Select to a user variable.
    Pass this user variable to a Script task.
    In the Script task do whatever you want to do including failing the package this can be done by failing the script task, which in turns fails the package. something like
    Dts.TaskResult = Dts.Results.Failure
    Abhinav http://bishtabhinav.wordpress.com/

  • Swing: when trying to get the values from a JTable inside an event handler

    Hi,
    I am trying to write a graphical interface to compute the Gauss Elimination procedure for solving linear systems. The class for computing the output of a linear system already works fine on console mode, but I am fighting a little bit to make it work with Swing.
    I put two buttons (plus labels) and a JTextField . The buttons have the following role:
    One of them gets the value from the JTextField and it will be used to the system dimension. The other should compute the solution. I also added a JTable so that the user can type the values in the screen.
    So whenever the user hits the button Dimensiona the program should retrieve the values from the table cells and pass them to a 2D Array. However, the program throws a NullPointerException when I try to
    do it. I have put the code for copying this Matrix inside a method and I call it from the inner class event handler.
    I would thank you very much for the help.
    Daniel V. Gomes
    here goes the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import AdvanceMath.*;
    public class MathF2 extends JFrame {
    private JTextField ArrayOfFields[];
    private JTextField DimOfSis;
    private JButton Calcular;
    private JButton Ativar;
    private JLabel label1;
    private JLabel label2;
    private Container container;
    private int value;
    private JTable DataTable;
    private double[][] A;
    private double[] B;
    private boolean dimensionado = false;
    private boolean podecalc = false;
    public MathF2 (){
    super("Math Calcs");
    Container container = getContentPane();
    container.setLayout( new FlowLayout(FlowLayout.CENTER) );
    Calcular = new JButton("Resolver");
    Calcular.setEnabled(false);
    Ativar = new JButton("Dimensionar");
    label1 = new JLabel("Clique no bot�o para resolver o sistema.");
    label2 = new JLabel("Qual a ordem do sistema?");
    DimOfSis = new JTextField(4);
    DimOfSis.setText("0");
    JTable DataTable = new JTable(10,10);
    container.add(label2);
    container.add(DimOfSis);
    container.add(Ativar);
    container.add(label1);
    container.add(Calcular);
    container.add(DataTable);
    for ( int i = 0; i < 10 ; i ++ ){
    for ( int j = 0 ; j < 10 ; j++) {
    DataTable.setValueAt("0",i,j);
    myHandler handler = new myHandler();
    Calcular.addActionListener(handler);
    Ativar.addActionListener(handler);
    setSize( 500 , 500 );
    setVisible( true );
    public static void main ( String args[] ){
    MathF2 application = new MathF2();
    application.addWindowListener(
    new WindowAdapter(){
    public void windowClosing (WindowEvent event)
    System.exit( 0 );
    private class myHandler implements ActionListener {
    public void actionPerformed ( ActionEvent event ){
    if ( event.getSource()== Calcular ) {
    if ( event.getSource()== Ativar ) {
    //dimensiona a Matriz A
    if (dimensionado == false) {
    if (DimOfSis.getText()=="0") {
    value = 2;
    } else {
    value = Integer.parseInt(DimOfSis.getText());
    dimensionado = true;
    Ativar.setEnabled(false);
    System.out.println(value);
    } else {
    Ativar.setEnabled(false);
    Calcular.setEnabled(true);
    podecalc = true;
    try {
    InitValores( DataTable, value );
    } catch (Exception e) {
    System.out.println("Erro ao criar matriz" + e );
    private class myHandler2 implements ItemListener {
    public void itemStateChanged( ItemEvent event ){
    private void InitValores( JTable table, int n ) {
    A = new double[n][n];
    B = new double[n];
    javax.swing.table.TableModel model = table.getModel();
    for ( int i = 0 ; i < n ; i++ ){
    for (int j = 0 ; j < n ; j++ ){
    Object temp1 = model.getValueAt(i,j);
    String temp2 = String.valueOf(temp1);
    A[i][j] = Double.parseDouble(temp2);

    What I did is set up a :
    // This code will setup a listener for the table to handle a selection
    players.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = players.getSelectionModel();
    rowSM.addListSelectionListener(new Delete_Player_row_Selection(this));
    //Class will take the event and call a method inside the Delete_Player object.
    class Delete_Player_row_Selection
    implements javax.swing.event.ListSelectionListener
    Delete_Player adaptee;
    Delete_Player_row_Selection (Delete_Player temp)
    adaptee = temp;
    public void valueChanged (ListSelectionEvent listSelectionEvent)
    adaptee.row_Selection(listSelectionEvent);
    in the row_Selection function
    if(ex.getValueIsAdjusting()) //To remove double selection
    return;
    ListSelectionModel lsm = (ListSelectionModel) ex.getSource();
    if(lsm.isSelectionEmpty())
    System.out.println("EMtpy");
    else
    int selected_row = lsm.getMinSelectionIndex();
    ResultSetTableModel model = (ResultSetTableModel) players.getModel();
    String name = (String) model.getValueAt(selected_row, 1);
    Integer id = (Integer) model.getValueAt(selected_row, 3);
    This is how I got info out of a table when the user selected it

  • Problem with event handling

    Hello all,
    I have a problem with event handling. I have two buttons in my GUI application with the same name.They are instance variables of two different objects of the same class and are put together in the one GUI.And their actionlisteners are registered with the same GUI. How can I differentiate between these two buttons?
    To be more eloborate here is a basic definition of my classes
    class SystemPanel{
             SystemPanel(FTP ftp){ app = ftp};
             FTP app;
             private JButton b = new JButton("ChgDir");
            b.addActionListener(app);
    class FTP extends JFrame implements ActionListener{
               SystemPanel rem = new SystemPanel(this);
               SystemPanel loc = new SystemPanel(this);
               FTP(){
                       add(rem);
                       add(loc);
                       pack();
                       show();
           void actionPerformed(ActionEvent evt){
            /*HOW WILL I BE ABLE TO KNOW WHICH BUTTON WAS PRESSED AS THEY
               BOTH HAVE SAME ID AND getSouce() ?
               In this case..it if was from rem or loc ?
    }  It would be really helpful if anyone could help me in this regard..
    Thanks
    Hari Vigensh

    Hi levi,
    Thankx..
    I solved the problem ..using same concept but in a different way..
    One thing i wanted to make clear is that the two buttons are in the SAME CLASS and i am forming 2 different objects of the SAME class and then putting them in a GUI.THERE IS NO b and C. there is just two instances of b which belong to the SAME CLASS..
    So the code
    private JButton b = new JButton("ChgDir");
    b.setActionCommand ("1");
    wont work as both the instances would have the label "ChgDir" and have setActionCommand set to 1!!!!
    Actually I have an array of buttons..So I solved the prob by writting a function caled setActionCmdRemote that would just set the action commands of one object of the class differently ..here is the code
    public void setActionCommandsRemote()
         for(int i = 0 ; i <cmdButtons.length ; i++)
         cmdButtons.setActionCommand((cmdButtons[i].getText())+"Rem");
    This just adds "rem" to the existing Actioncommand and i check it as folows in my actionperformed method
         if(button.getActionCommand().equals("DeleteRem") )          
                        deleteFileRemote();
          else if(button.getActionCommand().equals("Delete") )
                     deleteFileLocal();Anyway thanx a milion for your help..this was my first posting and I was glad to get a prompt reply!!!

  • Enhance standard class with event handler method

    In trying to enhance a standard class with a new event handler class, I find that the ECC 6.0 EHP4 system does not appear to recognise the fact the method is an event handler method.  The specific example is a new method to handle the event CL_GUI_ALV_GRID->USER_COMMAND. 
    I notice that the flag called Active has not been ticked - see image below.  Perhaps this is the reason why the event handler is not being triggered.
    Note that there is an event handler for the same event in the standard class which obviously is executed as expected.  Any ideas on limitations in the system or I am missing a step?
    Thanks
    John

    Thank you for your replies.
    There is a bug in the ALV handler of a standard SAP class (when executed in ITS WebGUI) and I was hoping to create a custom event handler as an Enhancement to execute some custom code to sort of "handle the bug". 
    I agree - ideally it should be done in a Z class but that will not give me access to the object methods and attributes of the enhanced class.
    Cheers,
    John

  • Javascript embedded in button pl/sql event handler not being executed

    Javascript calls not working from pl/sql button event handler. What am I missing? Are specific settings needed to execute javascript from pl/sql proceedures?
    Example: Want to toggle target='_blank' off and on in a button pl/sql event handler to open url call in new window & then reset when processing submit is done & the app returns to the form.
    portal form button's pl/sql submit handler:
    begin
    htp.p('<script language=JavaScript>') ;
    htp.p('this.form.target="_blank"') ;
    htp.p('</script>') ;
    PORTAL.wwa_app_module.set_target('http://www.oracle.com') ;
    htp.p('<script language=JavaScript>') ;
    htp.p('this.form.target="_blank"') ;
    htp.p('</script>') ;
    end ;
    Putting the following in the button's javascript on_click event handler works great:
    this.form.target='_blank'
    to force opening new window with a call in the button's submit pl/sql code via:
    PORTAL.wwa_app_module.set_target('http://www.oracle.com') ;
    but then the target='_blank' is left on when the submit is done & we return to the form.
    putting the above javascript as a function (called fcn_newpage) elsewhere (e.g., after form opens) & calling in the submit pl/sql with
    htp.p('fcn_newpage') ;
    also doesn't work.
    Metalink thought this was an application issue instead of a bug, so thought I'd see if anyone knows what's going wrong here. (Portal 9.0.4.1)

    thanks for your discussion of my post.
    Please clarify:
    "htp.p('fcn_newwindow') sends a string":
    What would you suggest the proper syntax for a function fcn_newwindow() call from a pl/sql javascript block that differs from
    htp.p('<script language="Javascript">') ;
    htp.p('fcn_newwindow');
    htp.p('</script>');
    or more simply
    htp.p('fcn_newwindow') ;
    More generally, what I'm trying to figure out is under what conditions javascript is executed, if ever, in the pl/sql of a button (either the submit or custom event handler, depending on the button).
    I've seen lots of posts asking how to do a simple htp.p('alert("THIS IS TROUBLE")') ; in a pl/sql event handler for a button on a form, but no description of how this can be done successfully.
    In addition to alerts, in my case, I'd like to call a javascript fcn from a pl/sql event handle that would pass a URL (e.g., http://www.oracle.com) where the javascript fcn executed
    window.open(URL). The API call to set_target(URL) in pl/sql has no ability to open in a new window, so calling that is inadequate to my needs and I must resort to javascript.
    Its clear in the PL/SQL of a button, you can effect form components since p_session..set_target & p_session.get_target set or get the contents of form components.
    So to see if javascript ever works, I tried to focus on something simple that only had to set what amounts to an enviromental variable when we returned to the form after a post. I chose to try to change the html value of TARGET from javascript in the PL/SQL button because it doesn't need to be implemented until we finish the post and return to the form.
    So I focused on a hack, setting this.form.TARGET='_blank' in the on_click event handler that forced every subsequent URL call or refresh of the form to be a new window. I then wanted to turn off opening new windows once I'd opened the URL call in a new window by setting TARGET='' in the portal form. I can achieve what I want by coding this.form.TARGET='' in the javascript (on_focus, on_change, or on_mousedown, ...) of every form component that might refresh the form. However, that is a ridiculous hack when a simple htp.p('<script>') ; htp.p('this.form.target=""') ; htp.p('</script>') ; at the end of the button's pl/sql event handle should do the same thing reliably if javascript ever works in the pl/sql event handler.
    If we didn't have access to form components through p_session calls, I'd assume it was a scope issue (what is available from the pl/sql event handler). But unless my syntax is just off, when, if ever, can javascript be used in a portal form's pl/sql event handler for a button?
    if I code a javascript funtion in the forms' pl/sql before displaying form:
    htp.p('<script language="JavaScript">') ;
    htp.p('function fcn_new_window(URL)') ;
    htp.p('window.open(URL)' ) ;
    htp.p('</script>') ;
    the function can be called from a button's on_click javascript event handler:
    fcn_new_window('http://www.oracle.com')
    but from the same button's pl/sql submit event handler this call doesn't work: htp.p('fcn_new_window("http://www.oracle.com")')
    So my questions remain: Is there other syntax I need, or does javascript ever work properly from the pl/sql of a form button's event handler? If it doesn't work, isn't this a bug that should be fixed by Oracle?
    I can probably figure out hacks to make things work the way I need, but executing javascript from pl/sql event handlers seems to be the expected way to affect portal html pages (forms, reports, ...) and it seems not to work as expected. I don't feel I should have to implement hacks for something as simple as calling a javascript function from pl/sql when almost every example I've found in metalink or the forums or Oracle Press's "portal bible" suggests using javascript from pl/sql via the utility htp.p() to effect web page components in portal.
    My TAR on the subject, while still open, returned the result basically: "We can reproduce your situation. Everything looks okay to us, but we can't explain how to use javascript where you want or point you to any documentation that would solve your problem or expain why it should not work the way you want it to. We don't feel its a technical issue. Why don't you post the problem on the portal applications forum."
    I'm hoping I'm just missing something fundamental and everything will work if I implement it a little differently. So if anyone sees my error, please let me know.
    by the way, not sure this is germain, but in reference to your comment:
    "redirections in pl/sql procedures give a peculiar result. in a pl/sql procedure, usually, portals give the last redirection statement and ignore anything else coming after it."
    if I try to raise an alert:
    htp.p('alert("you screwed up")');
    return;
    in a pl/sql event handler, it still doesn't raise the alert, even though its the last thing implemented in the event handler. But if I set the value of a text box using p_session..set_value_as_string() at the same spot, it correctly sets the text box value when I return to the form.

  • How to create Event Handler in OIM11g

    Hi all,
    How can I create an event handler in OIM11g
    Thank You in advance.

    there are three component required to generate this
    1. plugin.xml
    2. EventHandler class
    3. eventhandler.xml to import into MDS schema which define OPERATION,ORDER..etc
    you have to zip the first two and register using register utility in <IDM_HOME>server/bin and then import 3rd one into MDS using WeblogicImportMetaData.sh
    for details follow below link
    http://docs.oracle.com/cd/E14571_01/doc.1111/e14309/oper.htm
    Step by step explanation from development to deployement
    http://idmoim.blogspot.in/2011/07/developing-and-deploying-oim-11g-custom_29.html
    --nayan
    Edited by: Nishith Nayan on Feb 8, 2012 8:54 AM

  • How to create event handler in project online

     how to create a remote event handler for project online...
    i want to create a event handler onprojectcreating using CSOM...need Help..

    Hi Abidulla,
    Here is a good post from UMT for you to start.
    http://www.umtsoftware.com/blog/2013/08/01/project-server-2013-remote-event-handlers/
    Hope this helps,
    Guillaume Rouyre, MBA, MCP, MCTS |

Maybe you are looking for