如何从绑定的 ComboBox 中为项目添加价格?

How to add price on an item from a binded ComboBox?

我正在尝试了解 HashtableHashMap 之间的区别,并且我正在尝试在此处为这些项目添加具体价格。目标是将从 comboItem 中选择的项目的价格打印到 txtPrice.

        String[] items = {"Select Item","Betta Fish","Snail","Supplies","Food"};
        comboGroup = new JComboBox<String>(items);
        comboGroup.addActionListener(this);
        comboGroup.setBounds(130,35,150,40);
        
        comboItem = new JComboBox<>();
        comboItem.setPrototypeDisplayValue("XXXXXXXXXXX");
        comboItem.setBounds(130,85,150,40);
        
        String[] subItems1 = {"Select Betta","Plakat","Halfmoon","Double Tail","Crown Tail"};
        subItems.put(items[1], subItems1);
        
        String[] subItems2 = {"Select Snail","Pond Snail","Ramshorn","Apple Snail","Assassin Snail"};
        subItems.put(items[2], subItems2);
                
        String[] subItems3 = {"Select Supply","Small Fine Net","Large Fine Net","Flaring Mirror","Aquarium Hose (1meter)"};
        subItems.put(items[3], subItems3);
        
        String[] subItems4 = {"Select Food","Daphnia","Tubifex","Mosquito Larvae","Optimum Pellets"};
        subItems.put(items[4], subItems4);
        comboGroup.setSelectedIndex(1);      
        
        //TextFields <- this is the attempt to add price to subItems value but commented out
        /*int[] items1price = {0,150,350,200,200};
        subItems.put(items[1], items1price);
        int[] items2price = {0,15,25,80,120};
        subItems.put(items[2], items2price);
        int[] items3price = {0,50,80,25,15};
        subItems.put(items[3], items3price);
        int[] items4price = {0,50,100,50,50};
        subItems.put(items[4], items4price);
        comboGroup.setSelectedIndex(1);
        */
        txtPrice = new JTextField();
        txtPrice.setBounds(130,135,150,40);

到目前为止,根据我对 HashMap 的理解,将其应用于 CLi 而不是在 GUI 中,如果我尝试 HashMap<String,Integer> 我只能将其完全打印在一行中。

例如

HashMap<String,Integer> item = new HashMap<String,Integer>();
item.put("Plakat",50);

CLi Prints:
Plakat=50

我想要的是从选定的 comboItem 中打印 Plakat,然后将 50 打印到 txtPrice,但我不知道该怎么做。

完整代码在这里:https://github.com/kontext66/GuwiPos GUI 和主要。

补充说明:我是初学者,目前正在尝试了解Layout Manager,所以这里的代码有点乱。

下面是一个使用 JComboBox and HashMap to get the corresponding "prices" to specific items in the combo box. I would suggest going through the tutorial on How to Use Various Layout Managers and choose the ones that suit you best. As for the difference between HashMap and HashTable, please have a look at this answer. The main difference is that HashTable is synchronized, whereas HashMap is not, and since synchronization is not an issue for you, I'd suggest HashMap. Also, another option would be to add instances of a custom object to a JComboBox, as described here 的例子。因此,不需要使用 HashMap.

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

public class App {
    Map<String, String> map;
    JTextField tf;

    public App() {
        map = new HashMap<String, String>();
        map.put("Plakat", "50");
        map.put("Halfmoon", "25");
        map.put("Double Tail", "80");
    }

    private void addComponentsToPane(Container pane) {
        String[] items = { "Select Item", "Plakat", "Halfmoon", "Double Tail" };
        JComboBox<String> comboBox = new JComboBox<String>(items);

        comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    String item = (String) event.getItem();
                    System.out.println(item);
                    tf.setText(map.get(item));
                }
            }
        });

        tf = new JTextField();
        JPanel p = new JPanel();
        pane.add(comboBox, BorderLayout.NORTH);
        pane.add(tf, BorderLayout.SOUTH);
    }

    private void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addComponentsToPane(frame.getContentPane());
        // frame.setSize(640, 480);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new App().createAndShowGUI();
            }
        });
    }

}

更新

下面是前面描述的第二种方法的实现,其中自定义对象用于将项目添加到 JComboBox,因此不需要使用 HashMap

P.S。我还应该补充一点,如果不允许用户在文本字段中编辑“价格”,那么您应该使用 tf.setEditable(false);,甚至使用 JLabel

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

public class App {
    JTextField tf;

    class ComboItem {
        private String key;
        private String value;

        public ComboItem(String key, String value) {
            this.key = key;
            this.value = value;
        }

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

        public String getKey() {
            return key;
        }

        public String getValue() {
            return value;
        }
    }

    private void addComponentsToPane(Container pane) {
        JComboBox<ComboItem> comboBox = new JComboBox<ComboItem>();
        comboBox.addItem(new ComboItem("Select Item", ""));
        comboBox.addItem(new ComboItem("Plakat", "50"));
        comboBox.addItem(new ComboItem("Halfmoon", "25"));
        comboBox.addItem(new ComboItem("Double Tail", "80"));

        comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    Object item = comboBox.getSelectedItem();
                    String value = ((ComboItem) item).getValue();
                    tf.setText(value);
                }
            }
        });

        tf = new JTextField();
        JPanel p = new JPanel();
        pane.add(comboBox, BorderLayout.NORTH);
        pane.add(tf, BorderLayout.SOUTH);
    }

    private void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addComponentsToPane(frame.getContentPane());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new App().createAndShowGUI();
            }
        });
    }
}

更新 2

要将文本字段中的字符串转换为double,可以使用Double.parseDouble(String),如下所示(再次确保使用tf.setEditable(false);,这样值就不能被用户)。

double price = 0;
if (tf.getText() != null && !tf.getText().trim().isEmpty())
    price = Double.parseDouble(tf.getText());
System.out.println(price);