Hi guys,

I've been working with a project that requires me to use mutiple jcombobox. I did try to relate three jcombobox but failed to show all necesarry drop-down lists.
in one of my combobox I have lists of Banks (Bank1, Bank2), the other one is the list of all branches in a specific Bank that has been selected (Bank1(branch1-1, branch1-2), Bank2(branch2-1, branch2-2)) and the last one are the account # for all specific branches that has been selected. each branches has a multiple accounts. I have no problem working with 2 comboboxes, all branches are shown for a specific Bank that has been selected, but, when I added the third combobox which is the account #, only one branch is being queried from my db. ex. if I select Bank1 only "branch1" will be on the list, and if Bank2 only branch2-1 will be on the list also, but account # for that specific branches are on the drop-down lists.

here's my code:

private void populateSavingsAccountComboBox(){
accountNo.removeAllItems();
bankBranch.removeAllItems();
selectBank();
bankName.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String bank = bankName.getSelectedItem() == null ? "" : bankName.getSelectedItem().toString();
selectBranch(bank);
}
});

bankBranch.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
Object source = e.getSource();
JComboBox target = (JComboBox)e.getSource();
String branch = target.getSelectedItem() == null ? "" : target.getSelectedItem().toString();
if (e.getStateChange() == ItemEvent.SELECTED){
selectAccountNo(bankName.getSelectedItem().toString(), branch);
}
}
});
}

private void selectBank(){
List bankList = new ArrayList();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(" SELECT bankName FROM bank_tbl ");
bankName.removeAllItems();
while (rs.next()) {
String bank = rs.getString("bankName");
bankList.add(bank);
Object bankElement = bankList.get(bankList.size() - 1);
bankName.addItem(bankElement);
}
} catch (SQLException ex) {
Logger.getLogger(addSavings.class.getName()).log(Level.SEVERE, null, ex);
}
}
private String selectBranch(String bank){
try {
List branchList = new ArrayList();
rs = stmt.executeQuery(" SELECT branch FROM bank_branch_tbl WHERE "
+ " bankName = '" + bank + "' ");
bankBranch.removeAllItems();
while (rs.next()) {
branchList.add(rs.getString("branch"));
Object branchElement = branchList.get(branchList.size()-1);
bankBranch.addItem(branchElement);
}
} catch (SQLException ex) {
Logger.getLogger(addContact.class.getName()).log(Level.SEVERE, null, ex);
}
return bank;
}

private String selectAccountNo(String bank, String branch){
List accountNoList = new ArrayList();
try {
rs = stmt.executeQuery(" SELECT accountNo FROM account_no_tbl WHERE "
+ " bankName = '"+bank+"' AND "
+ " branch = '"+branch+"' ");
accountNo.removeAllItems();
while(rs.next()){
accountNoList.add(rs.getString("accountNo"));
Object accountNoElement = accountNoList.get(accountNoList.size()-1);
accountNo.addItem(accountNoElement);
}
} catch (SQLException ex) {
Logger.getLogger(addSavings.class.getName()).log(Level.SEVERE, null, ex);
}
return branch;
}

if you create simple example that will be conatains only three JComboBox(es), and Db conn will be replaces with data saved into JList or Strins[], then I'll look at ...

please edit your post and by mouse select code that you posted and pack that into [code] button

Thank you for the response.

private void populateSavingsAccountComboBox(){
accountNo.removeAllItems();
bankBranch.removeAllItems();
selectBank();
bankName.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String bank = bankName.getSelectedItem() == null ? "" : bankName.getSelectedItem().toString();
selectBranch(bank);
}
});

bankBranch.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
Object source = e.getSource();
JComboBox target = (JComboBox)e.getSource();
String branch = target.getSelectedItem() == null ? "" : target.getSelectedItem().toString();
if (e.getStateChange() == ItemEvent.SELECTED){
selectAccountNo(bankName.getSelectedItem().toString(), branch);
}
}
});
}

private void selectBank(){
List bankList = new ArrayList();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(" SELECT bankName FROM bank_tbl ");
bankName.removeAllItems();
while (rs.next()) {
String bank = rs.getString("bankName");
bankList.add(bank);
Object bankElement = bankList.get(bankList.size() - 1);
bankName.addItem(bankElement);
}
} catch (SQLException ex) {
Logger.getLogger(addSavings.class.getName()).log(Level.SEVERE, null, ex);
}
}
private String selectBranch(String bank){
try {
List branchList = new ArrayList();
rs = stmt.executeQuery(" SELECT branch FROM bank_branch_tbl WHERE "
+ " bankName = '" + bank + "' ");
bankBranch.removeAllItems();
while (rs.next()) {
branchList.add(rs.getString("branch"));
Object branchElement = branchList.get(branchList.size()-1);
bankBranch.addItem(branchElement);
}
} catch (SQLException ex) {
Logger.getLogger(addContact.class.getName()).log(Level.SEVERE, null, ex);
}
return bank;
}

