简体   繁体   English

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

[英]Java JTextField won't work in method call from inner class

I'm building a GUI and am trying to implement a very simple search - when you input a SSN, it checks to see if there's a customer with that SSN. 我正在构建一个GUI并尝试实现一个非常简单的搜索 - 当您输入SSN时,它会检查是否有客户使用该SSN。 I have a JTextField where the SSN is entered, and when you click submit, it calls the searchBySSNString method and returns true or false. 我有一个输入SSN的JTextField,当你单击submit时,它会调用searchBySSNString方法并返回true或false。 The problem is, whenever I pull text from the JTextField, it returns false. 问题是,每当我从JTextField中提取文本时,它都会返回false。

For the sake of this question, I've tried to boil this down to as little code as I reasonably can so someone doesn't have to wade through all of my code. 为了这个问题,我试图将其归结为尽可能少的代码,因此有人不必涉及我的所有代码。 I have extra code included in the problem portion to show what I've been working through. 我在问题部分中包含了额外的代码,以显示我一直在做的工作。 If I hard code a string in and search for it, it returns true, and if I compare that hard coded string to the text from the JTextField, it returns 0 if the same text is typed in. 如果我对字符串进行硬编码并搜索它,则返回true,如果我将该硬编码字符串与JTextField中的文本进行比较,则在输入相同的文本时返回0。

A few miscellaneous notes: I use SSN as a string because I don't think I'll ever need to manipulate it like it's a number. 一些杂项说明:我使用SSN作为字符串,因为我不认为我需要操纵它,就像它是一个数字。 If that's a bad idea, I'd like to know why. 如果那是个坏主意,我想知道原因。 The SSN on the account created is 222222222. I don't have anything implemented to validate the input or to account for dashes or anything yet. 创建的帐户上的SSN是222222222.我没有任何实现来验证输入或用于破折号或任何其他内容。

As you'll see if you actually slog through my code, I'm quite the beginner, so I'm always willing to listen to any tips anyone has, but the pressing problem now is figuring out why the input from the JTextField will not work in the search. 正如你会看到你是否真的在我的代码中跋涉,我是初学者,所以我总是愿意倾听任何人提出的任何提示,但现在迫在眉睫的问题是弄清楚为什么来自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;
    }
}
if(customers.get(i).getSSN() == ssn)

Problem is in this line. 问题出在这一行。 Use equals() method for string comparison instead of ==. 使用equals()方法进行字符串比较而不是==。

If you use == to compare strings, it will return true if both String objects' locations in memory are same. 如果使用==来比较字符串,如果两个String对象在内存中的位置相同,它将返回true。 But equals() method will check values of those String objects. 但是equals()方法将检查那些String对象的值。 So changing above line with 因此改变上面的线

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

will fix your problem. 将解决您的问题。

Actually i don't read all of your code, but the way you compare observational equality between objects in Java is with equals method, == is just reference equality. 实际上我并没有阅读你的所有代码,但是你比较Java中对象之间的观察相等性的方法是使用equals方法, ==只是引用相等。 So 所以

Change: 更改:

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

to

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

Also don't use null layout. 也不要使用null布局。 Swing was designed to use with Layout Managers. Swing旨在与布局管理器一起使用。

Read more in: 阅读更多:

How do i compare strings in java 我如何比较java中的字符串

Using layout managers 使用布局管理器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM