java - How to add different JPanel to a JFrame on a JButton click -


i add different jpanel jframe when user clicks on jbutton.

the panel must change according button clicked user. here portion of code :

addcours.addactionlistener(new actionlistener() {          @override         public void actionperformed(actionevent arg0) {             // todo auto-generated method stub             pancours.setbounds(215, 2, 480, 400);             pancours.setborder(borderfactory.createtitledborder("saisir les données concernant le cours"));             constituerdata.this.getcontentpane().add(pancours);             constituerdata.this.revalidate();             constituerdata.this.repaint();         }     });      addlocal.addactionlistener(new actionlistener() {          @override         public void actionperformed(actionevent arg0) {             // todo auto-generated method stub             panlocal.setbounds(215, 2, 480, 400);             panlocal.setborder(borderfactory.createtitledborder("saisir les données concernant le local"));             constituerdata.this.getcontentpane().add(panlocal);             constituerdata.this.revalidate();             constituerdata.this.repaint();         }     }); 

how can fix ?

first go on record in saying peeskillet's solution more elegant 1 detail , should using proper layoutmanager. cardlayout perfect particular situation.

however, if want quick hack fix current predicament can add following beginning of each of actionlisteners actionperformed() overrides.

for addcours's actionlistener add following first line;

constituerdata.this.remove(panlocal); 

for addlocal's actionlistener add following first line;

constituerdata.this.remove(pancours); 

basically, not removing last jpanel when putting new 1 in, why appears not change.

when replicated problem , solved used loop loop through frame's contents , remove jpanels first in each action listener, so;

@override public void actionperformed(actionevent e) {         for(component c : frame.getcontentpane().getcomponents()){             if(c instanceof jpanel){                 frame.remove(c);             }         }         jpanel panel = new jpanel();         panel.setbackground(color.red);         panel.setbounds(215, 2, 480, 480);         frame.add(panel);         frame.revalidate();          frame.repaint();       } 

Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -