java - How can I make this JButton work -


i working on code generate random number when press button , output number. have wrote code , compiles when press button nothing works. can please help. here of code.

public class slotmachine extends japplet {      jbutton b1 = new jbutton("start");     jpanel p;     int int1;      public slotmachine() {         init();      }      public void init() {          this.setlayout(null);         this.setsize(1000, 1000);          jbutton b1 = new jbutton("start");         b1.setbounds(100, 100, 100, 100);          getcontentpane().add(b1);         repaint();      }      public void run() {         b1.addactionlistener(new actionlistener() {              public void actionperformed(actionevent e) {                 random random1 = new random();                 int int1 = random1.nextint(11);              }          });     }      public void paint(graphics g) {          g.drawstring("your number is" + int1, 30, 30);      } } 

  1. avoid using null layouts, pixel perfect layouts illusion within modern ui design. there many factors affect individual size of components, none of can control. swing designed work layout managers @ core, discarding these lead no end of issues , problems spend more , more time trying rectify
  2. you create local variable of int1 within actionlistener button. has no relationship int1 of class.
  3. you never tell ui update
  4. you break paint chain failing call super.paint (be ready weird , wonderful graphics glitches)
  5. you've made same mistake b1 have int1. create instance level field, shadow local variable in init, meaning when start called, b1 null, result in nullpointerxception

instead, add jlabel applet, use it's settext method display random value

b1.addactionlistener(new actionlistener() {      public void actionperformed(actionevent e) {         random random1 = new random();         int int1 = random1.nextint(11);         lable.settext(integer.tostring(int1));     }  }); 

also, if possible, i'd avoid using japplet, have own set of issues can make life more difficult needs when learning swing api. instead, try using jpanel main container , add instance of jframe.

also, take at:

for more details


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -