java - How to add mouselisteners outside the constructor -


in example below, both button , button2 supposed become unclickable when press them. when press reset button, 2 disabled buttons supposed work again.

since made 2 buttons unclickable removing mouselisteners, how add mouselisteners using check() method still function in same way again?

public static boolean isreset = false; public static jbutton button = new jbutton("disable button 1"); public static jbutton button2 = new jbutton("disable button 2"); public static jbutton reset = new jbutton("reset buttons");  test() {     settitle("button test");     setsize(420, 80);     setlocationrelativeto(null);     setdefaultcloseoperation(jframe.exit_on_close);      jpanel buttons = new jpanel(new gridbaglayout());     gridbagconstraints gc = new gridbagconstraints();     gc.fill = gridbagconstraints.both;     gc.gridheight = 1;     gc.gridwidth = 1;      gc.gridx = 0;     gc.gridy = 0;     buttons.add(button, gc);      gc.gridx = 1;     gc.gridy = 0;     buttons.add(button2, gc);      gc.gridx = 3;     gc.gridy = 0;     buttons.add(reset, gc);      add(buttons);      button.addmouselistener(new mouse(){         public void mousepressed(mouseevent e){             button.setenabled(false);             button.removemouselistener(this);             system.out.println("you pressed button 1.");             isreset = false;             check(isreset);         }     });      button2.addmouselistener(new mouse(){         public void mousepressed(mouseevent e){             button2.setenabled(false);             button2.removemouselistener(this);             system.out.println("you pressed button 2.");             isreset = false;             check(isreset);         }     });      reset.addmouselistener(new mouse(){         public void mousepressed(mouseevent e){             isreset = true;             check(isreset);         }     });      setvisible(true); }  public static void check (boolean input){     if(input == true){         test.button.setenabled(true);         test.button.addmouselistener(this); //error here         test.button2.setenabled(true);         test.button2.addmouselistener(this); //error here     } }    

everything in code static. that's not how write jframe subclass. suggest read sample code first.

you don't have remove mouse listeners each time. calling setenabled enough.

also, should call addactionlistener instead of addmouselistener.

example:

button.addactionlistener(new actionlistener(){     public void actionperformed(actionevent e){         button.setenabled(false);         system.out.println("you pressed button 1.");         isreset = false;         check(isreset);     } }); 

Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -