有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我应该在哪里声明一个类中的变量以在另一个类中使用?

我有两个类,Window和CustomerInfo。Window类显示一个登录用户界面,用户将在其中的文本字段中输入有效的用户名和密码。我已经编写了正确接受正确用户名和密码并拒绝错误信息的代码。如果信息正确,CustomerInfo类将打开多个文本字段,其中包含用户信息,如姓名、地址、电话号码等。此用户信息存储在SQLite数据库中,当用户登录时,我将从该数据库中提取这些信息,并使用以前输入和保存的相应信息设置这些文本字段

如您所见,我正在使用SELECTFROM语句访问此信息。我需要包括一个WHERE子句,该子句将从输入的用户名中提取(例如,从CustInfo中选择FirstName,其中username=username)。用户名变量将是登录的用户。我试图通过字符串username=textFieldUsernameCust设置该变量。getText();我不知道在哪里声明这个变量语句,因为textFieldUsernameCust文本框在Window类中,我需要在CustomerInfo类中使用这个变量

窗口类

public class Window {

    private JFrame frame;
    public static JTextField textFieldUsernameCust;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Window window = new Window();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    Connection connection=null;
    public JPasswordField passwordFieldCust;
    public JTextField textFieldUsernameComp;
    public JPasswordField passwordFieldComp;

    /**
     * Create the application.
     */
    public Window() {
        initialize();
        connection=sqliteConnection.dbConnector();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setResizable(false);
        frame.setBounds(100, 100, 619, 377);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JLabel lblUsername = new JLabel("Username:");
        lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 14));
        lblUsername.setBounds(86, 166, 86, 14);
        frame.getContentPane().add(lblUsername);

        JLabel lblPassword = new JLabel("Password:");
        lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 14));
        lblPassword.setBounds(86, 202, 65, 14);
        frame.getContentPane().add(lblPassword);

        textFieldUsernameCust = new JTextField();
        textFieldUsernameCust.setBounds(182, 165, 97, 20);
        frame.getContentPane().add(textFieldUsernameCust);
        textFieldUsernameCust.setColumns(10);

        JButton btnLoginCust = new JButton("Login (Customer)");
        btnLoginCust.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
                    String query="select * from CustomerInfo where Username=? and Password=?";
                    PreparedStatement pst=connection.prepareStatement(query);
                    pst.setString(1, textFieldUsernameCust.getText() );
                    pst.setString(2, passwordFieldCust.getText() );

                    ResultSet rs=pst.executeQuery();
                    int count=0;
                    while(rs.next()){
                        count=count+1;
                    }
                    if (count==1)
                    {
                        JOptionPane.showMessageDialog(null, "Login Successful");
                        frame.dispose();
                        CustomerInfo custinfo=new CustomerInfo();
                        custinfo.setVisible(true);
                    }
                    else if(count>1)
                    {
                        JOptionPane.showMessageDialog(null, "Duplicate Username or Password");
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null, "Username or Password is incorrect. Please try again");
                    }

                    rs.close();
                    pst.close();

            } catch(Exception e)
                    {
                    JOptionPane.showMessageDialog(null, e);
                    }


            }
        });
        btnLoginCust.setBounds(116, 259, 117, 23);
        frame.getContentPane().add(btnLoginCust);

        JLabel lblWelcome = new JLabel("Welcome to InsurU");
        lblWelcome.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 20));
        lblWelcome.setBounds(221, 46, 232, 20);
        frame.getContentPane().add(lblWelcome);

        passwordFieldCust = new JPasswordField();
        passwordFieldCust.setBounds(182, 201, 97, 20);
        frame.getContentPane().add(passwordFieldCust);

        JLabel label = new JLabel("Username:");
        label.setFont(new Font("Tahoma", Font.PLAIN, 14));
        label.setBounds(329, 168, 86, 14);
        frame.getContentPane().add(label);

        JLabel label_1 = new JLabel("Password:");
        label_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
        label_1.setBounds(329, 204, 65, 14);
        frame.getContentPane().add(label_1);

        textFieldUsernameComp = new JTextField();
        textFieldUsernameComp.setColumns(10);
        textFieldUsernameComp.setBounds(425, 165, 97, 20);
        frame.getContentPane().add(textFieldUsernameComp);

        JButton btnLogincompanyt = new JButton("Login (Company)");
        btnLogincompanyt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
                    String query="select * from CustomerInfo where UserName=? and Password=?";
                    PreparedStatement pst=connection.prepareStatement(query);
                    pst.setString(1, textFieldUsernameComp.getText() );
                    pst.setString(2, passwordFieldComp.getText() );

                    ResultSet rs=pst.executeQuery();
                    int count=0;
                    while(rs.next()){
                        count=count+1;
                    }
                    if (count==1)
                    {
                        JOptionPane.showMessageDialog(null, "Login Successful");
                        frame.dispose();
                        CompanyInfo compinfo=new CompanyInfo();
                        compinfo.setVisible(true);
                    }
                    else if(count>1)
                    {
                        JOptionPane.showMessageDialog(null, "Duplicate Username or Password");
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null, "Username or Password is incorrect. Please try again");
                    }

                    rs.close();
                    pst.close();

            } catch(Exception e)
                    {
                    JOptionPane.showMessageDialog(null, e);
                    }
            }
        });
        btnLogincompanyt.setBounds(374, 259, 117, 23);
        frame.getContentPane().add(btnLogincompanyt);

        JLabel lblCustomerLogin = new JLabel("Customer Login");
        lblCustomerLogin.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblCustomerLogin.setBounds(116, 107, 117, 22);
        frame.getContentPane().add(lblCustomerLogin);

        JLabel lblCompanyLogin = new JLabel("Company Login");
        lblCompanyLogin.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblCompanyLogin.setBounds(374, 108, 117, 20);
        frame.getContentPane().add(lblCompanyLogin);

        passwordFieldComp = new JPasswordField();
        passwordFieldComp.setBounds(425, 201, 97, 20);
        frame.getContentPane().add(passwordFieldComp);
    }
}

