java - How to dynamically remove a JPanel? -


i have a gui looks follow.

enter image description here

i want dynamically add/remove panel. use arraylist keep trace of jpanel objects. , add panel dynamically, when want delete panel, not attribute can not remove it.

here code:

public class main implements actionlistener{     private list <mypanel> mplist;     private jpanel btnpanel;     private jbutton jbtadd,jbtdelete;     private jframe jf;     private jpanel jp;     private jscrollpane js;     private mypanel mp;     private static int size=0;     private int selectedid=-1;     //private     public main(){         mplist=new arraylist<mypanel>();         btnpanel=new jpanel();         jbtadd=new jbutton("addjpanel");         jbtdelete=new jbutton("deljpanel");         btnpanel.setlayout(new flowlayout(flowlayout.left,1,1));         btnpanel.add(jbtadd);         btnpanel.add(jbtdelete);         jf=new jframe("hello");         jp=new jpanel();         js=new jscrollpane(jscrollpane.vertical_scrollbar_as_needed, jscrollpane.horizontal_scrollbar_as_needed);            //jp.setlayout(new flowlayout(flowlayout.left,1,1));         jf.setlayout(new borderlayout(10,10));         jp.setlayout(new gridlayout(0,1,1,1));         jp.setpreferredsize(new dimension(500, 82*6));         for(int i=0;i<6;i++){             mypanel mp=new mypanel();             //mp.setsize(400, 82);             //mp.setbounds(0,82*i,480,82);             mp.getfiletypeiconlabel().settext(string.valueof(i));             mp.setindexid(size);             size++;             mplist.add(0,mp);             mp.addmouselistener(new mouselistener(){                 @override                 public void mouseclicked(mouseevent e) {                 // todo auto-generated method stub                     if(2==e.getclickcount()){                         system.out.println("indexind is"+mplist.get(0).getindexid());                         //system.out.println(index);                         mplist.get(0).setbackground(color.yellow);                     }                 }                  @override                 public void mouseentered(mouseevent e) {                     // todo auto-generated method stub                  }                  @override                 public void mouseexited(mouseevent e) {                     // todo auto-generated method stub                  }                  @override                 public void mousepressed(mouseevent e) {                     // todo auto-generated method stub                  }                  @override                 public void mousereleased(mouseevent e) {                     // todo auto-generated method stub                  }});             jp.add(mplist.get(0));         }         js.setviewportview(jp);         jf.setsize(600, 500);         jf.add(btnpanel,borderlayout.north);         jf.add(js);         jbtadd.addactionlistener(this);         jbtdelete.addactionlistener(this);         jf.setvisible(true);         jf.setdefaultcloseoperation(jframe.exit_on_close);      }     public static void main(string args[]){         new main();     }     @override     public void actionperformed(actionevent e) {         // todo auto-generated method stub         if(e.getsource()==jbtadd){             addmypanel();         }         else if(e.getsource()==jbtdelete){             delmypanel();         }     }     public void addmypanel(){         system.out.println("ok");         mp=new mypanel();         mp.getfiletypeiconlabel().settext(string.valueof(mplist.size()));         mp.setindexid(size);         system.out.println(size);         size++;         mplist.add(0, mp);         mp.addmouselistener(new mouselistener(){             @override             public void mouseclicked(mouseevent e) {             // todo auto-generated method stub                 if(2==e.getclickcount()){                     system.out.println("indexind is"+mplist.get(0).getindexid());                     //system.out.println(index);                     mplist.get(0).setbackground(color.yellow);                 }             }              @override             public void mouseentered(mouseevent e) {                 // todo auto-generated method stub              }              @override             public void mouseexited(mouseevent e) {                 // todo auto-generated method stub              }              @override             public void mousepressed(mouseevent e) {                 // todo auto-generated method stub              }              @override             public void mousereleased(mouseevent e) {                 // todo auto-generated method stub              }});         jp.add(mplist.get(0));         jp.setpreferredsize(new dimension(500, 82*mplist.size()));         //jp.validate();         js.validate();         //jp.repaint();         js.repaint();     }     public void delmypanel(){         selectedid=getindexofmypanelbyid();         if(selectedid>=0){             int indexid=getindexofmypanelbyid();             jp.remove(mplist.get(indexid));             mplist.remove(indexid);             jp.setpreferredsize(new dimension(500,82*mplist.size()));             jp.repaint();         }     }     protected int getindexofmypanelbyid(){         iterator<mypanel> it=mplist.iterator();         for(int id=0;it.hasnext();id++){             mypanel mp;             mp=it.next();             if(mp.isselected()){                 return id;             }         }         return -1;     } } 

here code of mypanel

class mypanel extends jpanel{     private static final long serialversionuid = 1l;     private jprogressbar downloadprogress;     private jlabel filetypeiconlabel,filenamelabel,downloadinfolabel,freelabel;     private int indexid;     private boolean isselected=false;     protected mypanel(){         setlayout(null);         downloadprogress=new jprogressbar(0,100);         filetypeiconlabel=new jlabel("test");         filenamelabel=new jlabel("filenamelabel");         downloadinfolabel=new jlabel("downloadinfolabel");         freelabel=new jlabel("freelabel");         downloadprogress.setbounds(80, 44, 400, 18);         downloadprogress.setstringpainted(true);         //downloadprogress.setstring("88%");         filetypeiconlabel.setbounds(0, 0, 80, 80);         filetypeiconlabel.setbackground(color.cyan);         filetypeiconlabel.setopaque(true);         filenamelabel.setbounds(80,0,400,22);         filenamelabel.setbackground(color.black);         filenamelabel.setopaque(true);         downloadinfolabel.setbounds(80, 22, 400, 22);         downloadinfolabel.setbackground(color.red);         downloadinfolabel.setopaque(true);         //downloadprogress.setvalue(50);         freelabel.setbounds(80, 62, 400, 18);         freelabel.setbackground(color.lightgray);         freelabel.setopaque(true);         add(downloadprogress);         add(filetypeiconlabel);         add(filenamelabel);         add(downloadinfolabel);         add(freelabel);       }     protected jlabel getfiletypeiconlabel() {         return filetypeiconlabel;     }     protected int getindexid() {         return indexid;     }     protected void setindexid(int indexid) {         this.indexid = indexid;     }     protected boolean isselected() {         return isselected;     }     protected void setselected(boolean isselected) {         this.isselected = isselected;     } } 

for many components in 1 space, use cardlayout seen in short example.

tips

jp.setpreferredsize(new dimension(500, 82*6)); 

see should avoid use of set(preferred|maximum|minimum)size methods in java swing? (yes.)

downloadprogress.setbounds(80, 44, 400, 18); 

java guis might have work on number of platforms, on different screen resolutions & using different plafs. such not conducive exact placement of components. organize components robust gui, instead use layout managers, or combinations of them1, along layout padding & borders white space2.

edit 1

as aside, screen-shot screams jlist custom renderer me. e.g.

enter image description here

import java.awt.*; import java.awt.event.actionevent; import javax.swing.*; import javax.swing.border.emptyborder;  public class dymanicdownloadlist {      // gui seen user (without frame)     jpanel gui = new jpanel(new borderlayout(2, 2));      public void initgui() {         gui.setborder(new emptyborder(2, 3, 2, 3));          jtoolbar tb = new jtoolbar();         gui.add(tb, borderlayout.page_start);          final defaultlistmodel<download> listmodel =                 new defaultlistmodel<download>();         final jlist<download> list = new jlist<download>(listmodel);         list.setcellrenderer(new downloadlistcellrenderer());         list.setvisiblerowcount(3);         gui.add(new jscrollpane(list), borderlayout.center);          action add = new abstractaction("add download") {              @override             public void actionperformed(actionevent e) {                 listmodel.addelement(new download());             }         };          action delete = new abstractaction("delete download") {              @override             public void actionperformed(actionevent e) {                 int index = list.getselectedindex();                 if (index < 0) {                     joptionpane.showmessagedialog(                             list,                             "select download delete!",                             "select download",                             joptionpane.error_message);                 } else {                     listmodel.removeelementat(index);                 }             }         };          tb.add(add);         tb.addseparator();         tb.add(delete);          (int ii = 0; ii < 2; ii++) {             listmodel.addelement(new download());         }     }      public jcomponent getgui() {         return gui;     }      public static void main(string[] args) {         runnable r = new runnable() {              @override             public void run() {                 dymanicdownloadlist ddl = new dymanicdownloadlist();                 ddl.initgui();                  jframe f = new jframe("dynamic list");                 f.add(ddl.getgui());                 // ensures jvm closes after frame(s) closed ,                 // non-daemon threads finished                 f.setdefaultcloseoperation(jframe.dispose_on_close);                 // see https://stackoverflow.com/a/7143398/418556 demo.                 f.setlocationbyplatform(true);                  // ensures frame minimum size needs                 // in order display components within                 f.pack();                 // should done last, avoid flickering, moving,                 // resizing artifacts.                 f.setvisible(true);             }         };         // swing guis should created , updated on edt         // http://docs.oracle.com/javase/tutorial/uiswing/concurrency         swingutilities.invokelater(r);     } }  class download {      download() {     } }  class downloadlistcellrenderer extends defaultlistcellrenderer {      jpanel downloadpanel = new jpanel(new borderlayout(10, 10));     jpanel labelstack = new jpanel(new gridlayout(0, 1, 2, 2));     jlabel number = new jlabel("", swingconstants.center);     jlabel source = new jlabel("file name label", swingconstants.center);     jlabel info = new jlabel("download info label", swingconstants.center);     jlabel free = new jlabel("free label", swingconstants.center);     jprogressbar progress = new jprogressbar() {         @override         public dimension getpreferredsize() {             dimension d = super.getpreferredsize();              return new dimension(400,d.height);         }     };      downloadlistcellrenderer() {         downloadpanel.add(labelstack, borderlayout.center);         labelstack.setopaque(false);         number.setfont(number.getfont().derivefont(40f));         labelstack.add(source);         labelstack.add(info);         labelstack.add(progress);         labelstack.add(free);         downloadpanel.add(labelstack, borderlayout.center);         downloadpanel.add(number, borderlayout.line_start);     }      @override     public component getlistcellrenderercomponent(             jlist list,             object value,             int index,             boolean isselected,             boolean cellhasfocus) {         jlabel l = (jlabel) super.getlistcellrenderercomponent(                 list, value, index, isselected, cellhasfocus);         downloadpanel.setbackground(l.getbackground());         number.settext("" + (index + 1));          return downloadpanel;     } } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -