我需要JPanel
在我正在编写的应用程序中重新实例化 a (基本上它是一个输入窗口,用户可以在其中构建图形,我希望用户能够清空它,所以使用CardLayout
不是一个选项),我正在考虑使用这样的东西:
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
}
}
问题是,当面板 p1 被重新实例化时,由于背景颜色发生变化, lbl2 没有显示,如果我只需要将面板重新实例化为空白状态,这不会那么糟糕,但我正在考虑使用这个方法也是通过装饰器模式向面板添加职责,因此我需要显示新恢复面板的组件。