1.
add( new DynamicPanel1().getD1());
Calling the "getD1()" is redundant here because when you say new DynamicPanel1, you are creating a DynamicPanel1 Object. The getD1() method returns a DynamicPanel1 Object, so you see, you already did that anyway.
2.
"got the removing.. but my main problem is how to add my panel 1 to the main frame if click the button from panel 2?"
Think the problem out a little more thoroughly: You have three Objects - your main frame, your panel 1, and your panel 2. What you want to do is add panel 1 to the main frame from within panel 2's class. So if your panel 2 constructor takes two arguments: the main frame and the panel 1, then you can accomplish this. For example:
public class DynamicFrame extends JFrame{
public DynamicFrame(){
public void actionPerformed(ActionEvent e){
add(new DynamicPanel1(this));
}
}
....
public class DynamicPanel1 extends JPanel{
DynamicFrame myFrame = null;
public DynamicPanel1(DynamicFrame frame){
myFrame = frame;
public void actionPerformed(ActionEvent e){
//Is this where you want to create your DynamicPanel2?
//I noticed you never created one... I'll show you how you'd
//create it though:
new DynamicPanel2(myFrame, this);
}
}
....
public class DynamicPanel2 extends JPanel{
DynamicFrame myFrame;
DynamicPanel1 myPanel1;
public DynamicPanel2(DynamicFrame frame, DynamicPanel1 panel1){
myFrame = frame;
myPanel1 = panel1;
}
public void actionPerformed(ActionEvent e){
myFrame.add(myPanel1);
}
It seems like you're making a legitimate effort to learn, so in this case, I think it is best to see how it is done so that you will understand in the future. But please note that you will not usually be given code on Daniweb, even if it is a few lines.... this is just one of those cases where "letting you figure it out on your own" isn't really advantageous.