如何跟踪组合框 1 中的选定选项并在 java 中的组合框 2 上显示相应的选项

How to track selected option from Combo Box 1 and show corresponding option on combo box 2 in java

我已经将近 6 年没有触及 java 只是试图完成这个副项目,我正在尝试让 jComboBox2 显示存储在数据库中的特定公司职位,这些职位来自所选公司jComboBox1,我知道 ActionListener 无法做到正确,我只需要使其动态化,每当从 combo1 中选择不同的公司时,相应的公司职位应该显示在 combo2 上,这里是示例代码:

public class NewMessage extends javax.swing.JFrame{

    /**
     * Creates new form NewMessage
     */
    public NewMessage() {
        initComponents();
        showCompany();
        showPosition();
        
    }
    
    public void showCompany(){
        try {
            String jdbcUrl = "jdbc:sqlite:/client.db";
            Connection connection = DriverManager.getConnection(jdbcUrl);
            
            String query = "SELECT * FROM contacts";
            Statement statement = connection.createStatement();
            ResultSet result = statement.executeQuery(query);
            
            while(result.next()){
                String company = result.getString("company");
                jComboBox1.addItem(company);
            }
        }catch(SQLException e) {
            JOptionPane.showMessageDialog(this, e.getMessage());
        }
    }
   
    
    public void showPosition(){
        try {
            String jdbcUrl = "jdbc:sqlite:/client.db";
            Connection connection = DriverManager.getConnection(jdbcUrl);
            
            String companyName = jComboBox1.getSelectedItem().toString();
            
            String query = "SELECT * FROM contacts WHERE company='"+companyName+"' ";
            Statement statement = connection.createStatement();
            
            ResultSet result = statement.executeQuery(query);
            
            while(result.next()){
                String positions = result.getString("position");
                jComboBox2.addItem(positions);
            }
        }catch(SQLException e) {
            JOptionPane.showMessageDialog(this, e.getMessage());
        }
    }

我不知道为什么您会认为 ActionListener 不适合这项任务。如果您不想知道某个项目何时变为“未选择”,那么 ActionListener 是完美的,因为您只需要处理选择的变化。

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    JFrame frame = new JFrame();
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    public class TestPane extends JPanel {

        private JComboBox<String> typesComboBox;
        private JComboBox<String> pokemonComboBox;

        private Map<String, List<String>> mapPokemon;

        public TestPane() throws IOException {
            setBorder(new EmptyBorder(32, 32, 32, 32));
            buildDatabase();

            DefaultComboBoxModel<String> typesModel = new DefaultComboBoxModel<>();
            for (String key : mapPokemon.keySet()) {
                typesModel.addElement(key);
            }

            typesComboBox = new JComboBox<>(typesModel);
            typesComboBox.setSelectedItem(null);
            pokemonComboBox = new JComboBox<>();
            pokemonComboBox.setEnabled(false);

            setLayout(new GridBagLayout());

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.insets = new Insets(4, 4, 4, 4);
            gbc.anchor = GridBagConstraints.LINE_START;

            add(new JLabel("Types: "), gbc);
            gbc.gridy++;
            add(new JLabel("Pokemon: "), gbc);

            gbc.gridx++;
            gbc.gridy = 0;
            gbc.fill = GridBagConstraints.HORIZONTAL;

            add(typesComboBox, gbc);
            gbc.gridy++;
            add(pokemonComboBox, gbc);

            typesComboBox.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    DefaultComboBoxModel<String> pokemon = new DefaultComboBoxModel<>();
                    String selected = (String)typesComboBox.getSelectedItem();
                    if (selected != null) {
                        List<String> values = mapPokemon.get(selected);
                        if (values != null) {
                            pokemon.addAll(values);
                        }
                    }                    
                    pokemonComboBox.setModel(pokemon);
                    pokemonComboBox.setEnabled(pokemon.getSize() != 0);
                }
            });
        }

        protected void buildDatabase() throws IOException {
            mapPokemon = new HashMap<>();
            mapPokemon.put("Water", getWaterTypes());
            mapPokemon.put("Fire", getFireTypes());
            mapPokemon.put("Ground", getGroundTypes());
            mapPokemon.put("Rock", getRockTypes());
        }

        protected List<String> getWaterTypes() throws IOException {
            return readFromResource("/resources/WaterTypes.txt");
        }

        protected List<String> getFireTypes() throws IOException {
            return readFromResource("/resources/FireTypes.txt");
        }

        protected List<String> getGroundTypes() throws IOException {
            return readFromResource("/resources/GroundTypes.txt");
        }

        protected List<String> getRockTypes() throws IOException {
            return readFromResource("/resources/RockTypes.txt");
        }

        protected List<String> readFromResource(String name) throws IOException {
            try (BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(name)))) {
                return readFrom(br);
            }
        }

        protected List<String> readFrom(BufferedReader br) throws IOException {
            List<String> values = new ArrayList<>(32);
            String value = null;
            while ((value = br.readLine()) != null) {
                if (!value.isBlank()) {
                    values.add(value);
                }
            }
            return values;
        }

    }
}