简体   繁体   中英

Java: Get List<> Items from one class into JComboBox of another class

Here's the thing:

I created a 'cocktailbar' software, and I have the following classes:

  • Cocktail,
  • CocktailBar,
  • CreateNewCPanel,
  • HelloPanel,
  • SearchCPanel,
  • ShowAllCPanel,
  • CocktailMixerGUI,
  • Ingredients.

Now: When adding a new Cocktail in the CreateNewCPanel , I add the cocktail to a List in the CocktailBar class.

Box buttonBox = Box.createHorizontalBox();
JButton speicherButton = new JButton("Speichern");
speicherButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e){
        neuerC.setCName(cName.getText());
        neuerC.fuegeZubereitungHinzu(zubereitungTextArea.getText());
        CocktailBar.addCocktail(neuerC);

Now I need to see all created cocktails in a 'dropdown' menu in the ShowAllCPanel . I've got the following:

//Adding the DropDown Menu, first a Box, then a ComboBox inside.
Box cDropDownBox = Box.createHorizontalBox();
cDropDownBox.add(Box.createHorizontalGlue());

JComboBox cChoose = new JComboBox();
groesseEinsetzen(cChoose, 500, 20);

cChoose.setAlignmentX(SwingConstants.LEFT);
cDropDownBox.add(cChoose);

But now I am wondering how do I get my List from the CocktailBar class into the ShowAllCPanel ?

edit: forgot to mention: i have a getter in the CocktailBar class, and i already tried:

        cChoose.addItem(CocktailBar.getCocktails());

within the comboBox in the ShowAllCPanel, but it doesnt show up anything in the dropdown.

thanks to @Do Re, i inserted this:

 //Adding the DropDown Menu, first a Box, then a ComboBox inside.
    Box cDropDownBox = Box.createHorizontalBox();
    cDropDownBox.add(Box.createHorizontalGlue());

    JComboBox cChoose = new JComboBox();

    if (CocktailBar.getCocktails() != null){

        for (Cocktail c : CocktailBar.getCocktails())
            cChoose.addItem(c);
    }

but still - when running, the dropdown list stays empty.

As you mentioned in the comments, you created a getter for the cocktails.

Try something like this

for (Coctail c : CocktailBar.getCocktails())
    cChoose.addItem(c);

This iterates over the list of cocktails and adds each item seperately rather than adding a list of Cocktails at once.

Edit

try

 cDropDownBox.revalidate();
 cDropDownBox.repaint();

or

cChoose.revalidate();
cChoose.repaint();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM