We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › Adding a function to a class
Page Index Toggle Pages: 1
Adding a function to a class (Read 408 times)
Adding a function to a class
Mar 6th, 2008, 8:55pm
 
I was wondering if it's possible to do the following:

I want to have an class, say just a button or something, that will have a method within it like "onClick", is it possible to set it up in a way that I could create an instance of the class, and do something like;

Code:

//terrible pseudo code//

myClass inst1 = new myClass();
myClass inst2 = new myClass();
inst1.onClick = myFunction();
inst2.onClick = myOtherFunction();

myFunction(){
do stuff
}
myOtherFunction(){
do other things
}


So that when ever the onClick function was fired for that particular instance, it would use the assigned function?

Is this a job for broadcasters and listeners? If so how do you go about doing that? does anyone know of anywhere that will explain it well?

Do I make any sense?

Thanks
Martin
Re: Adding a function to a class
Reply #1 - Mar 6th, 2008, 10:46pm
 
Hi, this isn't the way that processing work. Only the main PApplet can check for mouse events. So you need the mousePressed() methode to inform your class of the event. Take  a look at this example from the learning section: http://processing.org/learning/topics/buttons.html
Re: Adding a function to a class
Reply #2 - Mar 8th, 2008, 10:57am
 
Thanks, not quite what I was looking for, but I'm not sure how to explain it better for the time being. I'll probably post again when I know what I'm trying to say better.

Cheers
Martin
Re: Adding a function to a class
Reply #3 - Mar 8th, 2008, 12:48pm
 
Code:

class MyClass
{
void onClick () {
// nothing here by default
}
}

class MyOtherClass
extends MyClass
{
void onClick () {
println("MyOtherClass");
}
}

class YetAnotherClass
extends MyClass
{
void onClick () {
println("YetAnotherClass");
}
}

MyClass a,b,c;

void setup ()
{
a = new MyClass();
b = new MyOtherClass();
c = new YetAnotherClass();
}

void draw ()
{
a.onClick();
b.onClick();
c.onClick();
noLoop();
}



.. or have a look at interfaces.
F
Page Index Toggle Pages: 1