如何在 try/catch 之外使用变量? [英] How do I use a variable outside of a try/catch?

查看:50
本文介绍了如何在 try/catch 之外使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,用户在其中输入用户名,应用程序从数据库查询返回用户 ID.

I have an application where the user is inputting a user name and the application is returning the user ID from a database query.

我遇到的问题是如何在 userIDLbl 中显示 userID?

The problem I am having is how do I display the userID in the userIDLbl?

代码如下:

JButton currentRoleBtn = new JButton("Get ID");
    currentRoleBtn.setBounds(50, 50, 150, 30);
    currentRoleBtn.setToolTipText("Press to get the ID for the user");
    currentRoleBtn.addActionListener(new ActionListener()
    {
        public void actionPerformed (ActionEvent e)
        {
            int userID;
            String userName = adUserNameTxt.getText().toString();
            StringBuffer getRolesQuery1 = new StringBuffer("select id from hib.person where name = '");
            getRolesQuery1.append(userName).append("'");
            try 
            {
                ResultSet rs = stmt.executeQuery(getRolesQuery1.toString());
                try
                {
                    while (rs.next())
                    {
                        userID = rs.getInt(1);
                        System.out.println("The User ID is: " +userID);

                    }
                }
                finally
                {
                    rs.close();
                }
            } 

            catch (SQLException e1) 
            {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    });

    //Create UserID label
    JLabel userIDLbl = new JLabel("User ID is: " +userID);
    userIDLbl.setFont(new Font("Georgia", Font.PLAIN, 14));
    userIDLbl.setForeground(new Color(50,50, 25));
    userIDLbl.setBounds(25, 200, 200, 30);

推荐答案

将 userID 声明为类级别变量.

Declare userID as a class level variable.

所以你可以在其他任何地方使用它,你必须让它final才能在try catch块之外访问它,但是你不会 能够改变这个变量的值.

so you can use it anywhere else you'll have to make it final to access it outside the try catch block but then you won't be able to change the value of this variable.

class User  
{  
   private int userID;  

//Constructors
 public void actionPerformed (ActionEvent e)
        {  

   }
}    

这篇关于如何在 try/catch 之外使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