CustomerInfo类

public class CustomerInfo extends JFrame {

    private JPanel contentPane;
    private JTextField textFieldFirstName;
    private JTextField textFieldLastName;
    private JTextField textFieldAdress;
    private JTextField textFieldCity;
    private JTextField textFieldZipCode;
    private JTextField textFieldEmail;
    private JTextField textFieldNumber;
    private JTextField textFieldAge;
    private JTextField textFieldUsername;
    private JTextField textFieldPassword;
    private JTextField textField_10;
    private JTextField textField_11;
    private JTextField textField_12;
    private JTextField textField_13;
    private JTextField textField_14;
    private JTextField textField_15;
    private JTextField textField_16;
    private JTextField textField_17;
    private JTextField textFieldAnnualCar1;
    private JTextField textField_19;
    private JTextField textField_20;
    private JTextField textFieldAnnualCar2;
    private JTextField textField_22;
    private JTextField textField_23;
    private JTextField textFieldAnnualCar3;
    private JTextField textFieldTotalDrivers;
    private JTextField textField_26;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CustomerInfo frame = new CustomerInfo();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public CustomerInfo() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 623, 382);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        tabbedPane.setBounds(10, 11, 593, 327);
        contentPane.add(tabbedPane);

        JPanel panel = new JPanel();
        tabbedPane.addTab("Profile", null, panel, null);
        panel.setLayout(null);

        JLabel lblFirstName = new JLabel("First Name:");
        lblFirstName.setBounds(26, 26, 65, 14);
        panel.add(lblFirstName);

        textFieldFirstName = new JTextField();
        textFieldFirstName.setBounds(92, 23, 86, 20);
        panel.add(textFieldFirstName);
        textFieldFirstName.setColumns(10);

        JLabel lblAdress = new JLabel("Adress:");
        lblAdress.setBounds(26, 51, 46, 14);
        panel.add(lblAdress);

        JLabel lblDOB = new JLabel("Date of Birth:");
        lblDOB.setBounds(26, 155, 76, 14);
        panel.add(lblDOB);

        JLabel lblRelationship = new JLabel("Relationship Status:");
        lblRelationship.setBounds(310, 186, 96, 14);
        panel.add(lblRelationship);

        JLabel lblEmail = new JLabel("E-mail:");
        lblEmail.setBounds(26, 211, 46, 14);
        panel.add(lblEmail);

        JLabel lblPhone = new JLabel("Phone Number:");
        lblPhone.setBounds(310, 211, 76, 14);
        panel.add(lblPhone);

        JLabel lblLastName = new JLabel("Last Name:");
        lblLastName.setBounds(204, 26, 65, 14);
        panel.add(lblLastName);

        textFieldLastName = new JTextField();
        textFieldLastName.setBounds(270, 23, 86, 20);
        panel.add(textFieldLastName);
        textFieldLastName.setColumns(10);

        JLabel lblCityAdress = new JLabel("City:");
        lblCityAdress.setBounds(26, 76, 46, 14);
        panel.add(lblCityAdress);

        JLabel lblStateAdress = new JLabel("State:");
        lblStateAdress.setBounds(26, 101, 46, 14);
        panel.add(lblStateAdress);

        JLabel lblZipCode = new JLabel("Zip Code:");
        lblZipCode.setBounds(26, 126, 46, 14);
        panel.add(lblZipCode);

        textFieldAdress = new JTextField();
        textFieldAdress.setBounds(92, 48, 264, 20);
        panel.add(textFieldAdress);
        textFieldAdress.setColumns(10);

        textFieldCity = new JTextField();
        textFieldCity.setBounds(92, 73, 86, 20);
        panel.add(textFieldCity);
        textFieldCity.setColumns(10);

        textFieldZipCode = new JTextField();
        textFieldZipCode.setBounds(92, 123, 86, 20);
        panel.add(textFieldZipCode);
        textFieldZipCode.setColumns(10);

        JComboBox comboBoxState = new JComboBox();
        comboBoxState.setModel(new DefaultComboBoxModel(new String[] {"Al", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"}));
        comboBoxState.setBounds(92, 98, 46, 20);
        panel.add(comboBoxState);

        JComboBox comboBoxDBMonth = new JComboBox();
        comboBoxDBMonth.setModel(new DefaultComboBoxModel(new String[] {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"}));
        comboBoxDBMonth.setBounds(92, 152, 46, 20);
        panel.add(comboBoxDBMonth);

        JComboBox comboBoxDBDay = new JComboBox();
        comboBoxDBDay.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}));
        comboBoxDBDay.setBounds(141, 152, 37, 20);
        panel.add(comboBoxDBDay);

        JComboBox comboBoxDBYear = new JComboBox();
        comboBoxDBYear.setBounds(182, 152, 65, 20);
        panel.add(comboBoxDBYear);

        textFieldEmail = new JTextField();
        textFieldEmail.setBounds(92, 208, 130, 20);
        panel.add(textFieldEmail);
        textFieldEmail.setColumns(10);


        JComboBox comboRelationshipStatus = new JComboBox();
        comboRelationshipStatus.setModel(new DefaultComboBoxModel(new String[] {"Married", "Single", "Divorced", "Widowed", "Domestic Partners"}));
        comboRelationshipStatus.setBounds(422, 183, 86, 20);
        panel.add(comboRelationshipStatus);

        textFieldNumber = new JTextField();
        textFieldNumber.setBounds(422, 208, 122, 20);
        panel.add(textFieldNumber);
        textFieldNumber.setColumns(10);

        Statement stmt = null;
        Connection connection=null;
        connection=sqliteConnection.dbConnector();
        try{
            Class.forName("org.sqlite.JDBC");
            Connection conn=DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Gregory\\workspacefinal\\Customer.sqlite");
            stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT FirstName, LastName, Adress, City, ZipCode, Email, PhoneNumber, Age FROM CustomerInfo WHERE Username = username");

                String firstName = rs.getString("FirstName");
                String lastName = rs.getString("LastName");
                String adress = rs.getString("Adress");
                String city = rs.getString("City");
                String zipcode = rs.getString("ZipCode");
                String email = rs.getString("Email");
                String phonenumber = rs.getString("PhoneNumber");
                String age = rs.getString("Age");

                textFieldFirstName.setText(firstName);
                textFieldLastName.setText(lastName);
                textFieldAdress.setText(adress);
                textFieldCity.setText(city);
                textFieldZipCode.setText(zipcode);
                textFieldEmail.setText(email);
                textFieldNumber.setText(phonenumber);
                textFieldAge.setText(age);

            stmt.close();
            conn.close();
        }
        catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
        }

共 (2) 个答案

  1. # 1 楼答案

    gui逻辑和应用程序逻辑的这种混合非常糟糕

    您的主要职能应按以下结构进行:

    1. 调用一个单独的方法,该方法执行所有必要的gui技巧来提示用户输入用户名和密码,并在一个LoginInfo类中返回它们,该类专门创建用于保存用户名和密码
    2. 如果未给出响应,(用户已取消),则终止
    3. 调用另一个单独的方法,该方法执行所有必要的gui技巧,以提示用户输入剩余信息,并在专门创建用于保存该信息的CustomerInfo类中返回该信息。(不要调用对话框CustomerInfo。该对话框应称为CustomerInfoDialog。)
    4. 如果未给出响应,(用户已取消),则终止
    5. 用这些信息更新数据库

    gui函数返回null而不是实际的LoginInfoCustomerInfo对象意味着用户已取消

  2. # 2 楼答案

    首先,CustomerInfo看起来做的比名字暗示的要多。它扩展了JFrame,这意味着它是视图的一部分。您应该在类名中反映这一点

    考虑将用户名传递给CuuthEnror的构造函数。