Style implementation question

C

CBrand

Hello all,

I would like to implement events on the same level as the component
that is listening for them. Is there any problem with subclassing a
Component that implements its own listeners? For example:

public class Foo extends JTextField implements KeyListener {

public Foo() {

super(32);
addKeyListener(this);

}

public void keyPressed(KeyEvent e) {
//Do stuff here.
}

public void keyReleased(KeyEvent e) {
//Do stuff here.
}

public void keyTyped(KeyEvent e) {
//Do stuff here.
}

}
 
D

Daniel Pitts

CBrand said:
Hello all,

I would like to implement events on the same level as the component
that is listening for them. Is there any problem with subclassing a
Component that implements its own listeners? For example:

public class Foo extends JTextField implements KeyListener {

public Foo() {

super(32);
addKeyListener(this);

}

public void keyPressed(KeyEvent e) {
//Do stuff here.
}

public void keyReleased(KeyEvent e) {
//Do stuff here.
}

public void keyTyped(KeyEvent e) {
//Do stuff here.
}

}
There is no "problem", but it leads to bad design an unmaintainable code.

First, you should separate behavior from UI, search for the MVC pattern.
Second, you shouldn't let the "this" pointer escape until after your
constructor finishes (consider a static factory instead of constructor).
Third, it is common, and often cleaner IMO, to use Anonymous classes as
listeners/callbacks.
 
C

CBrand

Hi Daniel,

Thanks for the info. That was exactly what I was wanting to know.

- Corey



On Oct 11, 2:31 pm, Daniel Pitts

[snip]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,810
Latest member
Kassie0918

Latest Threads

Top