02 变量的作用范围

启动NetBeans,创建一个项目,名为fanwei,类别是java,项目类型是java应用程序,不创建主类。

选择新创建好的项目,然后单击“新建文件”按钮:


打开新建文件对话框:


选择Swing GUI窗体中的JFrame窗体,单击“下一步”按钮:


设置好类名后单击完成按钮。打开窗体的属性面板,设置title属性为“变量作用范围”:


然后在窗体中添加两个标签和一个按钮,并在按钮上点击右键,选择“编辑文本”,改成“点击”如图:


按钮上右击,选择“事件”->"Mouse"->“MouseReleased”,在方法private void jButton1MouseReleased(java.awt.event.MouseEvent evt)中添加代码,然后单击“设计”按钮:


返回设计窗口,在窗体上单击右键,选择“事件”->“window”->"windowopened",添加代码,最终代码如下:

public bianliangzuoyongfanwei() {
        initComponents();
    }
    private void initComponents() {


        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();


        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("变量作用范围");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });


        jLabel1.setText("jLabel1");


        jLabel2.setText("jLabel2");


        jButton1.setText("点击");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jButton1MouseReleased(evt);
            }
        });


        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addContainerGap(316, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addComponent(jLabel1)
                .addGap(47, 47, 47)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 141, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );


        pack();
    }// </editor-fold>
    int a = 150;
    int b = 350;
    private void jButton1MouseReleased(java.awt.event.MouseEvent evt) {
        int a = 100;
        int b = 300;
        jLabel1.setText("a=" + a);
        jLabel2.setText("b=" + b);
    }


    private void formWindowOpened(java.awt.event.WindowEvent evt) {
        jLabel1.setText("a=" + a);
        jLabel2.setText("b=" + b);
    }



    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(bianliangzuoyongfanwei.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(bianliangzuoyongfanwei.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(bianliangzuoyongfanwei.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(bianliangzuoyongfanwei.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>


        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new bianliangzuoyongfanwei().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration
}

关键是红色代码部分。

然后单击工具栏中的“运行项目”按钮:


此时会要求选择主类,我们只有一个文件,选择唯一的一个文件即可。然后看到如下窗口:


我们单击“点击”按钮,变成了:


这是由于一开始在类中方法之外定义了整型数据a和b,分别为150和350,窗口启动时,触发了窗体的Windowopened事件,它调用了方法之外定义的a和b,标签的文本内容被设置为150和350;单击“点击“按钮时,触发了按钮的MouseReleased事件,此时会调用jButton1MouseReleased方法,这个方法中定义了整型数据a和b,分别为100和300。这两个变量的作用范围就在方法内,因此两个标签的文本内容被设置为100和300.这说明定义在jButton1MouseReleased方法中的数据是无法在其它方法中使用的,而定义在类中的变量可以被其它方法调用,如果方法内外同时定义了相同名称的变量,以作为范围小的为准。



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值