Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8795405
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T23:22:57+00:00 2026-06-13T23:22:57+00:00

when i was programming in c# i was making very often use of events.

  • 0

when i was programming in c# i was making very often use of events. Now I would like to achieve something similar in Java. I know both languages are diffrent and there are some diffrences in implementing such mechanism. Well to give better picture maybe i will describe a little what i want to get, because i might confuse some of terminology:

MyClass contains code that handles launching MyEvent and some code that in certain situations launches that event.

MyEventArgs is class that transports data from MyClass and is sent along with event launch, so function that handles MyEvent has some additional information about state of MyClass instance.

And there is MyApp class that in main method contains instance of MyClass and code handling MyEvent and when event is raised inside MyClass certain actions are performed in code that listens to MyEvent.

If it’s still unclear, what i mean to achieve is exactly like c# mechanism that is behind button click, just instead of button there is my class, there are my event arguments instead of mouse event args and there is behaviour designed by me instead of click.

I’ve tried to google some answers to my problem and for example i found sites like:

http://javarevisited.blogspot.com/2011/12/observer-design-pattern-java-example.html http://www.javaworld.com/javaworld/javaqa/2002-03/01-qa-0315-happyevent.html

And either im just lost and I’m looking in bad places/using bad keywords, or what more possible i can’t understand anything out of these examples/i can’t transform them to work in way I need.

What im asking for, is some example, or atleast some draft of code handling such mechanism with use of MyClass, MyEvent, MyEventArgs, names, pointing code i should use in my class to raise event and some sample use of class and handling of event in Main method, so it would help me wrap my mind around this problem.

==========Edit========

Maybe there are some things like that avaliable for android developers? As my goal is to get to get into mobile apps development after i dust off java.

==========Edit========

If anyone still interested, here is some sample code, it doesn’t use names i metioned, just shows in general what im looking for:

And is there no exact solution, maybe somone would suggest something similar to thing im looking for?

frmTest.cs

namespace SampleApp
{
    public partial class frmTest : Form
    {
        CountdownTimer ctmrTest;

        public frmTest()
        {
            InitializeComponent();
            ctmrTest = new CountdownTimer(100);
            ctmrTest.CountdownTimerTick += new CountdownTimer.CountdownTimerTickEventHandler(ctmrTest_CountdownTimerTick); 
        }

        void ctmrTest_CountdownTimerTick(object sender, CountdownTimerEventArgs ea)
        {
            lblTimer.Text = ea.timeString;
            if (ea.countdownFinished) countdownEnd();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            ctmrTest.Reset();
            ctmrTest.Start();
        }

        void countdownEnd()
        {
            MessageBox.Show("Finish");
        }
    }
}

CountdownTimer.cs

namespace SampleApp
{
    public class CountdownTimer
    {
        Timer tmrTicks = new Timer();
        int secondsLeft = 0;
        int numberOfSecondsToCountdown = 0;

        public bool IsWorking
        {
            get { return tmrTicks.Enabled; }
        }

        public CountdownTimer(int seconds)
        {
            ...
        }

        void tmrTicks_Tick(object sender, EventArgs e)
        {
            ...
            WhenCountdownTimerTick(new CountdownTimerEventArgs(secondsLeft, numberOfSecondsToCountdown, true));
        }

        public void Reset()
        {
            ...
            WhenCountdownTimerTick(new CountdownTimerEventArgs(secondsLeft, numberOfSecondsToCountdown, false));
        }

        public void Stop()
        {
            tmrTicks.Enabled = false;
        }

        public void Start()
        {
            ,,,
        }

        public delegate void CountdownTimerTickEventHandler(object sender, CountdownTimerEventArgs ea);

        public event CountdownTimerTickEventHandler CountdownTimerTick;

        protected virtual void WhenCountdownTimerTick(CountdownTimerEventArgs ea)
        {
            if (CountdownTimerTick != null)
            {
                CountdownTimerTick(this, ea);
            }
        }
    }
}

CountdownTimerEventArgs.cs

namespace SampleApp
{
    public class CountdownTimerEventArgs : EventArgs
    {
        public string timeString = "";
        public bool countdownFinished = false;

