下面的例子,第一个正确,为什么第二个错误那?

来源:百度知道 编辑:UC知道 时间:2024/07/06 17:24:41
第一个:
import java.awt.*;
import javax.swing.*;
public class Text extends JFrame{
public Text(){
Container con = getContentPane();
con.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
for(int i=1;i<=6;i++){
if(i<=3) p1.add(new JButton("The "+i));
else p2.add(new JButton("The "+i));
}
con.add(p1);
con.add(p2);
}
public static void main(String[] args){
Text text = new Text();
text.setTitle("My Frame");
text.setSize(250,150);
text.setVisible(true);
text.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
第二个:
import java.awt.*;
import javax.swing.*;
public class Text extends JFrame{
public Text(){
Container con = getContentPane();
con.setLayout(new FlowLayout(FlowLayout.LEFT));

public Text(){
Container con = getContentPane();
con.setLayout(new FlowLayout(FlowLayout.LEFT));
}
你的con是在构造函数里定义的,是局部变量,在下面都没法用的。
Container con = getContentPane(); 把这一句放到构造函数外面,作为类变量就行了。