java - JButton ActionListener not responding -
i couldn't find answer anywhere else online, came here. apologize in advance if mistake in code obvious; i'm still quite new java swing. here's what's going on: have created jbutton named toggleelevators
, , want change text when clicked. have created actionlistener , added toggleelevators
. want right jbutton change text when clicked click me
clicked
.
first, here's picture of jframe looks when executed:
note: there third class, purely drawing picture on left. has nothing gridlayout or jbutton.
run
class (created frame , adds toggleelevators
jbutton:
import java.awt.color; import java.awt.eventqueue; import java.awt.gridlayout; import javax.swing.jframe; public class run extends input{ input = new input(); public static void main(string[] args) { new run(); } public run() { eventqueue.invokelater(new runnable() { @override public void run() { jframe frame = new jframe("elevators"); frame.setlayout(new gridlayout(0, 3)); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.add(new elevators(color.magenta, true)); frame.add(new elevators(color.orange, false)); frame.setsize(800,600); frame.setresizable(false); frame.getcontentpane().add(toggleelevators); //adds toggleelevators button jframe i.addbuttonlisteners(); //calls method defined in input class, adds actionlistener toggleelevators button frame.setlocationrelativeto(null); frame.setvisible(true); } }); } }
input
class (creates toggleelevators
jbutton , actionlistener):
import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jbutton; public class input { jbutton toggleelevators = new jbutton("click me."); public void addbuttonlisteners() { toggleelevators.addactionlistener(new toggleelevatorslistener()); } class toggleelevatorslistener implements actionlistener { public void actionperformed (actionevent event) { toggleelevators.settext("clicked."); system.out.println("actionlistener called."); //i know actionlistener not being called because line not being printed out in console } } }
your run class extends input, has input named i
. you're adding this.toggleelevators
frame, you're adding listener i.toggleelevators
.
remove i
field class. forget defining , extending input class. doesn't serve purpose, , seems confuse more you.
Comments
Post a Comment