【问题标题】:Go back in the class and get an attribute from another attribute回到类中,从另一个属性中获取一个属性
【发布时间】:2021-05-13 05:23:05
【问题描述】:

我有这个代码:

        ArrayList<Integer> codClub = new ArrayList<Integer>();
        for(Club club: clubs) {
           codClub.add(club.getCodClub()); //getCodeClub() simply returns an int value
        }
        ClubComboBox = new JComboBox(codClub.toArray());
        ClubComboBox.setToolTipText("Club");
        ClubComboBox.setBounds(160, 145, 86, 21);
        contentPane.add(ClubComboBox);

如您所见,我有一个带有整数值的 JComboBox。接下来在代码中,我使用一个带有整数参数的函数,并传递从 ComboBox 中选择的“codClub”。 但我想在组合框中显示俱乐部的名称,然后使用该名称返回“codClub”。那么有没有可能回到只有俱乐部名称的俱乐部类(“clubName”是Class Club中的String属性)并获得codClub?

【问题讨论】:

  • 1) 变量名不应以大写字符开头。 2) 不要使用空布局,也不要使用 setBounds(...)。 Swing 旨在与布局管理器一起使用。 2) 将自定义对象添加到包含“名称”和“id”的组合框中。然后您可以为用户显示“名称”并使用“id”访问俱乐部对象。见:Combo Box With Hidden Data

标签: java swing class attributes jcombobox


【解决方案1】:

是的,您可以在组合框中显示俱乐部名称而不是代码,因此您必须执行以下操作:

ArrayList<String> clubNames = new ArrayList<String>();
    for(Club club: clubs) {
       clubNames.add(club.getClubName()); 
    }
    ClubComboBox = new JComboBox(codClub.clubNames());
    ClubComboBox.setToolTipText("Club");
    ClubComboBox.setBounds(160, 145, 86, 21);
    contentPane.add(ClubComboBox);

您需要另一种方法来从 Club 类中获取您的 codClub,为此请尝试以下方法:

int getCodeFromClubName (String clubName){  
for(Club club: clubs) { 
if(club.getClubName().equals(clubName))
       return club.getCodClub()
                       }
return -1;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多