java - Slider Not Updating Label -
im new swing, tried making program creates slider , label. slider moved (form 1 16), label changes. however, label doesn't updated, , instead thread exceptions , other errors when slide slider. here full code:
package edu.cuny.brooklyn.cisc3120; import java.awt.*; import javax.swing.*; import javax.swing.event.changeevent; import javax.swing.event.changelistener; import java.awt.event.*; public class gui extends jframe { private static final int limit = 4; private static final int mininteger = 1; private static final int maxinteger = 16; private static jlabel currentguess; private static jslider slider; public gui() { setlayout(new flowlayout()); jslider slider = new jslider(jslider.horizontal, mininteger, maxinteger, 1); add(slider); slider.setmajortickspacing(1); slider.setpaintlabels(true); slider.setpaintticks(true); currentguess = new jlabel("current guess: 1"); add(currentguess); sliderevent e = new sliderevent(); slider.addchangelistener(e); } public static class sliderevent implements changelistener { public void statechanged(changeevent e) { currentguess.settext("current guess: " + slider.getvalue() ); } } public static void main(string[] args) { gui guessinggame = new gui(); guessinggame.setdefaultcloseoperation(jframe.exit_on_close); guessinggame.settitle("guessing game"); guessinggame.setlocation(100, 100); guessinggame.pack(); guessinggame.setvisible(true); } }
i reiterate i'm new swing. if i'm making stupid mistake, go easy on me please.
private static jslider slider; public gui() { setlayout(new flowlayout()); jslider slider = new jslider(jslider.horizontal, mininteger, maxinteger, 1);
you defining slider twice, once instance variable (which null) , once local variable.
get rid of local variable:
//jslider slider = new jslider(jslider.horizontal, mininteger, maxinteger, 1); slider = new jslider(jslider.horizontal, mininteger, maxinteger, 1);
also, should not using static variables. indication of poor design. suggest @ section swing tutorial on how use sliders demo code show better program structure. download demo code modify requirements.
Comments
Post a Comment