wEEdpEckEr <toch_lekker_nie@geen_email.aub> scribbled the following:
> Hi,
> I was wondering if it is possible to pass on a function as parameter.
> Because I have a class that extends a thread and uses a socket, and
> listens constantly to this socket. Now when something passes over the
> connection, the output needs to be displayed in a JTextArea. So what I
> would like to do is:
> public void displayOutput(String msg)
> {
> outputBox.append(msg);
> }
> and when initializing the thread:
> server = new Server(this.displayOutput());
> only I have no idea what I would have to in the constructor of the
> Serverclass nor how to call the function from within the server class. I
> know it's possible in C++, but about Java I'm not sure.
> Thanx if anyone knows the answer to this.
You can't pass methods as arguments in Java. It would be possible to
add this functionality to Java, but it wouldn't be exactly trivial.
You can fake this by using Reflection, but that would be a hack. A
better way is to rethink your design.
If I were you, I would make an interface something like this:
public interface ServerCallback {
public void callback(String arg);
}
and then an implementation of it like this:
public class MainThread extends Thread implements ServerCallback {
/* the code in your thread class defined above goes here */
public void callback(String arg) {
displayOutput(arg);
}
}
and then just call this from your MainThread class:
server = new Server(this);
where the Server constructor expects a ServerCallback.
--
/-- Joona Palaste () ------------- Finland --------\
\--
http://www.helsinki.fi/~palaste --------------------- rules! --------/
"Products like that make me wish I could menstruate."
- Andy Richter