How to use Action listener from Static method

Hello,
I am begginer in Java. I am trying to add JButton and add ActionListener to it in the Java tutorial example (TopLevelDemo).
The problem i am facing are:
1. Since "private static void createAndShowGUI" method is static I cannot reference (this) in the method addActionLisetener when trying to add the JButton
JButton pr = new JButton("Print Report");
     pr.addActionListener(this);
2. If I make "private static void createAndShowGUI" a non static method then it does not run from main method giving me the error(cannot reference non-static).
3. Where do I put actionPerformed method?
I did not post the errors for all situations. Just asking how I can Add JButton and add ActionListener to it in the following code
Thanks
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* TopLevelDemo.java requires no other files. */
public class TopLevelDemo {
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("TopLevelDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a cyan background.
JMenuBar cyanMenuBar = new JMenuBar();
cyanMenuBar.setOpaque(true);
cyanMenuBar.setBackground(Color.cyan);
cyanMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.
JLabel yellowLabel = new JLabel();
yellowLabel.setOpaque(true);
yellowLabel.setBackground(Color.yellow);
yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.
frame.setJMenuBar(cyanMenuBar);
frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}

Here is one way of doing it...
JButton btn = new JButton("Click on Me");
btn.addActionListener(new ActionListener(){
                          public void actionPerformed(ActionEvent ae){
                            // do something
                            }});here we create an anonymous inner class ActionListener and add it to our button...
- MaxxDmg...
- ' I am not me... '

Similar Messages

  • How to Call action Listener from Mouse Listener event

