【问题标题】:Java: Get List<> Items from one class into JComboBox of another classJava:从一个类获取列表<>项到另一个类的JComboBox
【发布时间】:2016-05-27 10:41:17
【问题描述】:

事情是这样的:

我创建了一个“鸡尾酒吧”软件,我有以下课程:

  • 鸡尾酒,
  • 鸡尾酒吧,
  • 创建新CPanel,
  • HelloPanel,
  • 搜索CPanel,
  • ShowAllCPanel,
  • CocktailMixerGUI,
  • 成分。

现在:在CreateNewCPanel 中添加新的Cocktail 时,我将鸡尾酒添加到CocktailBar 类的列表中。

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

现在我需要在ShowAllCPanel 的“下拉”菜单中查看所有创建的鸡尾酒。我有以下内容:

//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);

但现在我想知道如何将我的列表从CocktailBar 类中获取到ShowAllCPanel

编辑:忘了提:我在 CocktailBar 类中有一个吸气剂,我已经尝试过:

        cChoose.addItem(CocktailBar.getCocktails());

在 ShowAllCPanel 的组合框中,但它不会在下拉列表中显示任何内容。

感谢@Do Re,我插入了这个:

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

但仍然 - 运行时,下拉列表保持为空。

【问题讨论】:

  • 您是否尝试过为列表创建getter
  • 是的,我忘了提...我试过了:cChoose.addItem(CocktailBar.getCocktails());但它似乎不起作用
  • getCocktails() 返回什么?错误是什么?
  • public static List getCocktails(){ 返回鸡尾酒; } 没有错误,只是组合框中什么都看不到
  • 在答案中查看我的编辑。

标签: java swing list jcombobox


【解决方案1】:

正如您在 cmets 中提到的,您为鸡尾酒创建了一个吸气剂。

试试这样的

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

这会遍历鸡尾酒列表并单独添加每个项目,而不是一次添加鸡尾酒列表。

编辑

试试

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

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

【讨论】:

  • 我应该把它放在哪里?我在将下拉框添加到标签之前尝试过,没有效果
猜你喜欢
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-15
相关资源
最近更新 更多