private String selectAccountNo(String bank, String branch){
List accountNoList = new ArrayList();
try {
rs = stmt.executeQuery(" SELECT accountNo FROM account_no_tbl WHERE "
+ " bankName = '"+bank+"' AND "
+ " branch = '"+branch+"' ");
accountNo.removeAllItems();
while(rs.next()){
accountNoList.add(rs.getString("accountNo"));
Object accountNoElement = accountNoList.get(accountNoList.size()-1);
accountNo.addItem(accountNoElement);
}
} catch (SQLException ex) {
Logger.getLogger(addSavings.class.getName()).log(Level.SEVERE, null, ex);
}
return branch;
}

the skeleton structure for that code is,

jCombobox1 = bankName;
jCombobox2 = bankBranch;
jCombobox3 = accountNo;

private void populateCombobox(){
executeQuery(select bankName from db)
while(){
bankName.addItem(bankName.query)
}
bankName.addActionListener(...
executeQuery(select branch from db where bank = bankName.getselectedItem().toSring())
while(){
bankBranch.addItem(branch.query)
);
bankBranch.addItemListener(...
executeQuery(select accountNo from db where branch = bankBranch.getselectedItem().toSring())
while(){
accountNo.addItem(accountNo.query)
)
}

as ive said, if I use 2 jComboboxes all branches for a specific selected Bank will be in the drop-down list but when I added the 3rd jCombobox(3) for accountNO only the first (one) branch will be on the jCombobox(2) drop-down list.

no never etc...

example that I posted to one JavaExampleDepots

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

public class ComboBoxTwo extends JFrame implements ActionListener, ItemListener {

    private static final long serialVersionUID = 1L;
    private JComboBox mainComboBox;
    private JComboBox subComboBox;
    private Hashtable<Object, Object> subItems = new Hashtable<Object, Object>();

    public ComboBoxTwo() {
        String[] items = {"Select Item", "Color", "Shape", "Fruit"};
        mainComboBox = new JComboBox(items);
        mainComboBox.addActionListener(this);
        mainComboBox.addItemListener(this);
        //prevent action events from being fired when the up/down arrow keys are used
        //mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        getContentPane().add(mainComboBox, BorderLayout.WEST);
        subComboBox = new JComboBox();//  Create sub combo box with multiple models
        subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
        subComboBox.addItemListener(this);
        getContentPane().add(subComboBox, BorderLayout.EAST);
        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);
//      mainComboBox.setSelectedIndex(1);
    }

    @Override
    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));
        }
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            if (e.getSource() == mainComboBox) {
                if (mainComboBox.getSelectedIndex() != 0) {
                    FirstDialog firstDialog = new FirstDialog(ComboBoxTwo.this,
                            mainComboBox.getSelectedItem().toString(), "Please wait,  Searching Branches for ..... ");
                }
            } else if (e.getSource() == subComboBox) {
                if (subComboBox.getSelectedIndex() != 0) {
                    FirstDialog firstDialog = new FirstDialog(ComboBoxTwo.this,
                            subComboBox.getSelectedItem().toString(), "Please wait,   Loading Accounts for Selected Branch..... ");
                }
            }
        }
    }

    private class FirstDialog extends JDialog {

        private static final long serialVersionUID = 1L;

        FirstDialog(final Frame parent, String winTitle, String msgString) {
            super(parent, winTitle);
            setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
            JLabel myLabel = new JLabel(msgString);
            JButton bNext = new JButton("Stop Processes");
            add(myLabel, BorderLayout.CENTER);
            add(bNext, BorderLayout.SOUTH);
            bNext.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent evt) {
                    setVisible(false);
                }
            });
            javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    setVisible(false);
                }
            });
            t.setRepeats(false);
            t.start();
            setLocationRelativeTo(parent);
            setSize(new Dimension(400, 100));
            setVisible(true);
        }
    }

    public static void main(String[] args) {
        JFrame frame = new ComboBoxTwo();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

@mKorbel:

Good Day!

Thanks for the response, I did try your code but I think this is only applicable for 2 comboboxes, my concerns is chaining 3 comboboxes with data from my db.

that's will be easiest as built two (chaining) JComboBox(es)

@mKorbel:

can you show me a simple chained 3 jcomboboxes w/ db connection? im really stuck with what im doing, only the first query is being shown in my 2nd combobox when the 3rd combobox are filled with data from db. thank you very much for your response.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.