Event handling with images

I am not sure how to get my images to respond to the mouseClicked event. I need to know how I can get an image to play an audio clip once it is clicked on.

I am not too sure how to do that, so I will show you the code that I am using for my DrawingPanel class. I have a MyApp class as the main. I have the part in the mouselistener commented out because it doesn't compile. Please list a suggestion.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.applet.AudioClip;
import java.net.URL;
import java.net.MalformedURLException;
public class DrawingPanel extends JPanel
private Image goku, trunks, vegeta, gohan, piccolo, background;
private AudioClip clip1, clip2, clip3, clip4, _clip5;
private JApplet _app;
public DrawingPanel(JApplet app)
super();
_goku = new ImageIcon("goku.gif").getImage();
_vegeta = new ImageIcon("vegeta.gif").getImage();
_gohan = new ImageIcon("gohan.gif").getImage();
_trunks = new ImageIcon("trunks.gif").getImage();
_piccolo = new ImageIcon("piccolo.gif").getImage();
_background = new ImageIcon("DBZ%20wallpaper%202.jpg").getImage();
_clip1 = app.getAudioClip(app.getCodeBase(), "goku.wav");
_clip2 = app.getAudioClip(app.getCodeBase(), "vegeta.wav");
_clip3 = app.getAudioClip(app.getCodeBase(), "gohan.wav");
_clip4 = app.getAudioClip(app.getCodeBase(), "trunks.wav");
_clip5 = app.getAudioClip(app.getCodeBase(), "piccolo.wav");
_app = app;
public void Play1()
_clip1.play();       
public void Play2()
_clip2.play();       
public void Play3()
_clip3.play();       
public void Play4()
_clip4.play();       
public void Play5()
_clip5.play();       
public void paint(Graphics g)
super.paint(g);
g.drawImage(_background, 0, 0, app.getWidth(), app.getHeight(), null);
g.drawImage(_goku, 100, 100, 150, 200, null);
g.drawImage(_vegeta, 350, 100, 150, 200, null);
g.drawImage(_gohan, 300, 400, 150, 200, null);
g.drawImage(_trunks, 100, 400, 150, 200, null);
g.drawImage(_piccolo, 550, 100, 150, 200, null);
this.addMouseListener(new MyMouseListener(this));
private class MyMouseListener extends MouseInputAdapter {
private DrawingPanel _dp;
private Point _point;
public MyMouseListener (DrawingPanel dp) {
_dp = dp;
public void mouseClicked (MouseEvent e){
_point = e.getPoint();
/*if (_goku.getPoint() == _point) {
_dp.Play1();
else if (_vegeta.contains(e.getPoint()) == _point) {
_dp.Play2();
else if (_gohan.contains(e.getPoint()) == _point) {
_dp.Play3();
else if (_trunks.contains(e.getPoint()) == _point) {
_dp.Play4();
else if (_piccolo.contains(e.getPoint()) == _point) {
_dp.Play5();
}

Similar Messages

  • C# control event handling with javascript

    How can I get javascript to execute for "onchange" / "OnSelectedIndexChanged" event instead of a CodeBehind method? I think "OnSelectedIndexChanged" event has to be handled by CodeBehind; but how can I replace that (or onchange) with
    a javascript event handler?
    I have the following in my xyz.ascx file:
    <asp:DropDownList ID="ddlTypeCar" CssClass="BatsRefAddressTypes" runat="server"
                      onchange="javascript: testAlert();"
                      OnSelectedIndexChanged="ddlTypeCar_SelectedIndexChanged"
                      AutoPostBack="True" />
    I could not get the javascript to execute, even though I removed OnSelectedIndexChanged="ddlTypeCar_SelectedIndexChanged" and/or set AutoPostBack="false".
    Additionally, I tried added the following in xyz.ascx.cs Page_Load() method.
    ddlTypeOfAddress.Attributes.Add("onchange", "javascript: testAlert();");
    which didn't help.
    Thanks for your help in advance.

    Hi,
    you can control client events instead of server events with javascript
    look this url for more information
    http://www.w3schools.com/js/js_events.asp
    Regards

  • Registering event handler with preloader

    As you can see from the code below, I have an application
    with a custom preloader designated in the Application tag.
    I would like the preloader to be able to receive a message
    from my main application but in order to that I need to register a
    method in the preloader as an event handler for an event fired by
    my application and in order to do that I have to have a reference
    to both the preloader and the application.
    Where can I get a reference to both? this.preloader seems to
    be null when the initialize() event is fired in my application and
    mx.core.Application.application is null in my preloader. Is there
    any way at all to do this?
    I would GREATLY appreciate any help with this! I've been
    struggling with this for hours :(
    Thanks!
    Moshe

    Thank you Nayan..
    BR
    Aliye

  • Event Handling with Java API.: Adding to a hierarchy table throws 2events

    I´m having some problems with the event handling. I´ve registered a Class with extends AbstractDataListener as EventListener. When there are changes in the product hierarchy table, some extra work should be done. However if i add a new record into the hierarchy, two events are fired.
    DEBUG DataEventListener.java:123 - Added:Development;PRODUCT_HIERARCHY;R17;Getra?nke, SEW
    DEBUG DataEventListener.java:123 - Added:Development;PRODUCT_HIERARCHY;R17;32 Zoll, B&R
    DEBUG DataEventListener.java:123 - Added:Development;PRODUCT_HIERARCHY;R18;56 Zoll, Lenze
    DEBUG DataEventListener.java:123 - Added:Development;PRODUCT_HIERARCHY;R18;20 Zoll, allgemein
    In this case, i added the records "32 Zoll, B&R" and then "20 Zoll, allgemein". As you can see in both cases two events are fired and the first event seems to come with wrong data. The reported id for the newly created record is R17. For the logging, i did lookup the entry in the hierarchy table by id and use the displayvalue of the record. But the first event always shows the displayvalue from some already existing entry.
    How can i avoid duplicate events or if this is not possible, how i can recognize that the display value of the first event is not valid.

    I have not tetsted it yet, because I'm waiting for my server to be updated, but SAP told me that the API version 5.5.42.67 should fix the problem.
    Thanks for your post.

  • Event handling with JSF

    Hi Everybody,
    I have a question about event handling and I am just wondering if I can do the following with JSF.
    I have two HTML dropdown lists A and B. When ever a value changes in list A, based on the selected value, list B has to be populated. Is it possible to do with JSF? Can you guys give me pointers where some code samples may be available?
    Cheers!
    Krish

    Take a look at the JSF Value-Changed Listener sections

  • Event handling with button

    Hi All,
    I am trying to write an event handling on my button, but i seem dont know where to start from. My code are below:
    import java.net.*;
    import java.io.*;
    public class ReadWrite
    public static void main(String[] args) throws Exception {
    URL myLocalhost = new URL("http://localhost/Write.pl");
    URLConnection myURL = myLocalhost.openConnection();
    BufferedReader myBR = new BufferedReader(
    new InputStreamReader(
    myURL.getInputStream()));
    String inputLine;
    while ((inputLine = myBR.readLine()) != null)
    System.out.println(inputLine);
    myBR.close();
    I want to write a code with a button to run the above code.
    Could you please advise?
    Thank for any consideration you may give me.

    here's the code to read a file, modify for your url connection
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    class Testing extends JFrame implements ActionListener
      public Testing()
        setLocation(400,300);
        setSize(200,100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        JButton btn = new JButton("Read/Write");
        btn.addActionListener(this);
        panel.add(btn);
        getContentPane().add(panel);
      public void actionPerformed(ActionEvent ae)
        BufferedReader myBR = null;
        try
          myBR = new BufferedReader(new FileReader("Test.txt"));
          String inputLine;
          while ((inputLine = myBR.readLine()) != null)
            System.out.println(inputLine);
          myBR.close();
        catch(Exception e){e.printStackTrace();}
      public static void main(String args[]){new Testing().setVisible(true);}
    }

  • Event Handler with parameters

    I am to create a generic event handler ro process XML
    returned from the server. Its name is this code is "loadFormData".
    Here is my code:
    var params:Object = new Object();
    params.requesttype = 'send';
    params.datarequest = 'xml';
    params.methodexecute = 'mProcessFileRequest';
    params.formname = "FileIdAction";
    params.fileid = parentApplication.cboFileList.id;
    var t:loadFileData = new loadFileData();
    xmlModuleData.addEventListener(ResultEvent.RESULT,
    t.loadFormData(ResultEvent, frmGeneral));
    var r:runXML = new runXML();
    r.getXMLData(xmlModuleData, params);
    It would work if I dont send any parameters to
    t.loadFormData. But then it is not a generic solution. Is it
    possible to send parameters to a callback function?
    Thanks

    Thanks Charlie
    Liao
    and congrats to all :-)
    * Charlie,
    is there a new "Auto Spam Filter"?
    [Personal Site] [Blog] [Facebook]

  • Event Handler with Internal Loops

    Hi...
    I'm trying to update a basic program to handle control events more efficiently.  The program needs to perform the following functions on start button press:
    1)  Import data file and parse instrument settings from multiple (X) rows
    2)  Perform loop with case for each row changing input settings, the read test equipment, and store data in new output data file
    I've looked at producer/consumer example and the continuous measurement and logging example, but not sure if either (or none) of the following two options is the best way to handle the looping from the file...
    A)  Use events to trigger looping for all input cases within a consumer (I've had a problem with this due to not being able to terminate the loop within the consumer with an abort button)
    B)  Make the consumer only a single data acquisition and load loop inputs as queues and generate output queues to be handled by another parallel logging loop
    Any advice?

    Hi bripple,
    Based on what you've described above, a Producer/Consumer Design Pattern (Events) might work. There is a template for this design pattern that ships with LabVIEW which you can access by going to File > New > VI > From Template > Frameworks > Design Patterns. When the user clicks the start button on your front panel, you can queue up a command that will trigger your consumer loop to read the file and loop over each instrument setting. Within that loop, you should be able to queue up additional events corresponding to each instrument setting and reading.
    In terms of error handling, you can conditionally stop a loop if you detect an error. If your user decides to push a button on the front panel to stop the entire process, you can use Enqueue Element at Opposite End to put a stop command at the beginning of the queue. When your consumer loop encounters this event, it can flush the queue and do any cleanup it needs to perform.
    One additional thing to be cautious of is that queues can only handle one data type. Because of that, you may also want to consider a Queued Message Handler design pattern. This design pattern allows you to send both a command and data along with that command. I think that would be ideally situated for you since you could send a "Read Instrument" command along with the data for its settings. You can access this design pattern from within LabVIEW as well. If you have LabVIEW 2012 or LabVIEW 2013, see these instructions. The things I've said above also hold true for the Queued Message Handler as well.
    Let me know if you have any questions or if this is helpful.
    Regards,
    Matthew B.
    Applications Engineer
    National Instruments

  • Event handling with multiple panels

    Hi there,
    Like many here, I'm very new to this stuff so please bear with me..
    I've been building a gui, using a main "parent" JPanel and several
    subpanels. The main reason for creating subpanels was to help me
    with the layout (someone might let me know if this was a bad idea!).
    Now, all of the subpanels generate events in one form or another. What I'd
    like to do is find out the best way to handle ALL of the events that
    can be generated from my various subpanels from the "parent" panel. Hopefully
    this makes sense :) Could anyone offer any suggestions as to the best way
    to achieve this?
    For example, panel1 is a JPanel contains a slider and a button.
    multipanel is another JPanel that contains 6 panel1's. finally
    the main (parent) panel contains the multipanel.
    So, a program that creates an instance of the parent panel wants to know
    the value that one of the sliders on one of the panels in the multipanel
    has (!). How does it get the value?
    I hope I explained myself! Many thanks in advance for any advice offered,
    dan

    class InnerPanel extends JPanel {
    Vector listeners;
    public void add(SwingEventListener lsnr) {
    listeners.add(lsnr);
    protected void notifyListeners(AWTEvent ev) {
    for (Iterator i = listeners.iterator();i.hasNext();) {
    SwingEventListener lsnr = (SwingEventListener) i.next();
    lsnr.eventPeformed(ev);
    public void actionPerformed(ActionEvent ev) {
    notifyListener(ev);
    Your SwingEventListener will be
    interface SwingEventListener {
    public void eventPefromed(AWTEvent event);
    public ParentPanel extends JPanel implements SwingEventListener {
    public void eventPerformed(AWTEvent event) {
    ... do what is required.

  • Event handling with UIScrollView and it's subview

    Hi,
    I have a UIScrollView and inside it a UIImageView. I have a lot of difficulities to handle the events with these two views. Here is what I want to do:
    If it is a multi-touch event (event.allTouches.count > 2), I want the UIScrollView to handle the event, i.e Zoom in/out and pan. If it a single touch event (event.allTouches.count == 1), I want the UIImageView to handle the event.
    Could you please tell me how to do this?
    Thank you very much.
    ff

    Take a look at the JSF Value-Changed Listener sections

  • Event handling with buttons and mouse

    Hi, Im a beginner in Java...!!!
    I have 4 buttons with me- 2 for color(red,blue) and 2 for size(big,small)..
    How do we divide the frame into 2 panels..one for Buttons and Other for Mouse events...
    Now,if I click on RED button and BIG button..and later click in the Mouse Panel area..I shud get a big rectangle filled with red color..and similarly for small / blue..etc...if a new selection is made..the previous rectangles should remain as they are...
    Im unable to get the implementation...any help will be appreciated.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class ButtonPanel extends JPanel
    implements ActionListener, MouseMotionListener
    {  public ButtonPanel()
    blueButton = new JButton("Blue");
    redButton = new JButton("Red");
    bigButton = new JButton("Big");
    smallButton = new JButton("small");
    add(blueButton);
    add(redButton);
    add(bigButton);
    add(smallButton);
    blueButton.addActionListener(this);
    redButton.addActionListener(this);
    bigButton.addActionListener(this);
    smallButton.addActionListener(this);
    public void actionPerformed(ActionEvent evt)
    Color color = getBackground();
    repaint();
    // Paint Method
    public void paintComponent(Graphics g)
    {  super.paintComponent(g);
    class ButtonFrame extends JFrame
    {  public ButtonFrame()
    {  setTitle("ButtonTest");
    setSize(300, 200);
    addWindowListener(new WindowAdapter()
    {  public void windowClosing(WindowEvent e)
    {  System.exit(0);
    Container contentPane = getContentPane();
    contentPane.add(new ButtonPanel());
    public class ButtonTest
    {  public static void main(String[] args)
    {  JFrame frame = new ButtonFrame();
    frame.show();
    }

    can U kindly code it for me....!!!you're getting closer,
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=2&t=011033but rent-a-coder is that way ---->

  • Event handling with TextArea

    hi all,
    i'm really new to java programming !
    so, i will be glad for any help that is given by you.
    this is the problem:
    when we add text in to a TextArea, an event should be
    fired. that means, we should capture the status change of the TextArea.
    i tried with: implementing Actionlistener
    ItemStateChanged
    but didn't work !
    any suggestions ?
    thanx
    neo

    Try adding a TextListener.

  • Unobstrusive event handling with Spry

    Hi,
    I've got this
    In one of my javascript files I have the function
    function storeCaret(mytext) {
         if (mytext.createTextRange) {
             mytext.caretPos = document.selection.createRange().duplicate();
    In my source I have
    <textarea name="ReplyQuote"  rows="10" id="ReplyQuote" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);" onchange="storeCaret(this);">Text in here</textarea>
    Which has various event handlers that I would like to make unobtrusive.
    I've tried
    Spry.$$('#ReplyQuote').addEventListener("change",storeCaret(this),false);
    Spry.$$('#ReplyQuote').addEventListener("click",storeCaret(this),false);
    Spry.$$('#ReplyQuote').addEventListener("keyup",storeCaret(this),false);
    Spry.$$('#ReplyQuote').addEventListener("select",storeCaret(this),false);
    But it's just not returning the correct reference to the function storeCaret.  So I guess my understanding of this needs improving.  How do I ensure I pass the same reference unobtrusively?
    Thanks
    Phil

    Spry.$$
    ('#ReplyQuote').addEventListener("change",storeCaret(this),false);
    that will execute the storeCaret() function inside the observer.. The 
    function should be passed in as reference to the function. (without 
    the () );
    Spry.$$('#ReplyQuote').addEventListener("change",storeCaret,false);
    Will work. the "this" inside the function will reference to your 
    ReplyQuote

  • Event handling with cl_gui_alv_tree_simple

    Hi all...
    When i register some event for object cl_gui_alv_tree_simple it's work fine, but on the screen, only if i register a event (item_double_click), the 3rd level don't open (my tree has 4 levels)....
    Some help?!

    Your explanation of the problem is not clear. Have a look at the following demo program.
    BCALV_TREE_SIMPLE_DEMO
    Regards
    Raja

  • Canvas event handling with a custom menu

    Hey guys!
    OK, first off i have been trucking along quite nicely on this midlet but i think i have hit a fork in the road.
    I designed a custom menu that extends Canvas.
    I keep track of what is selected (there are 4 items) as an int value (0-3).
    When the midlet first starts, I have it go to the menu canvas.
    Now the problem I have is that I cannot figure out a way to signal the midlet to load another screen (a form Displayable) when the 'FIRE' button is pushed. (Note: the up and down buttons work fine)
    What is a good aproach to signal to the main class midlet that I want to load the corresponding screen??
    I have tried boolean with accsesor methods, and cannot get that way to work.
    If there is a a good link you guys have handy please pass it along also!
    Thanks,
    Nick
    www.2002registry.com

    Can't you just do the following:
    if (action == FIRE)
    display.setCurrent(your_new_screen);
    do_what_ever();

Maybe you are looking for

  • Third Party Process - Accounting Effects

    Hi  SAP-SD Gurs, Can u help me out  in Third Party Parocess - Accounting Effects. Regards, Sreenivas Peruru

  • IBook won't turn on

    So this is actually a question for my mom. Her iBook G4 has not been working correctly. Sometimes (not all the time) her computer will not turn on after she turns it off. The only way we can get it to turn back on is: 1. Take out the battery and unpl

  • How do you animate basic text in FlashDevelop?

    I need a text to be sliding on the Y axis but i cannot seem to figure out the code for it? Any ideas?

  • Hide attributes in adobe interactive form.

    Hi All, Can anybody help how to how to hide/show attributes in adobe interactive forms? The scenario is like this: In data view there are 2 attributes a1,a2. Currently i am showing both the attributes in the form. But only that attribute will be show

  • Unifying different iPhoto libraries & photos not in a library

    I am still trying to fix some iPhoto issues that have cropped up due to hard drive failures. We have had 3 hard drives in about 2.5 years. We have several thousand (maybe 20K?) pictures in our library. Because it takes so long to back-up the library,