        public CountdownTimerEventArgs(int secondsLeft, int SecondsToCountdown, bool isfinished)
        {
            countdownFinished = isfinished;
            timeString = string.Format("{0:00}:{1:00}", secondsLeft / 60, secondsLeft % 60);
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T23:22:57+00:00Added an answer on June 13, 2026 at 11:22 pm

    If i understand you correctly (i’m just starting learning C#), the normal way to do it in Java is to use the observer pattern (listener pattern):

    You create a listener interface with a method to be called when your event happens.
    That method can take some event-arguments and a sender as parameter, if you like.
    For example:

    public interface MyListener { // This is probably your MyEvent
        void myEventFired(Object sender, MyEventArgs eventArgs);
    }
    
    public class MyEventArgs {
        ...something...
    }
    

    A class which is to respond to your kind of event, needs to implement the above interface.
    (see an example a little below (MyListeningClass))

    Ok, so then you need a class (or more classes) which fires your event: MyClass.
    Usually MyClass has some way for other classes, who wants to respond to MyClass‘ event, to register
    themselves with MyClass. (Or more precisely, register themselves with a specific object of MyClass). This allows the MyClass-object to know which other objects it should inform about when the event happens.

    This is usually done by creating a method called “add[ListenerName]” in the class firing the event – in this case “addMyListener” in MyClass.
    To make this example simpler, let’s just assume there can only ever be one listener, so we will call it “setMyListener” instead:

    public class MyClass {
    
        private MyListener listener = null;
    
        // This is a method which sometimes fires an event, by calling the fireEvent() method below
        public void doSomething() {
            ...
            if (something) {
                // Let's say the event happens if "something" is true. 
                // So now we "fire the event". What "firing the event" means, 
                // is just to call the "myEventFired" method in the listener.
                fireEvent();
            }
            ...
    
        }
    
        // this is called from the method above to fire the event - i.e. to tell the listener that the event has happened
        protected void fireEvent() {
            if (listener != null) {
                Object sender = this; 
                MyEventArgs eventArgs = new MyEventArgs(...something...);
                listener.myEventFired(sender, eventArgs);
            }
        }
    
        // This method is called by the listener, to register itself as listener on this object.
        // MyClass remembers the listener in the "listener" instance variable, so that 
        // when the event happens at some later point in time, it knows which object it  
        // has to tell it to.
        public void setMyListener(MyListener listener) {
            this.listener = listener;
        }
    }
    

    (To support more than one listener, just have a list of listeners List<MyListener> listeners instead of the MyListener listener instance variable, and create an addListener and removeListener method instead of the setListener method. In the Android API they usually only allow one listener, so i thought i would show that version)

    So now we just need the class which wants to listen for the event. I.e. the class implementing the MyListener interface. (This class is thus a listener). A simple example:

    public class MyListeningClass implements MyListener {
    
        public MyListeningClass() {
            MyClass myClass = ...get the MyClass object from somewhere...;
            myClass.setMyListener(this);
        }
    
        // this is called by MyClass when the event occurs
        public void myEventFired(Object sender, MyEventArgs eventArgs) {
            System.out.println("EVENT HAPPENED!");
            System.out.println("Sender is: "+sender);
            System.out.println("MyEventArgs are: "+eventArgs);
        }    
    }
    

    (Of course you don’t actually have to create the interface if you don’t want to. You could of course just hardcode the MyListeningClass in MyClass instead, but it’s better style to use interfaces, to decouple MyClass and MyListeningClass from each other. And it’ll also be more extendable later, to allow other classes than MyListeningClass to listen for the events too.)

    There are many examples of this in the Java API. For example SWING makes heavy use of listeners – for example for button-clicks, as you mention. And of course the Android API too.

    I’ll see if i can find some examples of this later, but it’s very late and i’m very tired, so maybe tomorrow 😀 (and fix any spelling mistakes :D). Hope it helped a bit.

    To Recap:

    • MyClass (the class producing the events) needs some way to tell other classes about that the event has happened, when the event happens.
      It does that by calling a method in these classes when the event happens.

    • For MyClass to be able to call a method in these other classes, they have to implement some interface.

    • The classes which want to be told when the event happens, needs a way to tell MyClass that they want to
      be told about it. This is the reason we need the MyClass.setMyListener method.
      (or if we had allowed more than one listener: the MyClass.addMyListener method)

    (So there is nothing magical about this. It’s just simple method calling.)


    (Note that, a listener interface is usually named “[name of the event]Listener”. So instead of “MyListener” i should have called it “MyEventListener”, according to the naming convention, if we say that the event is called “MyEvent”. But for this post i think it looked too long and less simple. UPDATE: Now that i think about it, you actually usually omit “Event” from the name, so “MyListener” is right. For example if you have an event you call “OnClickEvent”, you call the interface “OnClickListener”.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Im new to programming and I dont know very much about but I'm making
I'm somewhat new to OOP programming so it's very likely I'm making some stupid
For my bachelor thesis I'm programming an Role Playing Game maker. I'm making use
I am new to programming and I'm making a very simple blackjack game with
In the purpose of practicing for an upcoming programming contest, I'm making a very
I'm very unaware of how the syntax goes for GTK+Glade3 programming. But for now
I am just getting started with programming and am making a Tic-Tac-Toe program. In
so I'm making some basic programming language (just for exercise). I've made simple grammar
I am making a libary file with functions for extra credit for computer programming
I am making a videos website where categories will be nested: e.g. Programming-> C

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.