java - Show JLabel on JButton click -


i want see jlabel when show jbutton clicked, doesn't work!

public class d5 extends jframe implements actionlistener {      jbutton showbutton;     static jlabel[] lbl;     jpanel panel;      public d5() {          showbutton = new jbutton("show");         showbutton.addactionlistener(this);         add(showbutton, borderlayout.page_start);         setdefaultcloseoperation(jframe.exit_on_close);         setsize(400, 500);         setlocation(300, 30);         setvisible(true);     }      public jpanel mypanel() {         panel = new jpanel(new flowlayout(flowlayout.left));         lbl = recordslabel();         (jlabel jlabel : lbl) {             panel.add(jlabel);         }         return panel;     }      public static void main(string[] args) {         new d5();     }      @override     public void actionperformed(actionevent e) {         if (e.getsource() == showbutton) {             add(mypanel(), borderlayout.page_start);             setvisible(true);             system.out.println("show button clicked");         }     }      public jlabel[] recordslabel() {         arraylist<string> lablelist = new arraylist<>();         lablelist.add("one");         lablelist.add("two");         lablelist.add("three");         object[] arrayresultrow = lablelist.toarray();          int rows = 3;          lbl = new jlabel[rows];         (int = 0; < rows; i++) {             lbl[i] = new jlabel(arrayresultrow[i].tostring());         }         return lbl;     } } 

as @nicecow comment you've add(showbutton, borderlayout.page_start); in same location panel. 1 component can add @ same location.

also not bad call validate.

@override public void actionperformed(actionevent e) {     if (e.getsource() == showbutton) {         add(mypanel(), borderlayout.page_start); // set position or remove previous component here         validate();          system.out.println("show button clicked");      } } 

by way don't recommend implementing actionlistener in jframe class, don't need extend jframe

public class d5 {   private jframe frame;  . . // part in constrcutor .   showbutton.addactionlistener(new actionlistener(){         @override           public void actionperformed(actionevent evt){               frame.add(mypanel(),borderlayout.page_start);               frame.validate();          }   }) } 

Comments