如何在java swing中将arraylist显示为单独的jlabels?

时间:2017-12-20 13:27:26

标签: java swing arraylist

我有一个城市名称的arraylist,我想把它们显示为自下而上的jlabels。我怎么能这样做?

   ArrayList<String> cityNames = new ArrayList<>(columnCount); 

                while(resultSet.next()){
                    int i = 1;
                       while(i <= columnCount) {
                           cityNames.add(resultSet.getString(i++));
                       }            
                }

                //Loop through cityNames as seperate Jlabels
            for(String city : cityNames){
                cityLabel.setText(city);
            }

1 个答案:

答案 0 :(得分:3)

创建多个JLabel并将其添加到面板

JPanel panel = [...];
ArrayList<String> cityNames = [...];

for(String city : cityNames)
    panel.add(new JLabel(city));

如果您以后需要对它们执行某些操作,请将它们添加到List

JPanel panel = [...];
ArrayList<String> cityNames = [...];
List<JLabel> cityLabels = new ArrayList<JLabel>();

for(String city : cityNames)
{
    JLabel label = new JLabel(city);
    cityLabels.add(label);
    panel.add(label);
}

如果您只想在一个JLabel (can be on multiple lines)

中使用所有城市名称
ArrayList<String> cityNames = [...];

String cities = "";
for(String city : cityNames)
    cities += ", " + city; //or use "<br>" for separate lines
cities = cities.substring(2); //remove the first ", "

JLabel cityLabel = new JLabel(cities); //add this to your rendering panel