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
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);