简体   繁体   English

如何基于用户输入创建类实例

[英]How to create class instances based on user input

I have 3 instances of a class being created in another class. 我在另一个类中创建了一个类的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);

Here is the constructor if you need to see it. 如果您需要查看的话,这里是构造函数。

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;
}

The user will input one of the three usernames through a jTextField. 用户将通过jTextField输入三个用户名之一。 How do I take there input and have it choose what instance of the class will run? 我该如何输入并让它选择将运行类的哪个实例? currently I have: 目前我有:

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

But I don't know what should go into the if statement. 但是我不知道if语句应该包含什么内容。

The user will input one of the three usernames through a jTextField. 用户将通过jTextField输入三个用户名之一。 How do I take there input and have it choose what instance of the class will run? 我该如何输入并让它选择将运行类的哪个实例?

You can store all the Customer objects into a Map (Customer Name as Key and Customer object as Value) and then upon receiving the user input, retrive the respective Customer object from the Map : 您可以将所有Customer对象存储到Map (以“ Customer Name”作为键,将“ Customer Object作为“ Value”),然后在收到用户输入后,从Map检索相应的Customer对象:

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));

Now, get the user input and retrieve the Customer object using the key (customer name by entered by user): 现在,获取用户输入并使用键(由用户输入的客户名称)检索Customer对象:

String userInput = usernameInputField.getText();
Customer customer = map.get(userInput);

Don't use a Map, an ArrayList or a JTextField, but instead put the Customers into a JComboBox, and have the user select the available Customers directly. 不要使用Map,ArrayList或JTextField,而是将客户放入JComboBox,然后让用户直接选择可用的客户。 This is what I'd do since it would be more idiot proof -- because by using this, it is impossible for the user to make an invalid selection . 这是我要做的,因为这将是更愚蠢的证明-因为使用此方法, 用户不可能做出无效选择

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);

Note that for this to work well, you'd have to either override Customer's toString method and have it return the name field or else give your JComboBox a custom renderer so that it renders the name correctly. 请注意,为使此方法正常运行,您必须重写Customer的toString方法并使其返回名称字段,或者为您的JComboBox提供自定义呈现器,以使其正确呈现名称。 The tutorials will help you with this. 本教程将帮助您解决这一问题。

eg, 例如,

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;
    }

}

You can create a lookup map for all the customers. 您可以为所有客户创建查找图。 You can even extend this to add and remove customers. 您甚至可以扩展它以添加和删除客户。

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

Example

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());
    }
}

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

相关问题 使用基于用户输入的装饰器设计原则创建类的实例 - Creating instances of class using decorator design principle based on user input 如何根据用户输入重命名分散在程序中的文件路径实例? - How to rename instances of filepath scattered throughout program based on user input? 如何根据用户输入在JFrame中同时启动浏览器实例? - How to start browser instances concurrently in JFrame based on user's input? 如何根据类的注释值动态创建类的实例? - How to dynamically create instances of a class based upon their annotation value? 如何根据用户输入创建新对象? - How to create new objects based on user input? Java:如何根据用户输入的数组长度使用随机类创建char数组? - Java: How to create char arrays using Random Class Based on User Input on Length of Array? 是否可以根据用户输入创建类对象? - Is it possible to create class objects based on input from the user? 使用 Spring Boot 根据输入请求中的字段创建类链的不同实例 - Create different instances of a class chain based on a field in the input request with Spring Boot 如何创建一个类的多个实例? - how to create multiple instances of a class? 如何基于Java中的用户输入创建新的文本文件? - How to create a new text file based on the user input in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM