java - How to hide elements with in a JComboBox? -
say have jcombobox contains elements in vector...
public class shade(){ //code creating panels etc , other components/containers jcheckbox primary = new jcheckbox("primary", false); vector<string> colours = new vector<string>(); } public shade(){ //settitle, look&feel, defaultcloseoperation, layouts etc etc... colours.add(0, "purple); colours.add(1, "red"); colours.add(2, "blue"); colours.add(3, "magenta"); jcombobox<string> colourselector = new jcombobox<string>(colours); }
if jcheckbox primary selected want 'hide' colours purple , magneta jcombobox, once primary jcheckbox has been deselected reveal hidden elements, original list pertains.
i tried doing this...
public class eventhandler implements itemlistener(){ shade refobj; public eventhandler(shade rinsefm){ refobj = rinsefm; } #overriding abstract implemented method... public void itemstatechanged(itemevent event){ if(refobj.primary.isselected() == true){ refobj.colours.hide(// index of colours required hide)) } } }
the hide method doesn't exist, there analogous this.
try this:
private jframe frame = new jframe("jcomboexample"); private jcheckbox primary = new jcheckbox("primary"); private jcombobox<string> colorselector; private string[] colorstohide = { "purple", "magenta" }; public jcomboexample() { swingutilities.invokelater(() -> { setupframe(); setupcheckbox(); initjcombobox("purple", "red", "blue", "magenta"); frame.add(primary, borderlayout.north); frame.add(colorselector, borderlayout.center); }); } private void setupframe() { frame.setsize(300, 100); frame.setlocationbyplatform(true); frame.setdefaultcloseoperation(3); frame.setlayout(new borderlayout()); } private void setupcheckbox() { primary.addactionlistener(event -> { if(primary.isselected()) { for(string color: colorstohide) { colorselector.removeitem(color); } } else { for(string color: colorstohide) { colorselector.additem(color); } } }); } private void initjcombobox(string... colors) { colorselector = new jcombobox<string>(colors); } public void setvisbility(boolean visibility) { frame.setvisible(visibility); } public static void main(string[] args) { jcomboexample example = new jcomboexample(); example.setvisbility(true); }
this class implements callback(adds actionlistener) when checkbox clicked. in callback, when checkbox activated, remove colors in array colorstohide
. if checkbox not activated, add them back.
side notes:
in java, should not using vector purpose. vectors largely considered obsolete. see post: why java vector class considered obsolete or deprecated?
you should create gui / handle gui state changes on edt. swing not thread-safe , although in cases may appear un-needed, practice call swingutilities.invokelater
or swingutilities.invokeandwait
before handling gui.
Comments
Post a Comment