初始化JPanel时遇到问题。这是我的代码:`
JPanel canvas = new JPanel();
JPanel can = canvas;
System.out.println("COMPONENTS 1 :" + canvas.getComponentCount());
System.out.println("COMPONENTS 1 :" + can.getComponentCount());
JTextField txt = new JTextField();
txt.setBounds(100, 100, 200, 30);
can.add(txt);
System.out.println("COMPONENTS 2 :" + canvas.getComponentCount());
System.out.println("COMPONENTS 2 :" + can.getComponentCount());
`
输出是:
COMPONENTS 1 :0
COMPONENTS 1 :0
COMPONENTS 2 :1
COMPONENTS 2 :1
我想要的是什么:
COMPONENTS 1 :0
COMPONENTS 1 :0
COMPONENTS 2 :0
COMPONENTS 2 :1
答案 0 :(得分:2)
用线
JPanel可以=画布;
您没有创建新的JPanel对象。你正在制作can,指向画布指向的同一个JPanel对象。 Canvas只是指向JPanel内存地址的指针。实际上,can和canvas是完全相同的JPanel。如果您希望能够独立修改它们,则需要创建新的JPanel实例。