    One class (class 1)implements mouse listener and responds to a mouse events.
    As part of that response it needs to call a variable set method in another class (class 2)and also have that setMethod call it's own ActionPerformed.
    Seems the problem is I don't have aaction event to pass
    I only have a mouse event. As follows:
    class 1
    public void mousePressed(MouseEvent e) {
    int y1=Math.abs(e.getY()-y);
    this.sourceReference.setVar(y1);
    repaint();
    class 2
    int var;
    public void setVar(int y)
    var=y;
    this.ActionPerformed(?? ); //This is what I want to do
    Same question slightly different.
    From class 1 I scould first call the setVar method
    and then issue a call to class 2's ActionPerformed.
    But again I don't seem to have the proper action event e to pass it.
    Thanks

    Do you need any information from an ActionEvent that you'd be calling from the MouseEvent (ie the action command, or somethig) or can you just have the actionPerformed method just call a different method that doesn't need an ActionEvent?
    public void actionPerformed(ActionEvent e) {
    this.doActionStuff();
    public void doActionStuff() {
    // does what you want the action event to do
    Then from the mousePressed method you can just call the doActionStuff method.
    I'm not sure if this helps or not, hope it does.
    Scott

  • How to use budget amount from previous years

    Dear Values Consultant
    How to use budget amount from previous years
    I create budget for 2007 and I use it .in 2008 I create new budget with new amount for account, but still there are amount from 2007-I want to use or transfer it to 2008,
    How to do this? Please give me details step to implement to this feature
    Thanks for caring

    Hi,
    There are two ways to do it:
    1. Define the account range in your Budget Organization and in the Budgetary Control region, out the Amount Type as "PJTD" and Boundary as "Project". This method is useful when you have project as a segment in your chart of accounts and the Budgets are defined for the full project.
    2. The Other way is to carry forward your funds available from last year. Go to Journals -> Generate -> Carry Forward and carry forward the balance for a certain range of account from one financial year to the next one.
    Gajendra

  • Accesing database from static method on java collaboration

    Hi *,
    I want cache data from a oracle database in a java collaboratioon when java collaboration is enabled by emanager.
    My java collaboration has a oracleOTD
    I did an static method on java collaboration, but I can't access database from static method.
    Thanks
    Hector

    hi hector,
    this wont work!
    regards chris

  • How to use an object's paint method

    I have created a class imagePanel which extends a jPanel to display an image. When I create a new imagePanel object I pass it an image argument which is used to paint my image on the jPanel, so far so good. I don't wish to have to continuously create new ImamePanels to display new images so I thought I could make a set_Image method that would set a new image in an exising imagePanel object. This is where I run into problems how to use the existing object paint method to replace the image. I tried this without success:
    public Image setMyImage (Image myImage)
    imageX = myImage; // imageX is the image that is painted by the imagePanel object's paint method
    paint(g);
    Something must be wrong on how I access the paint method. Thanks for any help.
    Jack

    Yahoooo, got it. This was the code I needed and thanks for your help:
    public void setImage (Image myImage)
    imageX = myImage;
    repaint(300);
    }

  • Problem with calling dispose() from static method

    I have one class, where I have this:
    EditorWindow.disposeWindow();and class EditorWindow, where I have static method
    protected static void disposeWindow() {
        dispose();
    }But, dispose() cant be called from static method. Is there any way to hide or close the EditorWindow window?

    kaneeec wrote:
    I dont have references of these windows, because it would be too difficult. They are created just by new Window().setVisible(true);It's not difficult:
    Window w = new Window();
    w.setVisible(true);Now you have a reference (w) to your window that you can later call dispose() on.
    w.dispose();dispose() isn't a static method, so you have no choice but to call it on a specific instance.

  • HT1491 how to use a ringtone from a downloaded app in iphone5

    how to use a ringtone from a downloaded app in iphone 5

    RINGTONE
    This how to make ring tones for your iPhone:
    Choose the desired song from you library
    Do a secondary click on your song if you are using a MAC (right click for PC)
    Click "Get Info"
    Go to Options tab
    Set Start Time and Stop Time, some iOS only allow for a 30 sec duration for ringtones, then click OK
    Do secondary click (right click for PC) to your selected song
    Click "Create AAC Version", new song from your selected will added to your library (short one)
    Do secondary click (right click for PC) to your short one (new song)
    Click "Show in Finder"
    Rename file *.m4a to *.m4r, click "use *.m4r"
    Drag the file to library, for the first time it would automatically add your library with new folder "Tones" under Apps folder
    Open the ring tones in the Tones folder of your library than drag it to your iPhone and your ringtone also would be automatically added "Tones" folder.
    Last but not least, set the ring tone in your iPhone under the "Setting-Sound"
    For information on how to make ringtones read http://www.ehow.com/how_2160460_custom-iphone-ringtones-free.html
    Or
    http://www.demogeek.com/2009/07/31/how-to-add-custom-ringtones-to-your-iphone/

  • How to use iphone 4s from japan locked by softbank ?

    how to use iphone 4s from japan locked by softbank?

    Ocean20 answered your question, don't waste your time contacting Softbank as Chris CA suggested. There are no officially unlocked iPhones sold in Japan & none of the Japanese carriers...which include Softbank...offer official unlocking for the iPhone. There is no way to get any Japanese iPhone officially unlocked.

  • How to get the class name  static method which exists in the parent class

    Hi,
    How to know the name of the class or reference to instance of the class with in the main/static method
    in the below example
    class AbstA
    public static void main(String[] args)
    System.out.println(getXXClass().getName());
    public class A extends AbstA
    public class B extends AbstA
    on compile all the class and run of
    java A
    should print A as the name
    java B
    should print B as the name
    Are there any suggestions to know the class name in the static method, which is in the parent class.
    Regards,
    Raja Nagendra Kumar

    Well, there's a hack you can use, but if you think you need it,Could you let me the hack solution for this..
    you probably have a design flaw and/or a misunderstanding about how to use Java.)May be, but my needs seems to be very genuine..of not repeat the main method contents in every inherited class..
    The need we have is this
    I have the test cases inheriting from common base class.
    When the main method of the test class is run, it is supposed to find all other test cases, which belong to same package and subpackages and create a entire suite and run the entire suite.
    In the above need of the logic we wrote in the main method could handle any class provided it knows what is the child class from which this main is called.
    I applicate your inputs on a better way to design without replicating the code..
    In my view getClass() should have been static as the instance it returns is one for all its instances of that class.
    I know there are complications the way compiler handles static vars and methods.. May be there is a need for OO principals to advance..
    Regards,
    Raja Nagendra Kumar
    Edited by: rajanag on Jul 26, 2009 6:03 PM

  • Invalidate cache on agents using CacheInvalidation Listener from BCC

    We have a stored procedure running from BCC server once the data load completes i want to clear the catalog cache from agents from BCC using CacheInvalidation Listener, how to configure CacheInvalidation Listener on agent side and send message from BCC server to invalidate the cache.
    on oracle API i saw invalidateAllCaches() , method how can i trigger this from the BCC server on the agent server?
    Edited by: 946140 on Dec 1, 2012 4:12 AM

    I think you can try invoking cache invalidator client. Refer this:
    http://docs.oracle.com/cd/E24152_01/Platform.10-1/ATGRepositoryGuide/html/s1018invokethecacheinvalidatormanuall01.html
    Note that you would have to include <ATG>/DAS/lib/classes.jar in classpath while invoking the client class.

  • How to use Action/Input maps

    It seems to me that the move to sharing actions menus, buttons, and other components is a logical one, given that it is desirable to have all references to the action reflect its enabled state.
    The question that arises is: which ActionMap object to use as the central store? Do you create your own and pass it on somewhere?
    And, if you try to do anything with homegrown InputMaps then the components stop seeing the events. I wish there was a definitive YOU MUST DO IT THIS WAY tutorial.
    Why is there no factory API that can create UI components pre-attached to actions and with accelerators or mnemonics already set? Then we would not need to write half the code we do now. My solution:
    public class ComponentFactory {
       ActionMap myMap;
       public ComponentFactory(ActionMap map) {
          myMap = map;
       public JButton createButton(String actioncommand) {
           Action a = myMap.get(actioncommand)
           if(a==null)
              return null;
           return new JButton(a);
       public JMenuItem createMenuItem(String actioncommand) {
        // etc...
       public void setAction(Action a) {
           myMap.put(a.getValue(ACTION_COMMAND_KEY),a);
       public void setEnabled(String actioncommand, boolean state) {
           Action a = myMap.get(actioncommand);
           if(a!=null)
               a.setEnabled(state);
    }Is there any concensus as to the best way to handle ActionMaps/InputMaps?

    Hugh,
    >
    The tutorial is a touch short on this subject, whilst
    it is good on how to create and use actions with
    toolbars and the like, the section on InputMaps and
    ActionMaps is far too brief to get the wider picture.
    The API docs on the same is about one paragraph's
    worth.okay, I just checked the tutorial - it's a bit short on the inputMap/actionMap indeed.
    >
    You are mixing up two different issues:
    a) customize a button with an action
    b) bind a keyStroke to an action for an arbitrary
    jComponent
    a) has nothing to do with b)If b) has nothing to do with a) why have MNEMONIC_KEY
    and ACCELERATOR_KEY on the action?Hmm... where do you see a contradiction to my statement? Those keys are part of a) as they are used for customization of the AbstractButtons: the button's mnenmonic/accelerator properties are set to the corresponding values of the action. This propertyChange triggers an update of the keyBinding to the button's "pressed"/"doClick" actions as registered in the actionMap. They are never used (at least not internally by Swing) for b)
    Historically the action is older than the inputMap/actionMap: basically it's an ActionListener (which is more or less a command pattern) plus some (view) state. This "plus" was designed right in the beginning of Swing for a) to enable state sharing between different "buttons" but not really integrated until version 1.4. parallel to that the need for a general mechanism of binding between keyStrokes and "commands" became obvious and inputMap/actionMap were introduced in 1.3. The only action state that's needed for this mechanism to work is the enabled property. All values are ignored - so currently they somehow appear to be overloaded in the context of the inputMap/actionMap. Personally I think they are very powerful because of this extra flexibility.
    >
    There is still not a single diagram; and I maintain
    that it is less than useful to beginners who are not
    familiar with the terminology used. Well, IMO diagrams are not everything - I still think it much easier to understand than the dnd spec or the focus spec f.i.
    >
    you are free to use whatever object you want as akey
    - write a utility method to use the name, if feellike
    doeing so. There is nothing in the framework that
    would single out the name as "the" key to use, The keybindings document specifically states:
    "New actions can be added to a component equally
    easily."
    "The conventional key for an action is it's
    name." If there is a conventional way then it
    should be encouraged with an appropriate API. I get your point. And I definitely agree on following a convention if there is one. Except when the convention is quite immature (to formulate mildly) - and not even followed by Swing internally: most of the default actions registered in the actionMap don't even have a name, the binding is done by string literals ... duplicated in at least two places: the XXLookAndFeel and the ui-delegates.
    Greetings
    Jeanette

  • How to use Property Editor from an Add-In?

    Hi,
    I am writing a WYSIWYG add-in for JDev that allows users to put some object into a JPanel instance.
    Thess object has properties such as left, right, width, height, etc.
    - Question: how to use JDev's property editor to allow users change properties of thess object?
    - Another word: how to user JDev's Property Editor API from an add-in?
    I looked at the document. It does not give me enough information about Property Editor.
    Thanks in advance,
    Trung

    Hello Prasad,
    You are on the right avenue - launch an external application which can connect to running Outlook instance and then close it. After this you can launch Outlook anew. Here are the steps required to get the job done:
    1. Use the Marshal.GetActiveObject method which obtains
    a running instance of the specified object from the running object table (ROT) - Outlook in your case, for example:
    // Check whether there is an Outlook process running.
    if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
    // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
    application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
    then use the
    Quit method to close the running instance. The
    associated Outlook session will be closed completely; the user will be logged out of the messaging system and any changes to items not already saved will be discarded.
    2.  Use the
    Start method of the System.Diagnostics.Process class to start Outlook anew.

  • Can't get ClassLoader from static method.

    I'm trying to get the ClassLoader within a static method getInstance().
    public class PropertyManager {
    public static PropertyManager getInstance(String fileName) {
    //The following line returns null
    ClassLoader cl = (new Object()).getClass().getClassLoader();
    URL url = cl.getResource(fileName);
    etc...
    However if getInstance gets called from e.g. a statless session bean, a null
    is returned instead of a valid ClassLoader.
    The same code executed from a standalone java program (e.g. from
    main(String[] args)) returns a valid ClassLoader
    Why does getClassLoader behave differently in WebLogic than in a standalone
    java program?
    Thanks for you help.
    Bernie

    Sorry for the confusion. I wrote a couple of more test programs and was able
    to confirm that WL behaves exacltly the same as java does. For some reason
    my intial tests were messed up...
    getClassLoader() executed from a static method always returns null (in WL as
    well as in a java standalone program).
    In this case ClassLoader.getSystemClassLoader() will return a valid class
    loader.
    Thanks for your help.
    Bernie
    "Rob Woollen" <[email protected]> wrote in message
    news:[email protected]..
    Bernhard Lenz wrote:
    I tried that as well, but getClassLoader() still returns null when
    executed
    in WL.
    I'm still not clear how getClassLoader() gets affected by running withinWL.
    >>
    >
    Very odd. Where is this class located? in the server's classpath, in ajar or
    war file? Does getClass().getClassLoader work from a non-static method inthis
    class?
    -- Rob
    "Rob Woollen" <[email protected]> wrote in message
    news:[email protected]..
    You want PropertyManager.class.getClassLoader()
    -- Rob
    Bernhard Lenz wrote:
    I'm trying to get the ClassLoader within a static method
    getInstance().
    >>>>
    public class PropertyManager {
    public static PropertyManager getInstance(String fileName) {
    //The following line returns null
    ClassLoader cl = (new Object()).getClass().getClassLoader();
    URL url = cl.getResource(fileName);
    etc...
    However if getInstance gets called from e.g. a statless sessionbean, a
    null
    is returned instead of a valid ClassLoader.
    The same code executed from a standalone java program (e.g. from
    main(String[] args)) returns a valid ClassLoader
    Why does getClassLoader behave differently in WebLogic than in astandalone
    java program?
    Thanks for you help.
    Bernie

  • How to use download listener for xml files?

    Hi all,
    In my usecase I should write the xml contents to the file using Output Stream writer.
    As of now I am using the below lines of code in the download listener method.
    String s = myDoc.getContent().toString();
    w.write(s);
    myDoc is my xml document. I can see the file but there is no content.
    Kindly come out with your help in which I could achieve this.
    Thanks,
    Phani.

    Hi john,
    What all I am trying to ask is how could I write xml data to external file by clicking a button or a link etc.. which is in the JSF page.
    Now for that I created a button and dragged the <af:fileDownloadActionListener> into the button.
    I binded the listener with the backing bean method.
    public void sayHello(FacesContext context, OutputStream out) throws IOException
    OutputStreamWriter w = new OutputStreamWriter(out, "UTF-8");
    IDocument myDoc = new Document2004();
    myDoc.addEle("sai");
    w.write(myDoc.getContent().toString());
    w.flush();
    in the method you can see IDocument that is an interface which I have in the external JAR files that I am using to write data to MS Word.
    The myDoc which I created as an object of IDocument has lot of methods in which I am using addEle(String) which writes a string to word document.
    in the writer object writer I am getting the content of the myDoc inorder to convert that to string as it will be in xml format.
    When I am writing every thing I can download and save the document but unable to see the data that I have written that is "*sai*" instead a blank page is getting opened.
    When I do the same with Creating a file object in the local disc using File f = new File(path) rather than downloading it using the listener I can see the contents what I have written.
    This is what all I mean to ask. Kindly come up with your help
    Thanks,
    Phani.

  • How to use Function CCM_HAB_EXECUTE from CIC WinClient?

    Hello,
    i me calling the function "CCM_HAB_EXECUTE" to call specific CIC-Actions (Transactions) from the CIC WinClient?
    How can i also give the Function above the Value of the object i would like to display or edit in the called Transaction??
    For example the Function can call a Transaction to display a Business-Partner in CRM, so how can i also give the Number of the Business-Partner too, in order to show its detail directly??
    Thanks,
    Nazih
    Message was edited by: Nazih Kayyali

    Hello,
    I want to use funtcion CCM_HAB_EXECUTE to process cic actions but how can I read the result? If the users cancels the transaction for instance...
    thx in advance,
    jeroen

Maybe you are looking for

  • Primary email address - madness

    Hi, I'm trying to change the destination where my purchase receipts are sent. I have searched the web & these forums but nothing is working for me. Here are my example details: Apple ID login - [email protected] (this is my user name & where my recei

  • Magic Mouse 1 finger swipe moves app to new desktop

    My mid-2009 is running the latest ML bits and it has developed an extremely irritating behavior. When using my Magic Mouse a 1 finger swipe across the top part of a window moves it to the next desktop. I have my settings in system prefs set to use a

  • Synchronous Receiver JDBC adapter--response message empty

    My scenario is ABAP Proxt to JDBC synchronous case where I am calling a stored procedure "GetEmployer" to get the relevent data. There is no input data to the stored procedure, just need to call the stored procedure to return the records. In the SXMB

  • Stop and restart rac resources

    what happends if we take down time start and restart the resources can any one explain on the above scenario in two node rac o/s windows version 10.2.0.4 thanks in advance cheers

  • Working with Aperture for the Press

    I would like to change my workflo and make it faster to get images to my Co. website faster then my competition. I usually drag my images from my card to a folder on my desktop with the event title. I then do my metatag info about the event to my sel