使用另一个组合框过滤组合框

时间:2015-11-20 10:50:40

标签: java swing

http://i.stack.imgur.com/ZxgaG.png

private void Filecombo(){

try{
    String sql ="Select * from checkstock";
    pst=conn.prepareStatement(sql);
    rs=pst.executeQuery();

    while (rs.next()){
    String name = rs.getString("Stock_Name");
    comboBoxStock.addItem(name);
    }
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}

}

我已将comboBoxStock连接到数据库。这意味着每当我在数据库中添加新股票时,它将在comboBoxStock(图片中的股票名称)中更新。但是现在如何使用类别组合框过滤股票?例如我在Catogeries组合框中选择笔记本电脑,只有笔记本电脑类别会显示在股票名称中吗?

1 个答案:

答案 0 :(得分:0)

您需要创建一个每次单击“类别”组合框时都会更改的子模型:

一个简单的例子让你开始:

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