【问题标题】:How to create class instances based on user input如何根据用户输入创建类实例
【发布时间】:2016-12-05 23:47:35
【问题描述】:

我在另一个类中创建了一个类的 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 语句应该包含什么内容。

【问题讨论】:

  • 我们也不知道。这就是编程的问题——在尝试之前你需要知道你想做什么。我们应该怎么知道?
  • 如果用户名很重要(有点像键...),请将其作为第一个参数。

标签: java swing class instance


【解决方案1】:

用户将通过 jTextField 输入三个用户名之一。 我如何接受那里的输入并让它选择哪个实例 课程会运行吗?

您可以将所有Customer 对象存储到Map(客户名称作为键,Customer 对象作为值),然后在接收到用户输入后,从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));

现在,获取用户输入并使用密钥检索Customer 对象(由用户输入的客户名称):

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

【讨论】:

  • 谢谢!这就是我要找的!
【解决方案2】:

不要使用 Map、ArrayList 或 JTextField,而是将客户放入 JComboBox,并让用户直接选择可用的客户。这就是我要做的,因为它会更容易证明白痴 - 因为通过使用它,用户不可能做出无效的选择

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 方法并让它返回名称字段,或者为您的 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;
    }

}

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多