萌新想问问为什么会报错呢?怎么访问构造函数里的name和pass啊?

为什么会报错啊,是不能访问到构造函数里的Name和Pass吗?为什么两句代码报错的位置还不同呢?

public class Test01 extends JFrame implements ActionListener {

    public Test01(){
    //1.设置标题
    this.setTitle("登陆");        
    //2.设置在屏幕上的位置
    GraphicsEnvironment a=GraphicsEnvironment.getLocalGraphicsEnvironment();
    Rectangle rec=a.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
    double x=(rec.getWidth()-260)/2;
    double y=(rec.getHeight()-220)/2;
    this.setLocation((int)x, (int)y);
    //3.设置大小
    this.setSize(260, 220);
    //4.设置logo
    Image image=Toolkit.getDefaultToolkit().createImage("D:/图片/杂/logo.jpg");
    this.setIconImage(image);
    //5.正常退出
    this.setDefaultCloseOperation(Test01.EXIT_ON_CLOSE);
    //6.关闭最大化
    this.setResizable(false);
    //7.布局管理
    //框架默认布局 管理器 边界布局
    //添加面板 透明的容器 不能单独存在 默认布局 流式 FlowLayout
    JPanel jplMain=new JPanel();  //主面板
    this.getContentPane().add(jplMain); //用自己的面板替换框架的内容面板
    JPanel jplTop=new JPanel(); //上面版
    JPanel jplMid=new JPanel(); //中面板
    JPanel jplBot=new JPanel(); //下面版
    //将面板添加到容器中
    jplMain.add(jplTop);
    jplMain.add(jplMid);
    jplMain.add(jplBot);
    //修改面板的布局管理器为网格且3行1列
    jplMain.setLayout(new GridLayout(3,1));
    //接下来设置各个面板
    //上面版
    JLabel lblTop=new JLabel(new ImageIcon("D:/图片/杂/main.jpg"));
    jplTop.add(lblTop);
    //中面板
    JLabel lblName=new JLabel("用户名:");
    JTextField Name=new JTextField(16);
    JLabel lblPass=new JLabel("密    码:");       
    JPasswordField Pass=new JPasswordField(16);
    Name.setForeground(Color.red);
    jplMid.add(lblName);
    jplMid.add(Name);
    jplMid.add(lblPass);
    jplMid.add(Pass);
    //下面版
    JLabel lblSelect=new JLabel("请选择服务器:    ");
    JComboBox Select=new JComboBox(
            new String[]{"1","2","3","4"}
            );
    JButton Login=new JButton("登陆(L)");
    JButton Exit=new JButton("退出(X)");
    //设置热键
    Login.setMnemonic('L');
    Exit.setMnemonic('X');

}

在这两个地方报错图片说明
错误原因:1.The method getText() is undefined for the type Attributes.Name
2.Pass cannot be resolved

拜托拜托!想了好久!


哈士奇WWW
浏览 645回答 3
3回答

蝴蝶刀刀

把构造函数中定义的局部变量都变成成员变量,像这样:public class Test01 extends JFrame implements ActionListener {     JPanel jplMain;  //主面板     JPanel jplTop; //上面版     JPanel jplMid; //中面板     JPanel jplBot; //下面版     JLabel lblName;     JTextField Name;     JLabel lblPass;            JPasswordField Pass;     public Test01(){     jplMain=new JPanel();  //主面板     jplTop=new JPanel(); //上面版     jplMid=new JPanel(); //中面板     jplBot=new JPanel(); //下面版     this.getContentPane().add(jplMain); //用自己的面板替换框架的内容面板     lblName=new JLabel("用户名:");     Name=new JTextField(16);     lblPass=new JLabel("密    码:");        Pass=new JPasswordField(16);     。。。。。     } }

开满天机

成员变量定义的地方不正确,你现在都定义在Test01构造函数中,就是局部变量,其他方法中是无法访问到的。把里面所有定义的变量都挪到类外面定义,然后在构造函数中new。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java