如何根据用户输入创建类实例

时间:2016-12-05 23:47:35

标签: java swing class instance

我在另一个类中创建了3个类的实例。

Customer kyle = new Customer(true,false,false,"Kyle",1000.00);
Customer andrew = new Customer(false,true,false,"Andrew",0.00);
Customer connor = new Customer(false,false,true,"Connor",5000.00);

如果你需要看它,这是构造函数。

public Customer(boolean regular, boolean payAhead, boolean loyal, String userName, double amountOfStorage) {
    this.regular = regular;
    this.payAhead = payAhead;
    this.loyal = loyal;
    this.userName = userName;
    this.amtOfStore = amountOfStorage;
}

用户将通过jTextField输入三个用户名之一。我如何获取输入并让它选择将运行该类的实例?目前我有:

if (usernameInputField.getText().equals(kyle.getUserName())
            || usernameInputField.getText().equals(andrew.getUserName())
            || usernameInputField.getText().equals(connor.getUserName())){
}

但我不知道应该在if声明中加入什么。

3 个答案:

答案 0 :(得分:4)

  

用户将通过jTextField输入三个用户名之一。   我如何接受输入并让它选择什么实例   上课会跑?

您可以将所有Customer个对象存储到Map(客户名称为密钥,Customer对象作为值),然后在收到用户输入后,检索相应的{{1来自Customer

的对象
Map

现在,获取用户输入并使用密钥检索Map<String, Customer> map = new HashMap<>(); map.add("Kyle", new Customer(true,false,false,"Kyle",1000.00)); map.add("Andrew", new Customer(false,true,false,"Andrew",0.00)); map.add("Connor", new Customer(false,false,true,"Connor",5000.00)); 对象(用户输入的客户名称):

Customer

答案 1 :(得分:2)

不要使用Map,ArrayList或JTextField,而是将Customers放入JComboBox,并让用户直接选择可用的Customers。这就是我要做的事情,因为它会更加白痴 - 因为使用它,用户无法进行无效选择

DefaultComboBoxModel<Customer> custComboModel = new DefaultComboBoxModel<>();
custComboModel.addElement(new Customer(true,false,false,"Kyle",1000.00));
custComboModel.addElement(new Customer(false,true,false,"Andrew",0.00));
custComboModel.addElement(new Customer(false,false,true,"Connor",5000.00));

JComboBox<Customer> custCombo = new JComboBox<>(custComboModel);

请注意,要使其正常工作,您必须覆盖Customer的toString方法并让它返回name字段,否则为JComboBox提供自定义渲染器,以便正确呈现名称。这些教程将为您提供帮助。

如,

import javax.swing.*;

@SuppressWarnings("serial")
public class SelectCustomer extends JPanel {
    private DefaultComboBoxModel<SimpleCustomer> custComboModel = new DefaultComboBoxModel<>();
    private JComboBox<SimpleCustomer> custCombo = new JComboBox<>(custComboModel);
    private JTextField nameField = new JTextField(10);
    private JTextField loyalField = new JTextField(10);
    private JTextField storageField = new JTextField(10);

    public SelectCustomer() {
        custComboModel.addElement(new SimpleCustomer("Kyle", true, 1000.00));
        custComboModel.addElement(new SimpleCustomer("Andrew", false, 0.00));
        custComboModel.addElement(new SimpleCustomer("Connor", false, 5000.00));
        custCombo.setSelectedIndex(-1);
        custCombo.addActionListener(e -> {
            SimpleCustomer cust = (SimpleCustomer) custCombo.getSelectedItem();
            nameField.setText(cust.getUserName());
            loyalField.setText("" + cust.isLoyal());
            storageField.setText(String.format("%.2f", cust.getAmtOfStore()));
        });


        add(custCombo);
        add(new JLabel("Name:"));
        add(nameField);
        add(new JLabel("Loyal:"));
        add(loyalField);
        add(new JLabel("Storage:"));
        add(storageField);
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("SelectCustomer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new SelectCustomer());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

public class SimpleCustomer {
    private String userName;
    private boolean loyal;
    private double amtOfStore;

    public SimpleCustomer(String userName, boolean loyal, double amtOfStore) {
        this.userName = userName;
        this.loyal = loyal;
        this.amtOfStore = amtOfStore;
    }

    public String getUserName() {
        return userName;
    }

    public boolean isLoyal() {
        return loyal;
    }

    public double getAmtOfStore() {
        return amtOfStore;
    }

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

}

答案 2 :(得分:1)

您可以为所有客户创建查找地图。您甚至可以对此进行扩展以添加和删除客户。

String username = textField.getText().toLowerCase();
if (customerMap.containsKey(username)) {
    output.setText(customerMap.get(username).toString());
} else {
    output.setText("Not found!");
}

实施例

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class App implements Runnable {
    private static class Customer {
        private String userName;
        private boolean regular;
        private boolean payAhead;
        private boolean loyal;
        private double amountOfStorage;

        public Customer(String userName, boolean regular, boolean payAhead, boolean loyal, double amountOfStorage) {
            this.userName = userName;
            this.regular = regular;
            this.payAhead = payAhead;
            this.loyal = loyal;
            this.amountOfStorage = amountOfStorage;
        }

        @Override
        public String toString() {
            return String.format("{ userName: %s, regular: %s, payAhead: %s, loyal: %s, amountOfStorage: %s }",
                    userName, regular, payAhead, loyal, amountOfStorage);
        }
    }

    private static class MainPanel extends JPanel {
        private static final long serialVersionUID = -1911007418116659180L;

        private static Map<String, Customer> customerMap;

        static {
            customerMap = new HashMap<String, Customer>();
            customerMap.put("kyle", new Customer("Kyle", true, false, false, 1000.00));
            customerMap.put("andrew", new Customer("Andrew", false, true, false, 0.00));
            customerMap.put("connor", new Customer("Connor", false, false, true, 5000.00));
        }

        public MainPanel() {
            super(new GridBagLayout());

            JTextField textField = new JTextField("", 16);
            JButton button = new JButton("Check");
            JTextArea output = new JTextArea(5, 16);

            button.addActionListener(new AbstractAction() {
                private static final long serialVersionUID = -2374104066752886240L;

                @Override
                public void actionPerformed(ActionEvent e) {
                    String username = textField.getText().toLowerCase();

                    if (customerMap.containsKey(username)) {
                        output.setText(customerMap.get(username).toString());
                    } else {
                        output.setText("Not found!");
                    }
                }
            });
            output.setLineWrap(true);

            addComponent(this, textField, 0, 0, 1, 1);
            addComponent(this, button, 1, 0, 1, 1);
            addComponent(this, output, 0, 1, 1, 2);
        }
    }

    protected static void addComponent(Container container, JComponent component, int x, int y, int cols, int rows) {
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.gridx = x;
        constraints.gridy = y;
        constraints.gridwidth = cols;
        constraints.gridwidth = rows;
        container.add(component, constraints);
    }

    @Override
    public void run() {
        JFrame frame = new JFrame();
        MainPanel panel = new MainPanel();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new App());
    }
}