Anonymous class for Event handling isnt working

my anonymous class is not working.i keep gettin an invalid method declaration. i think im either mispelling something somewhwere or missing a curly.

public SpouseGUI(){

add(new JButton("test"){

addActionListener(new ActionListener(){

publicvoid actionPerformed(ActionEvent e){

JOptionPane.showMessageDialog(null,"hi","hi",3);

}//end method

}//end action listener

);

}//end anonymous class

);

setSize(100,100);

setVisible(true);

}

//end of constructor

[1156 byte] By [dhansen@grm.neta] at [2007-10-2 9:34:06]
# 1

Yeah, you shouldn't use anonymous classes like that; that's not the purpose of anonymous classes. If you really, really, want to use an anonymous class, you will have to use a initializer block, like this:

p.add(new JButton("test") {

{ // initializer block

addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt) {

// do something

}

});

}

});

But there is absolutely no point in doing that, it's much better to just create the button and add the action listener:

JButton btn = new JButton("test");

btn.addActionListener(...);

add(btn);

happy_hippoa at 2007-7-16 23:40:21 > top of Java-index,Security,Event Handling...
# 2
thanks. i just forgot the initializer block. I wont typically use that, but it was part of this study guide for scjd/scjp to help understand anonymous classes and what not.
dhansen@grm.neta at 2007-7-16 23:40:21 > top of Java-index,Security,Event Handling...