为什么这只适用于设计的 comboBox 而不是硬编码的 swing?

Why does this only work on designed comboBox and not on hardcoded swing?

新手问题:

所以这段代码在这里

public void comboItemItemStateChanged(java.awt.event.ItemEvent evt) {  
        ArrayList<String> arrayItem = new ArrayList<>();
        Iterator<String> iter;
        if(comboGroup.getSelectedItem().equals("Betta Fish")){
            comboItem.removeAllItems();
            arrayItem.add("Plakat");
            arrayItem.add("Halfmoon");
            arrayItem.add("Crown Tail");
            arrayItem.add("Double Tail");
            iter = arrayItem.iterator();
            while(iter.hasNext()){
                comboItem.addItem(iter.next());
            }
        }
        else if(comboGroup.getSelectedItem().equals("Snails")){
            comboItem.removeAllItems();
            arrayItem.add("Apple Horn");
            arrayItem.add("RamsHorn");
            arrayItem.add("Pond Snail");
            arrayItem.add("Assassin Snail");
            iter = arrayItem.iterator();
            while(iter.hasNext()){
                comboItem.addItem(iter.next());
            }

当我在 NetBeans 的 Design 选项卡的组合框上尝试它时有效。但是当我尝试将它应用到我的编码 ComboBox 时,我从 evt 收到一条消息说 Unused method parameters should be removed。我能解释一下为什么以及硬编码 comboBox 的替代方案是什么吗?

代码的用途:一个动态的 comboBox 所以无论我从 comboBox1 中选择什么都会有每个自己的列表集 comboBox2

注意:我还尝试将 comboItemItemStateChanged 更改为 itemStatChanged

我的项目源代码:https://github.com/kontext66/GuwiPos/blob/main/GuwiPos

对不起大家的困惑,我有一个主要的class。

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

Main.java、GuwiPos.java

真的很简单。
该消息只是 NetBeans 通知您方法 comboItemItemStateChanged 的代码未引用方法参数 evt。这不是错误,甚至不是警告。你可以忽略它。当您编写代码时,NetBeans 在其编辑器中显示这些“提示”,而 NetBeans GUI 生成器生成代码。

请注意,每次选择 JComboBox 中的项目以及每次选择 de-selected 中的项目时,都会调用方法 comboItemItemStateChanged。我猜你只希望在选择一个项目时代码为 运行,因此方法的第一行 comboItemItemStateChanged 应该是

if (evt.getStateChange() == ItemEvent.SELECTED) {

然后您正在引用方法参数,“提示”将消失。

参考How to Write an Item Listener

编辑

我想您可能会从学习 GUI 设计中受益。我从来没有见过像你这样的人。我想知道您是如何得出该设计的。在任何情况下,下面的代码仅解决 comboItem 中的列表根据 comboGroup.

中的所选项目进行调整的功能

根据我的经验,通过方法 removeAllItemsaddItem 删除和添加项目到 JComboBox 非常慢。简单地替换我在下面的代码中所做的 JComboBox 模型会更有效。对于像您这样的小列表,差异不会被注意到,但随着列表变大,差异会增加。

此外,[JComboBox] 所选项目位于方法 comboItemItemStateChangedevt 参数中。

您的原始代码没有向 comboGroup 添加 项目侦听器 ,也没有 main 方法。我在下面的代码中添加了这些。请注意,项目侦听器 是通过 method reference.

添加的
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JComboBox;

import java.awt.Color;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 *
 * @author kahbg
 */
public class GuwiPos extends JFrame implements ActionListener {
    public static final Map<String, ComboBoxModel<String>>  LISTS;

    JButton buttonBasket;
    JButton buttonHelp;
    JTextField txtGroup;
    JTextField txtItem;
    JTextField txtQty;
    JTextField txtTotal;
    JTextField txtPrice;
    JComboBox<String> comboGroup;
    JComboBox<String> comboItem;

    static {
        LISTS = new HashMap<>();
        Vector<String> v = new Vector<>();
        v.add("Plakat");
        v.add("Halfmoon");
        v.add("Crown Tail");
        v.add("Double Tail");
        ComboBoxModel<String> model = new DefaultComboBoxModel<>(v);
        LISTS.put("Betta Fish", model);
        v = new Vector<>();
        v.add("Apple Horn");
        v.add("RamsHorn");
        v.add("Pond Snail");
        v.add("Assassin Snail");
        model = new DefaultComboBoxModel<>(v);
        LISTS.put("Snails", model);
        v = new Vector<>();
        v.add("Small Fine Net");
        v.add("Large Fine Net");
        v.add("Flaring Mirror");
        v.add("Aquarium Hose");
        model = new DefaultComboBoxModel<>(v);
        LISTS.put("Supplies", model);
        v = new Vector<>();
        v.add("Tubifex");
        v.add("Daphnia");
        v.add("Optimum Pellets");
        model = new DefaultComboBoxModel<>(v);
        LISTS.put("Food", model);
    }

    GuwiPos() {

        // ComboBox
        String[] products = {"Select Item...", "Betta Fish", "Snails", "Supplies", "Food"};
        comboGroup = new JComboBox<String>(products);
        comboGroup.addItemListener(this::comboItemItemStateChanged);
        comboGroup.setBounds(130, 35, 150, 40);

        comboItem = new JComboBox<String>();
        comboItem.setBounds(130, 85, 150, 40);

        // TextFields
        txtPrice = new JTextField();
        txtPrice.setBounds(130, 135, 150, 40);

        txtQty = new JTextField();
        txtQty.setBounds(130, 185, 150, 40);

        txtTotal = new JTextField();
        txtTotal.setBounds(130, 235, 150, 40);

        // txtTotalAmt = new JTextField(); to code later on

        // txtPaid = new JTextField(); to code later on

        // txtChange = new JTextField(); to code later on

        // Labels
        // Product
        JLabel labelProduct = new JLabel();
        labelProduct.setText("Item Group");
        labelProduct.setBounds(10, 5, 100, 100);
        // Item
        JLabel labelItem = new JLabel();
        labelItem.setText("Item");
        labelItem.setBounds(10, 55, 100, 100);
        // Price
        JLabel labelPrice = new JLabel();
        labelPrice.setText("Price");
        labelPrice.setBounds(10, 105, 100, 100);
        // Qty
        JLabel labelQty = new JLabel();
        labelQty.setText("Quantity");
        labelQty.setBounds(10, 155, 100, 100);
        // Total
        JLabel labelTotal = new JLabel();
        labelTotal.setText("Total");
        labelTotal.setBounds(10, 205, 100, 100);

        // Buttons
        buttonBasket = new JButton();
        buttonBasket.setBounds(0, 0, 300, 50);
        buttonBasket.setText("Add to Basket");
        buttonBasket.setFocusable(false);
        buttonBasket.setBorder(BorderFactory.createEtchedBorder());
        buttonBasket.addActionListener(this);

        JButton buttonPay = new JButton();
        buttonPay.setText("PAY");
        buttonPay.setBounds(0, 50, 150, 100);
        buttonPay.setFocusable(false);
        buttonPay.setBorder(BorderFactory.createEtchedBorder());
        buttonPay.addActionListener(e -> System.out.println("Payment Success"));

        JButton buttonCancel = new JButton();
        buttonCancel.setText("CANCEL");
        buttonCancel.setBounds(0, 150, 150, 100);
        buttonCancel.setFocusable(false);
        buttonCancel.setBorder(BorderFactory.createEtchedBorder());
        buttonCancel.addActionListener(e -> System.out.println("Transaction Cancelled"));

        JButton buttonDiscount = new JButton();
        buttonDiscount.setText("Apply Discount?");
        buttonDiscount.setBounds(150, 50, 150, 50);
        buttonDiscount.setFocusable(false);
        buttonDiscount.setBorder(BorderFactory.createEtchedBorder());
        buttonDiscount.addActionListener(e -> System.out.println("20% Discount Applied"));

        JButton buttonHelp = new JButton();
        buttonHelp.setText("HELP");
        buttonHelp.setBounds(150, 100, 150, 100);
        buttonHelp.setFocusable(false);
        buttonHelp.setBorder(BorderFactory.createEtchedBorder());

        JButton buttonDelete = new JButton();
        buttonDelete.setText("DELETE");
        buttonDelete.setBounds(150, 200, 150, 50);
        buttonDelete.setFocusable(false);
        buttonDelete.setBorder(BorderFactory.createEtchedBorder());
        buttonDelete.addActionListener(e -> System.out.println("Item Deleted"));

        // Panels
        // Left contains item and price
        JPanel bluePanel = new JPanel();
        bluePanel.setBackground(Color.blue);
        bluePanel.setBounds(0, 0, 300, 300); // x,y,width,height
        bluePanel.setLayout(null);
        // Right contains product basket
        JPanel redPanel = new JPanel();
        redPanel.setBackground(Color.red);
        redPanel.setBounds(300, 0, 600, 300); // x,y,width,length
        redPanel.setLayout(null);
        // Bottom Left contains buttons pay,change,discount
        JPanel greenPanel = new JPanel();
        greenPanel.setBackground(Color.green);
        greenPanel.setBounds(0, 300, 300, 450);// x,y,width,length
        greenPanel.setLayout(null);
        // Bottom Right contains total amount
        JPanel yellowPanel = new JPanel();
        yellowPanel.setBackground(Color.yellow);
        yellowPanel.setBounds(0, 300, 900, 450);// x,y,width,length
        yellowPanel.setLayout(null);

        this.setTitle("Open Betta POS");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(null);
        this.setSize(900, 590);
        this.setResizable(false);
        this.setVisible(true);

        // ADDED AWT
        bluePanel.add(txtQty);
        bluePanel.add(txtTotal);
        bluePanel.add(txtPrice);
        bluePanel.add(comboItem);
        bluePanel.add(comboGroup);
        bluePanel.add(labelProduct);
        bluePanel.add(labelItem);
        bluePanel.add(labelPrice);
        bluePanel.add(labelQty);
        bluePanel.add(labelTotal);
        greenPanel.add(buttonBasket);
        greenPanel.add(buttonPay);
        greenPanel.add(buttonCancel);
        greenPanel.add(buttonDiscount);
        greenPanel.add(buttonHelp);
        greenPanel.add(buttonDelete);
        this.add(bluePanel);
        this.add(redPanel);
        this.add(greenPanel);
        this.add(yellowPanel);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == buttonBasket) {
            System.out.println("Added Item to Basket: " + comboGroup.getSelectedItem() + "\n"
                    + comboItem.getSelectedItem());
        }
    }

    // This is not working
    public void comboItemItemStateChanged(java.awt.event.ItemEvent evt) {
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            Object selection = evt.getItem();
            ArrayList<String> arrayItem = new ArrayList<>();
            Iterator<String> iter;
            if (selection.equals("Betta Fish")) {
                comboItem.setModel(LISTS.get("Betta Fish"));
            }
            else if (selection.equals("Snails")) {
                comboItem.setModel(LISTS.get("Snails"));
            }
            else if (selection.equals("Supplies")) {
                comboItem.setModel(LISTS.get("Supplies"));
            }
            else if (selection.equals("Food")) {
                comboItem.setModel(LISTS.get("Food"));
            }
            else if (selection.equals("Select Item...")) {
                comboItem.removeAllItems();
                arrayItem.add("Select Item...");
                iter = arrayItem.iterator();
                while (iter.hasNext()) {
                    comboItem.addItem(iter.next());
                }
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new GuwiPos());
    }
}

您的代码(改进版 - 减一 ActionListener

public class SwingApp {
    
    private static JComboBox<String> comboItem;
    private static JComboBox<String> productCombo;
    
    public static void main (String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            
            @Override
            public void run () {
                createAndShowGUI();
            }
        });
    }
    
    private static void createAndShowGUI () {
        
        JFrame frame = createMainFrame();
        
        JPanel bluePanel = createBluePanel();
        JPanel greenPanel = createGreenPanel();
        JPanel redPanel = createRedPanel();
        JPanel yellowPanel = createYellowPanel();
        
        frame.add(bluePanel);
        frame.add(greenPanel);
        frame.add(redPanel);
        frame.add(yellowPanel);
        frame.setVisible(true);
    }
    
    private static JFrame createMainFrame () {
        JFrame frame = new JFrame("Open Betta POS");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);
        frame.setSize(900, 590);
        frame.setResizable(false);
        return frame;
    }
    
    private static JPanel createBluePanel () {
        ComboSelectionListener productComboListener = new ComboSelectionListener();
        JPanel panel = new JPanel(null); // Sets layout manager to null which is a bad idea!
        String[] products =
            {"Select Item...", "Betta Fish", "Snails", "Supplies", "Food"};
        productCombo = new JComboBox<>(products);
        productCombo.setBounds(130, 35, 150, 40);
        productCombo.setActionCommand("selectProduct");
        productCombo.addActionListener(productComboListener);
        comboItem = new JComboBox<>();
        comboItem.setBounds(130, 85, 150, 40);
        
        // TextFields
        JTextField txtPrice = new JTextField();
        txtPrice.setBounds(130, 135, 150, 40);
        
        JTextField txtQty = new JTextField();
        txtQty.setBounds(130, 185, 150, 40);
        
        JTextField txtTotal = new JTextField();
        txtTotal.setBounds(130, 235, 150, 40);
        JLabel labelProduct = new JLabel();
        labelProduct.setText("Item Group");
        labelProduct.setBounds(10, 5, 100, 100);
        // Item
        JLabel labelItem = new JLabel();
        labelItem.setText("Item");
        labelItem.setBounds(10, 55, 100, 100);
        // Price
        JLabel labelPrice = new JLabel();
        labelPrice.setText("Price");
        labelPrice.setBounds(10, 105, 100, 100);
        // Qty
        JLabel labelQty = new JLabel();
        labelQty.setText("Quantity");
        labelQty.setBounds(10, 155, 100, 100);
        // Total
        JLabel labelTotal = new JLabel();
        labelTotal.setText("Total");
        labelTotal.setBounds(10, 205, 100, 100);
        
        panel.setBackground(Color.blue);
        panel.setBounds(0, 0, 300, 300); // x,y,width,height
        panel.add(txtQty);
        panel.add(txtTotal);
        panel.add(txtPrice);
        panel.add(comboItem);
        panel.add(productCombo);
        panel.add(labelProduct);
        panel.add(labelItem);
        panel.add(labelPrice);
        panel.add(labelQty);
        panel.add(labelTotal);
        return panel;
        
    }
    
    private static JPanel createGreenPanel () {
        JPanel panel = new JPanel(null);
        panel.setBackground(Color.green);
        panel.setBounds(0, 300, 300, 450);// x,y,width,length
        JButton buttonBasket = new JButton();
        buttonBasket.setBounds(0, 0, 300, 50);
        buttonBasket.setText("Add to Basket");
        buttonBasket.setFocusable(false);
        buttonBasket.setBorder(BorderFactory.createEtchedBorder());
        buttonBasket
            .addActionListener(e -> System.out.println("Added Item to Basket: "
                + productCombo.getSelectedItem() + "\n" + comboItem.getSelectedItem()));
        
        JButton buttonPay = new JButton();
        buttonPay.setText("PAY");
        buttonPay.setBounds(0, 50, 150, 100);
        buttonPay.setFocusable(false);
        buttonPay.setBorder(BorderFactory.createEtchedBorder());
        buttonPay.addActionListener(e -> System.out.println("Payment Success"));
        
        JButton buttonCancel = new JButton();
        buttonCancel.setText("CANCEL");
        buttonCancel.setBounds(0, 150, 150, 100);
        buttonCancel.setFocusable(false);
        buttonCancel.setBorder(BorderFactory.createEtchedBorder());
        buttonCancel
            .addActionListener(e -> System.out.println("Transaction Cancelled"));
        
        JButton buttonDiscount = new JButton();
        buttonDiscount.setText("Apply Discount?");
        buttonDiscount.setBounds(150, 50, 150, 50);
        buttonDiscount.setFocusable(false);
        buttonDiscount.setBorder(BorderFactory.createEtchedBorder());
        buttonDiscount
            .addActionListener(e -> System.out.println("20% Discount Applied"));
        
        JButton buttonHelp = new JButton();
        buttonHelp.setText("HELP");
        buttonHelp.setBounds(150, 100, 150, 100);
        buttonHelp.setFocusable(false);
        buttonHelp.setBorder(BorderFactory.createEtchedBorder());
        
        JButton buttonDelete = new JButton();
        buttonDelete.setText("DELETE");
        buttonDelete.setBounds(150, 200, 150, 50);
        buttonDelete.setFocusable(false);
        buttonDelete.setBorder(BorderFactory.createEtchedBorder());
        buttonDelete.addActionListener(e -> System.out.println("Item Deleted"));
        
        panel.add(buttonBasket);
        panel.add(buttonPay);
        panel.add(buttonCancel);
        panel.add(buttonDiscount);
        panel.add(buttonHelp);
        panel.add(buttonDelete);
        
        return panel;
    }
    
    private static JPanel createRedPanel () {
        JPanel panel = new JPanel(null);
        panel.setBackground(Color.red);
        panel.setBounds(300, 0, 600, 300); // x,y,width,length
        return panel;
    }
    
    private static JPanel createYellowPanel () {
        JPanel panel = new JPanel();
        panel.setBackground(Color.yellow);
        panel.setBounds(0, 300, 900, 450); // x,y,width,length
        return panel;
    }
    
    private static class ComboSelectionListener implements ActionListener {
        
        @Override
        public void actionPerformed (ActionEvent e) {
            JComboBox<String> comboGroup = (JComboBox<String>) e.getSource();
            
            ArrayList<String> arrayItem = new ArrayList<>();
            Iterator<String> iter;
            if (comboGroup.getSelectedItem().equals("Betta Fish")) {
                comboItem.removeAllItems();
                arrayItem.add("Plakat");
                arrayItem.add("Halfmoon");
                arrayItem.add("Crown Tail");
                arrayItem.add("Double Tail");
                iter = arrayItem.iterator();
                while (iter.hasNext()) {
                    comboItem.addItem(iter.next());
                }
            } else if (comboGroup.getSelectedItem().equals("Snails")) {
                comboItem.removeAllItems();
                arrayItem.add("Apple Horn");
                arrayItem.add("RamsHorn");
                arrayItem.add("Pond Snail");
                arrayItem.add("Assassin Snail");
                iter = arrayItem.iterator();
                while (iter.hasNext()) {
                    comboItem.addItem(iter.next());
                }
            } else if (comboGroup.getSelectedItem().equals("Supplies")) {
                comboItem.removeAllItems();
                arrayItem.add("Small Fine Net");
                arrayItem.add("Large Fine Net");
                arrayItem.add("Flaring Mirror");
                arrayItem.add("Aquarium Hose");
                iter = arrayItem.iterator();
                while (iter.hasNext()) {
                    comboItem.addItem(iter.next());
                }
            } else if (comboGroup.getSelectedItem().equals("Food")) {
                comboItem.removeAllItems();
                arrayItem.add("Tubifex");
                arrayItem.add("Daphnia");
                arrayItem.add("Optimum Pellets");
                iter = arrayItem.iterator();
                while (iter.hasNext()) {
                    comboItem.addItem(iter.next());
                }
            } else if (comboGroup.getSelectedItem().equals("Select Item...")) {
                comboItem.removeAllItems();
                arrayItem.add("Select Item...");
                iter = arrayItem.iterator();
                while (iter.hasNext()) {
                    comboItem.addItem(iter.next());
                }
            }
        }
    }
}

改进(除了解决主要问题)

  1. 创建了一个不是 Swing 组件的 Swing(主要)class
  2. 主要 class 没有实现 ActionListener
  3. 已使用 SwingUtilities 启动 Swing 应用程序
  4. 创建方法来封装涉及创建组件的细节
  5. 最小化变量范围