4

I'm trying to combine 2 jcomboboxes. 1 combobox is for showing category of expences. and second combobox is reading file from text file to show types of products. If I change first combobox I would like that second combobox will change based on what user select in the first one.

Is there any chance that i can still load the other combobox from text files? That subitems would not be Arrays but same as before as it is on the bottom of the code to cboperson.

edited code:

private JComboBox cboCategory;
private JComboBox cboPerson;
private JComboBox cboItem;
public String itemChange = "groceries.txt";

public ExpenditureTracker() {......


    String[] items = {"Select Item", "Groceries", "Bills", "Travelling", "Leasure", "Other"};
    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);
    mainComboBox.setBounds(113, 138, 85, 20);
    importPanel.add(mainComboBox);


    subComboBox = new JComboBox();//  Create sub combo box with multiple models
    subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
    subComboBox.addItemListener(this);
    subComboBox.setBounds(113, 188, 85, 20);
    importPanel.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);
    String[] subItems4 = {"Select Fruit", "Apple", "Orange", "Banana"};
    subItems.put(items[4], subItems3);
    String[] subItems5 = {"Select Fruit", "Apple", "Orange", "Banana"};
    subItems.put(items[5], subItems3);


    loadDataTocboPerson();
}




private void loadDataToCboPerson() {
    Scanner fileReader = new Scanner(getClass().getResourceAsStream(
            itemChange));
    try {
        DefaultComboBoxModel model = new DefaultComboBoxModel();
        while (fileReader.hasNextLine()) {
            model.addElement(fileReader.nextLine());
        }
        cboItem.setModel(model);
    } finally {
        fileReader.close();
    }
}
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Petr
  • 73
  • 1
  • 7
  • are you calling the loadDataToCboItem()? You should call it either from yout actionPerformed method either in displaySelectedItem() method. – Adrian Ancuta Jun 05 '11 at 21:52
  • Please edit your answer some more. The code is poorly formatted and it's unclear to which combobox the methods belong. – toto2 Jun 05 '11 at 21:54

3 Answers3

5

for example

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 for ..... ");
                }
            } 
        }
    }

    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
  • 109,525
  • 20
  • 134
  • 319
  • Hi this is perfect is there any chance that the String subItems can be pulled from text file as my other comboboxes??? – Petr Jun 06 '11 at 01:47
  • This is perfect is there any chance that i can load them same as before from text file ? private void loadDataToCboItem() { Scanner fileReader = new Scanner(getClass().getResourceAsStream( itemChange)); try { DefaultComboBoxModel model = new DefaultComboBoxModel(); while (fileReader.hasNextLine()) { model.addElement(fileReader.nextLine()); } subComboBox.setModel(model); } finally { fileReader.close(); } } and just change it to subitems and add there the text files ???? thanks a lot. – Petr Jun 06 '11 at 01:51
  • @Petr: Please edit your question to include new code samples. That looks like a dog's breakfast! – Andrew Thompson Jun 06 '11 at 02:33
1

For one thing, don't compare Strings with == but rather use the equals or equalsIgnoreCase method. e.g.,

Change this:

if (item == "Groceries") {

to this:

if ("Groceries".equalsIgnoreCase(item.toString())) {

You'll want to call toString() on item to make sure that you compare String with String. You'll also want to make sure that item isn't null before doing any of this.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0
 if(jComboBox1.getSelectedItem() == "First Choice"){
   jComboBox2.removeAllItems();
   jComboBox2.addItem("First Choice Item 1");
 }
 if(jComboBox1.getSelectedItem() == "Another Choice"){
   jComboBox2.removeAllItems();
   jComboBox2.addItem("Another Choice Item 1");
 }

or you could include items in an array if it is too many.

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108