用于附加组合框的 ActionListener

ActionListener to append a Combo Box

我正在尝试使用一个图形用户界面,以便根据用户从第一个列表中选择的内容,第二个列表变得可见。

为此,我需要向第一个组合框添加一个动作侦听器。然后在action listenerclass中做一个switch语句。但是,我在执行此操作时遇到错误。

是否允许在占位符空组合框上附加一个完整的组合框?

package balanceThatSheep;

/*
 * This Class is the GUI for the program.
 */

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class BalancingInterface extends JFrame{
private JLabel sexL, classL, weightL, forageL, concentratesL;

private JButton calculateB, exitB;

private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
private SheepTypeListHandler stlHandler;

private static final int WIDTH = 600;
private static final int HEIGHT = 500;

public BalancingInterface(Data getSomeData){
    // Create four labels
    sexL = new JLabel("Select Sheep Type: ", SwingConstants.CENTER);
    classL = new JLabel("Select Sheep Classification: ", SwingConstants.CENTER);
    weightL = new JLabel("Select Sheep Weight: ", SwingConstants.CENTER);
    forageL = new JLabel("Select a Forage: ", SwingConstants.CENTER);
    concentratesL = new JLabel("Select Feed Concentrates: ", SwingConstants.CENTER);

    //Create the Arrays
    String [] sheepType = {"Ewe", "Ram", "Lamb"}; //Three Choices - can only pick one
    String [] eweClass = {"Maintenance", "Nonlactating, first 15 weeks gestation",
        "Last 6 wks gestation OR Last 8 wks lactation suckling singles",
        "First 8 wks lactation suckling singles OR last 8 wks lactation suckling twins",
        "First 8 weeks lactation suckling twins", "Replacement lambs and yearlings"};
    String [] ramClass = {"Replacement lambs and yearlings"}; //This is the only option for Rams
    String [] lambClass = {"Finishing", "Early-weaned"}; //Only 2 choices
    String [] forageNames = getSomeData.getForageNames(); //Pull in the forage names
    String [] placeholder = {""}; //Use this list as a placeholder

    //Create Drop Down Lists
    JComboBox<String> sheepListCB = new JComboBox<>(sheepType); //Can Only Pick one element - good
    JComboBox<String> sheepEweClassCB = new JComboBox<>(eweClass); //If ewe selected
    JComboBox<String> sheepRamClassCB = new JComboBox<>(ramClass); //If ram selected
    JComboBox<String> sheepLambClassCB = new JComboBox<>(lambClass); //If lamb selected
    JComboBox<String> foragesCB = new JComboBox<>(forageNames); //Can Only Pick one element - good
    JComboBox<String> placeholderCB = new JComboBox<>(placeholder); //Use as a placeholder
    JComboBox<String> placeholder2CB = new JComboBox<>(placeholder); //Use as a placeholder
    JComboBox<String> placeholder3CB = new JComboBox<>(placeholder); //Use as a placeholder

    //Create Calculate Button
    calculateB = new JButton("Calculate");
    cbHandler = new CalculateButtonHandler();
    calculateB.addActionListener(cbHandler);
    //Calculate button you are making the program listen to it.

    //Create Exit Button
    exitB = new JButton("Exit");
    ebHandler = new ExitButtonHandler();
    exitB.addActionListener(ebHandler);

    //Handle the Selection of the Sheep Type
    stlHandler = new SheepTypeListHandler();
    sheepListCB.addActionListener(stlHandler);


    //Set the title of the window box
    setTitle("Welcome to the Sheep Ration Balancer");

    //Get the container
    Container pane = getContentPane();

    //Set the layout
    pane.setLayout(new GridLayout(6, 2)); //6 rows, 2 columns

    //Place all items created
    pane.add(sexL);
    pane.add(sheepListCB);
    pane.add(classL);
    pane.add(placeholderCB);
    pane.add(weightL);
    pane.add(placeholder2CB);
    pane.add(forageL);
    pane.add(foragesCB);
    pane.add(concentratesL);
    pane.add(placeholder3CB);
    pane.add(calculateB);
    pane.add(exitB);

    //set the size of the window and display it
    setSize(WIDTH,HEIGHT);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    //repaint - usually used for graphics - might work here
    repaint();
} //End Constructor

/*
 * This method will execute after the constructor
 */
public void paint(Graphics g)
{
    super.paint(g);


} //End paint Method

private class SheepTypeListHandler implements ActionListener{
    public void actionPerformed(ActionEvent e)
    {
        if (e == "ewe")
            placeholderCB.append(sheepEweClassCB);
        if (e == "ram")
            placeholder2CB.append(sheepRamClassCB);
        else
            placeholder3CB.append(sheepLambClassCB);

        //TODO - Finish this Method
    } //End actionPerformed Method
}

private class CalculateButtonHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        //TODO - Finish this Method
    } //End actionPerformed Method
} //End CalculateButtonHandler Class

private class ExitButtonHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        System.exit(0);
    } //End actionPerformed Method
} //End ExitButton Method Class


} //End of BalancingInterface Class

完整代码如上所示。我正在使用的组合框是 "sheepListCB" 上面的动作侦听器显示了我实现下一个要显示的组合框的逻辑。但是,它不起作用。

也许你想要这样的东西。

Select 来自第一个组合框和第二个组合框的值被填充:

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

public class ComboBoxTwo extends JPanel implements ActionListener
{
    private JComboBox<String> mainComboBox;
    private JComboBox<String> subComboBox;
    private Hashtable<String, String[]> subItems = new Hashtable<String, String[]>();

    public ComboBoxTwo()
    {
        String[] items = { "Select Item", "Color", "Shape", "Fruit" };
        mainComboBox = new JComboBox<String>( items );
        mainComboBox.addActionListener( this );

        //  prevent action events from being fired when the up/down arrow keys are used
        mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        add( mainComboBox );

        //  Create sub combo box with multiple models

        subComboBox = new JComboBox<String>();
        subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
        add( subComboBox );

        String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
        subItems.put(items[1], subItems1);

        String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
        subItems.put(items[2], subItems2);

        String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
        subItems.put(items[3], subItems3);
    }

    public void actionPerformed(ActionEvent e)
    {
        String item = (String)mainComboBox.getSelectedItem();
        Object o = subItems.get( item );

        if (o == null)
        {
            subComboBox.setModel( new DefaultComboBoxModel() );
        }
        else
        {
            subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
        }
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new ComboBoxTwo() );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}