Question

I need to reinstantiate a JPanel in an application I'm writing (basically it's an input window where the user can build a graph, and I'd like the user to be able to empty it, so using CardLayout is not an option), and I was thinking of using something like this:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class AppletProve extends JPanel implements MouseListener, MouseMotionListener{

private JPanel p1;
public AppletProve(){
    super();
    setLayout(null);
    Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
    dim.width=(int) (dim.width*0.66);
    dim.height=(int) (dim.height*0.75);
    setPreferredSize(dim);
    addMouseListener(this);
}
public void crea(){
    p1=new JPanel();
    p1.setBounds(10,10,60,70);
    p1.setBackground(Color.YELLOW);
    JLabel lbl1=new JLabel("prova1");
    p1.add(lbl1);
    add(p1);
}
public void collega(){
    remove(p1);
    p1=new JPanel();
    p1.setBounds(10,10,60,70);
    p1.setBackground(Color.BLUE);
    JLabel lbl2=new JLabel("prova2");
    p1.add(lbl2);
    add(p1);
}
@Override
public void mouseClicked(MouseEvent arg0) {
    System.out.println("chiamato");
    collega();

}
@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void mouseDragged(MouseEvent arg0) {
    repaint();

}
@Override
public void mouseMoved(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
}

The problem is that while the panel p1 is reinstantiated, since the background color changes, lbl2 isn't shown, which wouldn't be that bad if I only had to reinstantiate the panel to a blank state, but I was thinking of using this method also for adding responsibilities to the panel through the decorator pattern, so I need to show the components of the new reinstatiated panel.

Was it helpful?

Solution

I'd like the user to be able to empty it, so using CardLayout is not an option

Sure it is. See, CardLayout.removeLayoutComponent(Component).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top