ActionListener附加组合框

时间:2015-04-10 19:23:50

标签: java swing user-interface combobox append

我正在尝试使用gui,这取决于用户从第一个列表中选择的内容,然后第二个列表变为可见。

为了做到这一点,我需要在第一个组合框中添加一个动作监听器。然后在动作侦听器类中执行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”,上面的动作监听器显示了我的逻辑,用于实现下一个显示的组合框。但是,它不起作用。

1 个答案:

答案 0 :(得分:2)

也许你想要这样的东西。

从第一个组合框中选择一个值,然后填充第二个组合框:

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