简体   繁体   中英

How to create class instances based on user input

I have 3 instances of a class being created in another class.

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. 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.

The user will input one of the three usernames through a 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 :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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