Java JTextField 在内部类的方法调用中不起作用

标签 java string swing compare jtextfield

我正在构建一个 GUI 并尝试实现一个非常简单的搜索 - 当您输入 SSN 时,它会检查是否有客户使用该 SSN。我有一个 JTextField,其中输入了 SSN,当您单击提交时,它会调用 searchBySSNString 方法并返回 true 或 false。问题是,每当我从 JTextField 中提取文本时,它都会返回 false。

为了这个问题,我试图将其归结为尽可能少的代码,这样别人就不必费力地阅读我的所有代码。我在问题部分包含了额外的代码,以显示我一直在努力完成的工作。如果我硬编码一个字符串并搜索它,它返回 true,如果我将该硬编码字符串与 JTextField 中的文本进行比较,如果输入相同的文本,它返回 0。

一些杂项说明:我将 SSN 用作字符串,因为我认为我永远不需要像处理数字一样处理它。如果这是个坏主意,我想知道为什么。创建的帐户的 SSN 是 222222222。我还没有实现任何验证输入或考虑破折号或任何东西的方法。

正如您将看到的,如果您真的费力地阅读我的代码,我是初学者,所以我总是愿意听取任何人的任何提示,但现在紧迫的问题是弄清楚为什么输入JTextField 在搜索中不起作用。

import java.util.ArrayList;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextPane;

public class Bank {

    private JFrame frame;
    private JTextField txtSearchBySSN;
    private JTextField txtTestMessage;
    static ConnectionFactory connectionFactory = ConnectionFactory.getConnectionFactory();

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        connectionFactory.newAccountAndCustomer("Mike", "222222222");

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Bank window = new Bank();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Bank() {
        initialize();
    }

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

        JLabel lblSearchBySSN = new JLabel("Search for customer by SSN");
        lblSearchBySSN.setBounds(6, 38, 190, 16);
        frame.getContentPane().add(lblSearchBySSN);

        txtSearchBySSN = new JTextField();
        txtSearchBySSN.setBounds(208, 32, 134, 28);
        frame.getContentPane().add(txtSearchBySSN);
        txtSearchBySSN.setColumns(10);

        //here's the problem portion
        JButton btnSearchBySSN = new JButton("Search");
        btnSearchBySSN.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //get text from the textbox
                String testString = txtSearchBySSN.getText();
                //print out the text from the textbox to see if it looks the same
                System.out.println(testString);
                //call the search method using the string from the textbox
                System.out.println(connectionFactory.searchBySSNString(testString));
                //call the search method using two hard-coded string to see if the method works
                //one that does match and one that doesnt
                System.out.println(connectionFactory.searchBySSNString("222222222"));
                System.out.println(connectionFactory.searchBySSNString("333333333"));
                //compare the text from the textbox to a hard-coded string - this returns 0
                System.out.println(testString.compareTo("222222222"));
            }
        });
        btnSearchBySSN.setBounds(355, 33, 117, 29);
        frame.getContentPane().add(btnSearchBySSN);

        txtTestMessage = new JTextField();
        txtTestMessage.setBounds(117, 83, 134, 28);
        frame.getContentPane().add(txtTestMessage);
        txtTestMessage.setColumns(10);
    }
}

class ConnectionFactory {
    private ArrayList<Customer> customers;
    private ArrayList<Account> accounts;
    private ArrayList<Connection> connections;
    private static ConnectionFactory connectionFactory;

    private ConnectionFactory() {
        customers = new ArrayList<Customer>();
        accounts = new ArrayList<Account>();
        connections = new ArrayList<Connection>();
    }

    //creates a ConnectionFactory if one doesn't already exist
    public static ConnectionFactory getConnectionFactory() {
        if (connectionFactory == null) {
            connectionFactory = new ConnectionFactory();
        }
        return connectionFactory;
    }

    //create new account and new customer
    public void newAccountAndCustomer(String customerName, String ssn) {
        Customer customer = new Customer(customerName, ssn);
        Account account = new CheckingAccount();

        //create the connection object, add all of the items to their respective arrays
        Connection connection = new Connection(customer, account);
        customers.add(customer);
        accounts.add(account);
        connections.add(connection);
    }

    //check to see if customer exists
    public String searchBySSNString(String ssn) {
        boolean customerExists = false;

        for(int i = 0; i < customers.size(); i++) {
            if(customers.get(i).getSSN() == ssn) {
                customerExists = true;
                break;
            }
        }
        if (customerExists) {
            return "true";
        }
        else {
            return "false";
        }
    }
}

abstract class Account {
    private long accountNumber;
    private double currentBalance;

    protected Account() {
        //
    }

    protected Account(double currentBalance) {
        this.currentBalance = currentBalance;
    }

    public void withdraw(double withdrawalAmount) {
        currentBalance -= withdrawalAmount;
    }

    public void deposit(double depositAmount) {
        currentBalance += depositAmount;
    }

    public double getCurrentBalance() {
        return currentBalance;
    }

    public void setCurrentBalance(double newBalance) {
        this.currentBalance = newBalance;
    }

    public long getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(long accountNumber) {
        this.accountNumber = accountNumber;
    }
}

class CheckingAccount extends Account {
    private double overdraftAmount;
    private static long nextAccountNumber = 10000000;
    private long accountNumber;

    public CheckingAccount() {
        accountNumber = nextAccountNumber;
        nextAccountNumber++;
    }

    public void setOverdraftAmount(double overdraftAmount) {
        this.overdraftAmount = overdraftAmount;
    }

    public double getOverdraftAmount() {
        return overdraftAmount;
    }

    public long getAccountNumber() {
        return accountNumber;
    }

    @Override
    public String toString() {
        return String.valueOf(accountNumber);
    }
}

class Connection {
    private Customer customer;
    private Account account;

    public Connection(Customer customer, Account account) {
        this.customer = customer;
        this.account = account;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setAccount(Account account) {
        this.account = account;
    }

    public Account getAccount() {
        return account;
    }   
}

class Customer {
    private String name;
    private String ssn;

    public Customer(String name, String ssn) {
        this.name = name;
        this.ssn = ssn;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setSSN(String ssn) {
        this.ssn = ssn;
    }

    public String getSSN() {
        return ssn;
    }

    @Override
    public String toString() {
        return name;
    }
}

最佳答案

其实我并没有阅读你所有的代码,但是你在 Java 中比较对象之间的观察相等性的方式是使用 equals 方法,== 只是引用相等性.所以

改变:

if(customers.get(i).getSSN() == ssn)

if(customers.get(i).getSSN().equals(ssn))

也不要使用null 布局。 Swing 旨在与布局管理器一起使用。

阅读更多:

How do i compare strings in java

Using layout managers

关于Java JTextField 在内部类的方法调用中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20318736/

相关文章:

java - java中的简单加密

python - 正则表达式数字之间的整个字符串匹配

c++ - 如何在一行上连接多个 C++ 字符串?

java - JComboBox 确定项目是否在下拉列表中可见

java - 如何在 Windows 10 的 ejdk 中使用 jrecreate 创建非常小的 JRE?

java - 使用模拟方法参数来模拟后续步骤

java - 模态无父 JDialog 不抢焦点

Java Swing 应用程序导致 ClassNotFoundException

java - 如何通过xml签名文件提取 "original"内容

Python从字符串中删除多个字符串的最佳方法