java - Adding an ActionListener to a JButton from another class is giving a NullPointerException? -
i want able add acitonlistener jbutton class keep code neat. problem brings nullpointerexception when trying add it.
i'm adding actionlistener through handler class defined 'h'.
in display class:
public class display { private handler h; //my handler object private jframe frame; private jbutton btncalculate; /** * launch application. */ public static void createdisplay() { eventqueue.invokelater(new runnable() { public void run() { try { display window = new display(); window.frame.setvisible(true); } catch (exception e) { e.printstacktrace(); } } }); } /** * create application. */ public display() { initialize(); } /** * initialize contents of frame. */ private void initialize() { frame = new jframe(); frame.setbounds(100, 100, 450, 300); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.getcontentpane().setlayout(null); btncalculate = new jbutton("calculate"); btncalculate.setbounds(66, 208, 89, 23); btncalculate.addactionlistener(h.getcalculatelistener()); //actionlistener added here. frame.add(btncalculate); } //getter jbutton public jbutton getbtncalculate() { return btncalculate; } }
here's handler class includes getters. helps make lot more simple having getters in handler class instead of having them spread out in multiple different classes:
public class handler { private display display; //my display object private calculateactionlistener calculate; //my calculateactionlistener object public handler(display display, calculateactionlistener calculate) { this.display = display; this.calculate = calculate; } public jbutton getbutton() { return display.getbtncalculate(); } public actionlistener getcalculatelistener() { return calculate.getcalculatelistener(); } }
and finally, here's calculateactionlistener class contains actual actionlistener:
public class calculateactionlistener { //here's actual actionlistener private actionlistener calculatelistener = new actionlistener() { public void actionperformed(actionevent e) { joptionpane.showmessagedialog(null, "working!"); } }; //getter actionlistener public actionlistener getcalculatelistener() { return calculatelistener; } }
note imports removed there in code. imports not problem.
you not creating new instance of handler
. before use h
, need create instance of it. add line before create button in display class constructor. this:
h = new handler(this, new calculateactionlistener());
Comments
Post a Comment