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); } }
- 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 - you create local variable of
int1
withinactionlistener
button. has no relationshipint1
of class. - you never tell ui update
- you break paint chain failing call
super.paint
(be ready weird , wonderful graphics glitches) - you've made same mistake
b1
haveint1
. create instance level field, shadow local variable ininit
, meaning whenstart
called,b1
null
, result innullpointerxception
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:
- understanding class members more information local , class/instance context variables
- how use labels
- why frowned upon use null layout in swing? , laying out components within container
- and if interested in how painting works, performing custom painting , painting in awt , swing
for more details
Comments
Post a Comment