2011-06-05 4 views
3

J'essaie de combiner 2 jcombobox. 1 combobox est pour montrer la catégorie des dépenses. et deuxième combobox lit le fichier du fichier texte pour montrer les types de produits. Si je change de première combobox je voudrais que la seconde combobox change en fonction de ce que l'utilisateur sélectionne dans le premier.JCombobox changer un autre JCombobox

Est-il possible que je puisse toujours charger l'autre liste déroulante à partir de fichiers texte? Les sous-éléments ne seraient pas des tableaux mais les mêmes que précédemment, car ils se trouvent en bas du code de cboperson.

Code modifié:

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

appelez-vous loadDataToCboItem()? Vous devriez l'appeler soit à partir de votre méthode actionPerformed soit dans la méthode displaySelectedItem(). –

+0

S'il vous plaît modifier votre réponse plus. Le code est mal formaté et il n'est pas clair à quelle combobox les méthodes appartiennent. – toto2

Répondre

4

par exemple

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); 
    } 
} 
+0

Salut c'est parfait est-il une chance que les sous-éléments de la chaîne peuvent être tirés du fichier texte comme mes autres comboboxes ??? – Petr

+0

Ceci est parfait est-il une chance que je puisse les charger comme avant du fichier texte? loadDataToCboItem private void() { \t \t Scanner FileReader = new Scanner (getClass() getResourceAsStream ( \t \t \t \t itemChange).); \t \t try { \t \t \t DefaultComboBoxModel model = nouveau DefaultComboBoxModel(); \t \t \t tandis que (fileReader.hasNextLine()) { \t \t \t \t model.addElement (fileReader.nextLine()); \t \t \t} \t \t \t subComboBox.setModel (modèle); \t \t} enfin { \t \t \t fileReader.close(); \t \t} \t} et juste le changer en sous-éléments et y ajouter les fichiers texte ???? Merci beaucoup. – Petr

+0

@Petr: S'il vous plaît modifier votre question pour inclure de nouveaux exemples de code. Cela ressemble au petit-déjeuner d'un chien! –

1

D'une part, ne pas comparer des chaînes avec == mais plutôt d'utiliser les égaux ou méthode equalsIgnoreCase. par exemple,

Modifier ceci:

if (item == "Groceries") { 

à ceci:

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

Vous aurez envie d'appeler toString() sur le point pour vous assurer que vous comparez avec cordes String. Vous devez également vous assurer que cet élément n'est pas nul avant de faire cela.

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

ou vous pouvez inclure les éléments d'un tableau s'il est trop.